university-final-iot-backend/app/api/resources/token.py

28 lines
872 B
Python
Raw Normal View History

from flask_restful import Resource, abort
from webargs import fields
from webargs.flaskparser import use_args
2018-05-07 14:13:07 +00:00
from flasgger import swag_from
2018-05-06 19:42:21 +00:00
import app.accounts as accounts
class TokenResource(Resource):
user_args = {
'user': fields.Nested({
2018-05-07 12:10:20 +00:00
'username': fields.Str(required=True),
'password': fields.Str(required=True)
}, required=True, location='json')
2018-05-06 19:42:21 +00:00
}
@use_args(user_args)
2018-05-07 14:13:07 +00:00
@swag_from('swagger/create_token_spec.yaml')
def post(self, args):
2018-05-06 19:42:21 +00:00
try:
args = args['user']
2018-05-06 19:42:21 +00:00
token = accounts.create_token(
args['username'],
args['password'])
if token:
return {'status': 'success', 'token': token}, 200
2018-05-06 19:42:21 +00:00
except ValueError:
abort(401, message='Invalid credentials', status='error')