Lunching for groups.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.7 KiB

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""Helper functions."""
from functools import wraps
from flask import request
from flask import jsonify
11 years ago
from luncho.server import User
from luncho.exceptions import RequestMustBeJSONException
from luncho.exceptions import InvalidTokenException
from luncho.exceptions import MissingFieldsException
from luncho.exceptions import UserNotFoundException
11 years ago
class ForceJSON(object):
def __init__(self, required=None):
self.required = required or []
def __call__(self, func):
@wraps(func)
def check_json(*args, **kwargs):
json = request.get_json(force=True, silent=True)
if not json:
raise RequestMustBeJSONException()
# now we have the JSON, let's check if all the fields are here.
missing = []
11 years ago
for field in self.required or []:
if not field in json:
missing.append(field)
if missing:
raise MissingFieldsException(missing)
return func(*args, **kwargs)
return check_json
def user_from_token(token):
11 years ago
"""Returns a tuple with the user that owns the token and the error. If the
token is valid, user will have the user object and error will be None; if
there is something wrong with the token, the user will be None and the
error will have a Response created with :py:func:`JSONError`.
:param token: The token received
:type token: str
:return: Tuple with the user and the error."""
user = User.query.filter_by(token=token).first()
if not user:
raise UserNotFoundException()
11 years ago
if not user.valid_token(token):
raise InvalidTokenException()
11 years ago
return user