2016-01-13 13:49:28 +01:00

114 lines
2.8 KiB
Python

"""
This file is part of Accountant.
Accountant is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Accountant is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Accountant. If not, see <http://www.gnu.org/licenses/>.
"""
# vim: set tw=80 ts=4 sw=4 sts=4:
import arrow
from functools import wraps
from flask import request, g
from flask.ext.restful import Resource, fields, reqparse, marshal_with, marshal_with_field
from accountant import app
from .. import api
from ..fields import Object
from ..models.users import User
def load_user_from_token(token):
return User.verify_auth_token(token)
def load_user_from_auth(auth):
token = auth.replace('Bearer ', '', 1)
return load_user_from_token(token)
def authenticate():
return {'error': 'Please login before executing this request.'}, 401
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)
if user:
g.user = user
return f(*args, **data)
return authenticate()
return wrapped
token_model = {
'token': fields.String,
'expiration': fields.DateTime(dt_format='iso8601'),
'token_type': fields.String
}
user_model = {
'id': fields.Integer(default=None),
'email': fields.String,
'active': fields.Boolean
}
parser = reqparse.RequestParser()
parser.add_argument('email', type=str, required=True)
parser.add_argument('password', type=str, required=True)
class LoginResource(Resource):
@marshal_with(token_model)
def post(self):
"""
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(
seconds=app.config['SESSION_TTL']
)
return {
'token': token,
'expiration': expiration_time.datetime,
'token_type': 'Bearer'
}, 200
@requires_auth
@marshal_with_field(Object(user_model))
def get(self):
return g.user, 200
api.add_resource(LoginResource, "/user/login")