def api(require_login=True, schema=None):
"""
Decorator for API requests.
Handles auth and adds the username as the first argument.
"""
if schema is not None:
Draft4Validator.check_schema(schema)
validator = Draft4Validator(schema)
else:
validator = None
def innerdec(f):
@wraps(f)
def wrapper(*args, **kwargs):
g.auth = Auth(PUBLIC, None)
user_agent_str = request.headers.get('user-agent', '')
g.user_agent = httpagentparser.detect(user_agent_str, fill_none=True)
if validator is not None:
try:
validator.validate(request.get_json(cache=True))
except ValidationError as ex:
raise ApiException(requests.codes.bad_request, ex.message)
auth = request.headers.get(AUTHORIZATION_HEADER)
g.auth_header = auth
if auth is None:
if require_login:
raise ApiException(requests.codes.unauthorized, "Not logged in")
else:
headers = {
AUTHORIZATION_HEADER: auth
}
try:
resp = requests.get(OAUTH_USER_API, headers=headers)
resp.raise_for_status()
data = resp.json()
# TODO(dima): Generalize this.
user = data.get('current_user', data.get('login'))
assert user
email = data['email']
g.auth = Auth(user, email)
except requests.HTTPError as ex:
if resp.status_code == requests.codes.unauthorized:
raise ApiException(
requests.codes.unauthorized,
"Invalid credentials"
)
else:
raise ApiException(requests.codes.server_error, "Server error")
except (ConnectionError, requests.RequestException) as ex:
raise ApiException(requests.codes.server_error, "Server error")
return f(*args, **kwargs)
return wrapper
return innerdec
评论列表
文章目录