CS_TA / scripts /provision_grading_accounts.py
zzhang2816's picture
Upload 12 files
78494de verified
Raw History Blame Contribute Delete
4.69 kB
#!/usr/bin/env python3
"""Create permanent-password Cognito grading users and seed the local EC2 database."""
from __future__ import annotations
import argparse
import json
import os
import secrets
import subprocess
from pathlib import Path
import boto3
def private_json(path: Path, value: dict):
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
os.fchmod(fd, 0o600)
with os.fdopen(fd, 'w') as stream:
json.dump(value, stream, indent=2)
stream.write('\n')
def account(client, pool: str, username: str, group: str):
try:
client.admin_create_user(UserPoolId=pool, Username=username,
UserAttributes=[{'Name': 'email', 'Value': username},
{'Name': 'email_verified', 'Value': 'true'}],
MessageAction='SUPPRESS')
except client.exceptions.UsernameExistsException:
pass
password = 'Aa1!' + secrets.token_urlsafe(24)
client.admin_set_user_password(UserPoolId=pool, Username=username,
Password=password, Permanent=True)
other = 'patient' if group == 'doctor' else 'doctor'
try:
client.admin_remove_user_from_group(UserPoolId=pool, Username=username, GroupName=other)
except client.exceptions.ResourceNotFoundException:
pass
client.admin_add_user_to_group(UserPoolId=pool, Username=username, GroupName=group)
user = client.admin_get_user(UserPoolId=pool, Username=username)
sub = next(x['Value'] for x in user['UserAttributes'] if x['Name'] == 'sub')
return password, sub
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--region', required=True)
parser.add_argument('--user-pool-id', required=True)
parser.add_argument('--app-client-id', required=True)
parser.add_argument('--base-url', required=True, help='Public site origin, e.g. http://EC2_PUBLIC_IP')
parser.add_argument('--doctor-email', required=True)
parser.add_argument('--alice-email', required=True)
parser.add_argument('--bob-email', required=True)
parser.add_argument('--student-id', default='')
args = parser.parse_args()
emails = [args.doctor_email, args.alice_email, args.bob_email]
if len(set(emails)) != 3:
parser.error('Doctor, Alice, and Bob must have distinct emails')
client = boto3.client('cognito-idp', region_name=args.region)
app_client = client.describe_user_pool_client(UserPoolId=args.user_pool_id,
ClientId=args.app_client_id)['UserPoolClient']
if app_client.get('ClientSecret'):
parser.error('App client must be public, without a secret')
if 'ALLOW_USER_PASSWORD_AUTH' not in app_client.get('ExplicitAuthFlows', []):
parser.error('App client must support ALLOW_USER_PASSWORD_AUTH')
for group in ('doctor', 'patient'):
try:
client.create_group(UserPoolId=args.user_pool_id, GroupName=group)
except client.exceptions.GroupExistsException:
pass
specs = [('doctor', args.doctor_email, 'doctor', None, None),
('alice', args.alice_email, 'patient', 'P1001', 'Alice'),
('bob', args.bob_email, 'patient', 'P1002', 'Bob')]
accounts, seed = {}, []
for label, email, role, patient_id, name in specs:
password, sub = account(client, args.user_pool_id, email, role)
accounts[label] = {'username': email, 'password': password}
if patient_id:
accounts[label]['patient_id'] = patient_id
seed.append({'sub': sub, 'role': role, 'patient_id': patient_id, 'name': name})
subprocess.run(['docker', 'compose', 'exec', '-T', 'api', 'python',
'/app/scripts/seed_accounts.py'], input=json.dumps(seed),
text=True, check=True)
origin = args.base_url.rstrip('/')
submission = {'base_url': origin + '/api', 'web_url': origin + '/',
'student_id': args.student_id, 'region': args.region,
'user_pool_id': args.user_pool_id, 'app_client_id': args.app_client_id,
'accounts': {label: {'username': value['username'],
**({'patient_id': value['patient_id']} if 'patient_id' in value else {})}
for label, value in accounts.items()}}
Path('submission.json').write_text(json.dumps(submission, indent=2) + '\n')
private_json(Path('private_accounts.json'), accounts)
print('Wrote submission.json (non-secret) and private_accounts.json (mode 0600).')
print('Each run resets all three passwords. Send the private file only via Canvas private submission.')
if __name__ == '__main__':
main()