Browse Source

preparing to use the token in a basic auth fashion

master
Julio Biason 11 years ago
parent
commit
b91308da21
  1. 8
      luncho/exceptions.py
  2. 23
      luncho/helpers.py

8
luncho/exceptions.py

@ -61,3 +61,11 @@ class ElementNotFoundException(LunchoException):
super(ElementNotFoundException, self).__init__()
self.status = 404
self.message = '{element} not found'.format(element=element_name)
class AuthorizationRequiredException(LunchoException):
"""The request requires auhtorization."""
def __init__(self):
super(AuthorizationRequiredException, self).__init__()
self.status = 412
self.message = 'Request requires authorization'

23
luncho/helpers.py

@ -6,7 +6,6 @@
from functools import wraps
from flask import request
from flask import jsonify
from luncho.server import User
@ -14,9 +13,11 @@ from luncho.exceptions import RequestMustBeJSONException
from luncho.exceptions import InvalidTokenException
from luncho.exceptions import MissingFieldsException
from luncho.exceptions import UserNotFoundException
from luncho.exceptions import AuthorizationRequiredException
class ForceJSON(object):
"""Decorator to check if the request is in JSON format."""
def __init__(self, required=None):
self.required = required or []
@ -40,6 +41,26 @@ class ForceJSON(object):
return check_json
class Auth(object):
"""Validate the token in the Basic Auth header."""
def __call__(self, func):
@wraps(func)
def check_auth(*args, **kwargs):
if not request.authorization:
raise AuthorizationRequiredException
token = request.authorization.username
user = User.query.filter_by(token=token).first()
if not user:
raise UserNotFoundException()
if not user.valid_token(token):
raise InvalidTokenException()
return func(*args, **kwargs)
def user_from_token(token):
"""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

Loading…
Cancel
Save