From 3fd746916c0400e95475b5da2d06f2a6696829d3 Mon Sep 17 00:00:00 2001 From: Alexis Lahouze Date: Wed, 13 Jan 2016 12:57:27 +0100 Subject: [PATCH] Change authentication algorithm. --- accountant/api/views/users.py | 42 +++++++++++------------------------ 1 file changed, 13 insertions(+), 29 deletions(-) diff --git a/accountant/api/views/users.py b/accountant/api/views/users.py index d1593eb..1392c3a 100644 --- a/accountant/api/views/users.py +++ b/accountant/api/views/users.py @@ -22,10 +22,6 @@ from functools import wraps from flask import request, g from flask.ext.restful import Resource, fields, reqparse, marshal_with, marshal_with_field -from sqlalchemy.orm.exc import NoResultFound - -from werkzeug.exceptions import BadRequest - from accountant import app from .. import api @@ -44,27 +40,6 @@ def load_user_from_auth(auth): return load_user_from_token(token) -def load_user_from_request(): - # No token found, trying to authenticate using request data. - try: - data = parser.parse_args() - - try: - user = User.query().filter( - User.email == data['email'] - ).one() - - if user and user.verify_password(data['password']): - return user - - except NoResultFound: - pass - except BadRequest: - pass - - return None - - def authenticate(): return {'error': 'Please login before executing this request.'}, 401 @@ -72,11 +47,11 @@ def authenticate(): def requires_auth(f): @wraps(f) def wrapped(*args, **data): + user = None + if 'Authorization' in request.headers: auth = request.headers['Authorization'] user = load_user_from_auth(auth) - else: - user = load_user_from_request() if user: g.user = user @@ -104,10 +79,19 @@ parser.add_argument('password', type=str, required=True) class LoginResource(Resource): - @requires_auth @marshal_with(token_resource_fields) def post(self): - user = g.user + """ + Login to retrieve authentication token. + """ + data = parser.parse_args() + + user = User.query().filter( + User.email == data['email'] + ).one_or_none() + + if not user or not user.verify_password(data['password']): + authenticate() token = user.generate_auth_token() expiration_time = arrow.now().replace(