From b91308da21d94c278b30d62f25f73de13393d383 Mon Sep 17 00:00:00 2001 From: Julio Biason Date: Thu, 3 Apr 2014 13:21:44 -0300 Subject: [PATCH] preparing to use the token in a basic auth fashion --- luncho/exceptions.py | 8 ++++++++ luncho/helpers.py | 23 ++++++++++++++++++++++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/luncho/exceptions.py b/luncho/exceptions.py index 0214c1f..81dbce4 100644 --- a/luncho/exceptions.py +++ b/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' diff --git a/luncho/helpers.py b/luncho/helpers.py index f1c9e2a..dcbbcec 100644 --- a/luncho/helpers.py +++ b/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