zcash-grant-system/backend/grant/utils/auth.py

66 lines
2.0 KiB
Python
Raw Normal View History

import ast
import json
2018-09-10 09:55:26 -07:00
from functools import wraps
import requests
2018-12-14 11:36:22 -08:00
from flask_security.core import current_user
2018-09-10 09:55:26 -07:00
from flask import request, g, jsonify
import sentry_sdk
2018-09-10 09:55:26 -07:00
2018-12-14 11:36:22 -08:00
from grant.settings import SECRET_KEY
2018-11-07 11:19:12 -08:00
from ..proposal.models import Proposal
from ..user.models import User
2018-09-10 09:55:26 -07:00
2018-12-14 11:36:22 -08:00
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
2018-12-14 11:36:22 -08:00
if not current_user.is_authenticated:
return jsonify(message="Authentication is required to access this resource"), 401
g.current_user = current_user
with sentry_sdk.configure_scope() as scope:
scope.user = {
"id": current_user.id,
}
return f(*args, **kwargs)
return decorated
2018-11-07 11:19:12 -08:00
2018-12-14 11:36:22 -08:00
2018-11-07 11:19:12 -08:00
def requires_same_user_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
2018-12-14 11:36:22 -08:00
user_id = kwargs["user_id"]
if not user_id:
return jsonify(message="Decorator requires_same_user_auth requires path variable <user_id>"), 500
2018-11-07 11:19:12 -08:00
2018-12-14 11:36:22 -08:00
user = User.get_by_id(user_id=user_id)
if not user:
2018-12-14 11:36:22 -08:00
return jsonify(message="Could not find user with id {}".format(user_id)), 403
if user.id != g.current_user.id:
2018-11-07 11:19:12 -08:00
return jsonify(message="You are not authorized to modify this user"), 403
2018-11-07 11:19:12 -08:00
return f(*args, **kwargs)
2018-12-14 11:36:22 -08:00
return requires_auth(decorated)
2018-11-07 11:19:12 -08:00
2018-11-07 11:19:12 -08:00
def requires_team_member_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
proposal_id = kwargs["proposal_id"]
if not proposal_id:
return jsonify(message="Decorator requires_team_member_auth requires path variable <proposal_id>"), 500
proposal = Proposal.query.filter_by(id=proposal_id).first()
if not proposal:
return jsonify(message="No proposal exists with id {}".format(proposal_id)), 404
2018-11-07 11:19:12 -08:00
if not g.current_user in proposal.team:
return jsonify(message="You are not authorized to modify this proposal"), 403
g.current_proposal = proposal
return f(*args, **kwargs)
2018-12-14 11:36:22 -08:00
return requires_auth(decorated)