def patch(cls, event: dict, context) -> dict: logger.info('Starting to patch a user') if event.get('body'): user_id: str = event.get('pathParameters').get('user_id') try: user: UserModel = UserModel.get(user_id) patch_partial_params: dict = UserSchemaPatch( unknown=marshmallow.EXCLUDE).loads(event.get('body')) user.update(actions=[ getattr(UserModel, attr).set(value) for attr, value in patch_partial_params.items() ]) response: dict = { 'statusCode': 200, 'body': json.dumps({ 'message': 'User was patched successful', 'user': UserSchemaGet().dump(UserModel.get(user_id)) }) } logger.info('User was patched successful') except UserModel.DoesNotExist: response: dict = { 'statusCode': 404, 'body': json.dumps({ 'message': json.dumps('User does not exist'), }) } logger.info('User does not exist') except marshmallow.exceptions.ValidationError as err: response: dict = { 'statusCode': 400, 'body': json.dumps(err.messages) } logger.warning('Invalid data') else: response: dict = { 'statusCode': 400, 'body': json.dumps('Request body is empty') } logger.error('Request body is empty') return response
def get(cls, event: dict, context) -> dict: user_id: str = event.get('pathParameters').get('user_id') try: user: UserModel = UserModel.get(user_id) response: dict = { 'statusCode': 200, 'body': json.dumps(UserSchemaGet().dump(user)) } except UserModel.DoesNotExist: response: dict = { 'statusCode': 404, 'body': json.dumps({'message': 'User not found'}) } return response
def create_session(): token = parse_request_parameter(request, 'token') # check valid token req = transport_requests.Request() claims = google.oauth2.id_token.verify_firebase_token(token, req) if not claims: return 'Unauthorized', 401 # check authorized users email = claims["email"] authorized_users = get_config("authorized_users") ok = False for au in authorized_users: ok = ok or (au["email"] == email) if not ok: return 'Unauthorized', 401 # create user if not exist user_id = email um = UserModel.get(user_id) if um is None: name = email if "name" in claims: name = claims["name"] screen_name = re.sub(r"@.*", "", email) um = UserModel.from_dict({ "user_id": user_id, "name": name, "email": email, "screen_name": screen_name, }) um.put() # create session session_id = get_random_str("session_") sm = SessionModel.from_dict({ "session_id": session_id, "user_id": user_id, "screen_name": um.screen_name, "created_at": utcnow() }) sm.put() # todo: session cache return jsonify({"session": session_id})
def delete(cls, event: dict, context) -> dict: user_id: str = event.get('pathParameters').get('user_id') try: user: UserModel = UserModel.get(user_id) deleted_user: dict = UserSchemaGet().dump(user) user.delete() response: dict = { 'statusCode': 204, 'body': json.dumps({ 'message': 'User was deleted successful', 'user': deleted_user }) } except UserModel.DoesNotExist: response: dict = { 'statusCode': 404, 'body': json.dumps({'message': 'User not found'}) } return response