MISC <<
Previous Next >> Webots
GW
Google Workspace 應用:
https://edu.google.com/intl/ALL_tw/workspace-for-education/editions/overview/
使用 Python + Flask 建立一個網頁介面,讓管理員透過網頁表單自動在 Google Workspace(前 G Suite)中建立新的 email address(即新增用戶)。
必備條件:
1. Google Workspace 管理員權限:你必須擁有管理員帳號才能新增使用者。
2. Google Cloud Platform 專案:你需要在 GCP 建立一個專案並啟用 [Admin SDK API](https://console.developers.google.com/apis/library/admin.googleapis.com)。
3. 建立服務帳戶(Service Account)並授權 Domain-wide Delegation:這樣 Flask 應用就能以管理員身分進行操作。
4. 下載服務帳戶金鑰(JSON):Flask 會用這個來驗證。
5. 設定 Google Workspace 的管理員 Email:Flask 會用於 impersonate。
安裝模組:
pip install flask google-api-python-client google-auth google-auth-oauthlib google-auth-httplib2
範例程式:
from flask import Flask, request, render_template_string
from google.oauth2 import service_account
from googleapiclient.discovery import build
app = Flask(__name__)
# 服務帳戶金鑰路徑
SERVICE_ACCOUNT_FILE = 'path/to/your/service-account.json'
# 管理員 email
ADMIN_EMAIL = 'admin@yourdomain.com'
@app.route('/', methods=['GET', 'POST'])
def index():
msg = ''
if request.method == 'POST':
user_email = request.form['email']
password = request.form['password']
first_name = request.form['first_name']
last_name = request.form['last_name']
# 建立新使用者
result = create_google_user(user_email, password, first_name, last_name)
msg = '帳號建立成功' if result else '建立失敗'
return render_template_string("""
<form method="post">
Email: <input name="email"><br>
密碼: <input name="password"><br>
名: <input name="first_name"><br>
姓: <input name="last_name"><br>
<button type="submit">建立</button>
</form>
<p>{{ msg }}</p>
""", msg=msg)
def create_google_user(email, password, first_name, last_name):
SCOPES = ['https://www.googleapis.com/auth/admin.directory.user']
creds = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
delegated_creds = creds.with_subject(ADMIN_EMAIL)
service = build('admin', 'directory_v1', credentials=delegated_creds)
user_info = {
"primaryEmail": email,
"password": password,
"name": {
"givenName": first_name,
"familyName": last_name
}
}
try:
service.users().insert(body=user_info).execute()
return True
except Exception as e:
print(e)
return False
if __name__ == '__main__':
app.run(debug=True)
注意事項:
1. 服務帳戶要開啟「網域範圍授權」(Domain-wide Delegation),管理員要在 Google Workspace 控制台授權該服務帳戶操作指定的範圍。
3. 密碼建議強度:可以加強密碼生成與驗證。
4. 部署建議:請勿將服務帳戶金鑰暴露於公開網路。
5. 安全性:建議加入認證機制,避免未授權使用。
MISC <<
Previous Next >> Webots