def get(self): if not current_user: raise InvalidUsage.user_not_found() user = current_user if user.type == "child": return user.parents else: raise InvalidUsage.unknown_error()
def post(self, name, surname, email, password, confirmPassword, **kwargs): if (password != confirmPassword): raise InvalidUsage.password_dont_match() try: user = Parent(name, surname, email, password, **kwargs).save().save() user.token = create_access_token(identity=user) except IntegrityError: db.session.rollback() raise InvalidUsage.user_already_registered() return user
def delete(self, post_id): user = current_user post = Post.get_one(post_id) if not post: raise InvalidUsage(404, 'Post not found') if post.owner_id != user.id: raise InvalidUsage(403, 'Permission denied') post.delete() return {'deleted': post.id}
def put(self, post_id, data): user = current_user post = Post.get_one(post_id) if not post: raise InvalidUsage(404, 'Post not found') if user.id != post.owner_id: raise InvalidUsage(403, 'Permission denied') post.update(**data) return post
def put(self, post_id, comment_id, data): post = Post.get_one(post_id) if not post: raise InvalidUsage(404, 'Post not found') comment = post.comments.filter_by(id=comment_id).first() if not comment: raise InvalidUsage(404, 'Comment not found') if comment.author_id != current_user.id: raise InvalidUsage(403, 'Permission denied') comment.update(**data) return comment
def delete(self, post_id, comment_id): post = Post.get_one(post_id) if not post: raise InvalidUsage(404, 'Post not found') comment = post.comments.filter_by(id=comment_id).first() if not comment: raise InvalidUsage(404, 'Comment not found') if comment.author_id != current_user.id: raise InvalidUsage(403, 'Permission denied') comment.delete() return {'deleted': comment.id}
def random_game(): """Pulls a game at random (given some parameters to choose the game from -- passed in via URL parameters). Query params: - free_only: If true, only free games are shown - players: The number of players in the party """ schema = ActivitySchema() # Validate our query param input: free_only = request.args.get('free_only', 'false') players = request.args.get('players') if not players: raise InvalidUsage( "Please pass in an integer value for the players query parameter") try: players = int(players) except ValueError: raise InvalidUsage("players must be an integer") if players < 1: raise InvalidUsage("players must be at least 1") # Pull IDs matching these conditions from the database: game_query = Activity.query # Find games such that min players <= players <= max_players # (max players can also be null in the case where a game has # a practically infinite # of players) game_query = game_query.filter( Activity.min_players <= players, or_(Activity.max_players >= players, column('max_players').is_(None))) # Add a filter against paid games if the user chooses: if free_only == 'true': game_query = game_query.filter(Activity.paid == False) # Get a list of primary key IDs representing the games: ids = [game.id for game in game_query.all()] # Then pick randomly from them: if len(ids) > 0: game = Activity.query.get(choice(ids)) return jsonify(game=schema.dump(game)), 200 else: return jsonify(message="No games found"), 404
def consume_suggestion(): """Pushes a game suggestion to the database. Expects a JSON payload conforming to the submission schema. """ # Perform validation on what we receive: schema = SubmissionSchema() input_json = request.get_json() if not input_json: return InvalidUsage("Please submit a game") # For any empty strings, set them to None so our # schema validation catches it: for key, value in input_json.items(): if input_json[key] == '': input_json[key] = None # Loading will perform validation checks -- if there's # a problem, we have a handler for this submission = schema.load(input_json) if submission['max_players'] == 0: submission['max_players'] = None # If we made it to this point, data passed validation checks # and we go ahead and try to submit to the database: try: db.session.add(Submission(**submission)) db.session.commit() return jsonify(message="Submission added successfully"), 200 except SQLAlchemyError: raise # we have a handler for this declared up top except Exception as e: current_app.logger.error(f'Issue saving submission: {e}') return jsonify(message="Internal server error"), 500
def delete(self, post_id): post = Post.get_one(post_id) if not post: raise InvalidUsage(404, 'Post not found') post.unfavorite(current_user) return post
def get(self): if current_user is not None: user = current_user user.token = request.headers.environ['HTTP_AUTHORIZATION'].split( 'Token ')[1] return current_user else: raise InvalidUsage.user_not_found()
def get(self, post_id): post = Post.get_one(post_id) if not post: raise InvalidUsage(404, 'Post not found') comments = post.comments. \ order_by(Comment.created_at.desc()) return comments
def post(self, post_id, data): post = Post.get_one(post_id) if not post: raise InvalidUsage(404, 'Post not found') comment = Comment(post_id=post.id, author_id=current_user.id, **data) comment.save() return comment
def delete(self): if current_user.type == 'parent': current_user.children = [] db.session.delete(current_user) db.session.commit() return 200 else: raise InvalidUsage.unknown_error()
def post(self, email, password, **kwargs): user = User.query.filter_by(email=email).first() if user is not None and user.check_password(password): user.token = create_access_token(identity=user, fresh=True) user.update(last_seen=dt.datetime.utcnow()) return user else: raise InvalidUsage.user_not_found()
def post(self, data): user = User.get_by_email(data['email']) if not user or not user.check_hash(data['password']): raise InvalidUsage(403, 'Invalid credentials') token = create_access_token(identity=user) user.token = token return user
def get(self, username): user = User.get_by_username(username) if not user: raise InvalidUsage(404, 'User not found') posts = user.favorites. \ order_by(Post.created_at.desc()) return posts
def put(self, ehrid, **kwargs): try: user = current_user child = Child.query.filter_by(ehrid=ehrid).first() child.update(**kwargs) db.session.commit() except IntegrityError: db.session.rollback() raise InvalidUsage.user_already_registered() return user
def get(self, username): user = User.get_by_username(username) if not user: raise InvalidUsage(404, 'User not found') posts = user.posts. \ order_by(Post.created_at.desc()). \ filter_by(owner_id=user.id) return posts
def post(self, data): user_in_db = User.get_by_email(data['email']) if user_in_db: raise InvalidUsage(400, 'Email already registered') user = User(**data) user.save() token = create_access_token(identity=user) return {'token': token, 'username': user.username}, 201
def post(self): timer = request.args['timer'] if timer == 'null': current_user.timer = None else: current_user.timer = dt.datetime.strptime(timer, '%Y-%m-%dT%H:%M:%S') try: db.session.commit() except IntegrityError: db.session.rollback() raise InvalidUsage.unknown_error() return timer
def decorated(*args, **kwargs): if current_app.config['ADMIN_OFF']: raise InvalidUsage("Private endpoints have been turned off", status_code=501) # Get token from Authorization: Bearer <Token> header token = get_token_auth_header() # Look through known JSON Web Key Sets: known_req = requests.get( f'https://{os.getenv("AUTH0_DOMAIN")}/.well-known/jwks.json') jwks = known_req.json() unverified_header = jwt.get_unverified_header(token) rsa_key = {} for key in jwks["keys"]: if key["kid"] == unverified_header["kid"]: rsa_key = { "kty": key["kty"], "kid": key["kid"], "use": key["use"], "n": key["n"], "e": key["e"] } if rsa_key: try: payload = jwt.decode(token, rsa_key, algorithms=["RS256"], audience=os.getenv('AUTH0_API_AUDIENCE'), issuer="https://" + os.getenv('AUTH0_DOMAIN') + "/") except jwt.ExpiredSignatureError: raise AuthError("Authorization token expired") except jwt.JWTClaimsError: raise AuthError("Incorrect claims") except Exception: raise AuthError("Authorization failed") return f(*args, **kwargs, current_user=payload) raise AuthError("Unable to find required key")
def post(self, name, surname, email, password, confirmPassword, dateofbirth, gender, disease, diseaseInfo, **kwargs): if (password != confirmPassword): raise InvalidUsage.password_dont_match() if not current_user: raise InvalidUsage.user_not_found() r = requests.post(apiurl + 'ehr', auth=HTTPBasicAuth( current_app.config['EHR_USER'], current_app.config['EHR_USER_PASS'])) if r.status_code == 201: body = { "firstNames": name, "lastNames": surname, "gender": gender, "dateOfBirth": dateofbirth.isoformat(), "partyAdditionalInfo": [{ "key": "ehrId", "value": r.json()['ehrId'] }, { "key": "disease", "value": disease }] } if disease == 'DIABETES': body['partyAdditionalInfo'].append({ "key": "intendedMeasurements/Day", "value": diseaseInfo["measurements"] }) body['partyAdditionalInfo'].append({ "key": "SU_LO", "value": diseaseInfo["SU_LO"] }) body['partyAdditionalInfo'].append({ "key": "SU_HI", "value": diseaseInfo["SU_HI"] }) if disease == 'OBESITY': body['partyAdditionalInfo'].append({ "key": "goalweight", "value": diseaseInfo["goalweight"] }) party = requests.post(apiurl + '/demographics/party', json=body, auth=HTTPBasicAuth( current_app.config['EHR_USER'], current_app.config['EHR_USER_PASS'])) print(party) print(party.status_code) if party.status_code == 201: try: ehrid = r.json()['ehrId'] child = Child(name, surname, email, password, current_user, ehrid, **kwargs) db.session.add(child) db.session.commit() return child except IntegrityError: db.session.rollback() raise InvalidUsage.user_already_registered() raise InvalidUsage.unknown_error()
def get(self, username): user = User.get_by_username(username) if not user: raise InvalidUsage(404, 'User not found') return user
def get(self, post_id): post = Post.get_one(post_id) if not post: raise InvalidUsage(404, 'Post not found') return post