added user profile endpoint

deb
androiddrew 7 years ago
parent a52d431e0d
commit 3ef15e7b48

@ -1,12 +1,13 @@
import datetime as dt
from apistar import Component, Settings, http, Route, Include
from apistar import Component, Settings, http, Route, Include, annotate
from apistar.interfaces import Auth
from apistar.backends.sqlalchemy_backend import Session
from apistar_jwt.authentication import get_jwt
from apistar_jwt.authentication import get_jwt, JWTAuthentication
from apistar_jwt.token import JWT
from apistar_mail import Message, Mail
from sqlalchemy.exc import IntegrityError, InvalidRequestError
from sqlalchemy.orm.exc import NoResultFound
from cookie_api.models import User
@ -19,7 +20,16 @@ def login(settings: Settings, json_data: http.RequestData, session: Session):
user_id = json_data.get('email')
password = json_data.get('password')
user = session.query(User).filter_by(email=user_id).one()
try:
user = session.query(User).filter_by(email=user_id).one()
except NoResultFound:
error = {
'status': 'fail',
'message': 'User does not exist'
}
return http.Response(error, status=400, headers={'WWW-Authenticate': 'Bearer'})
if not user.check_password(password):
error = {'error': 'Password auth failed'},
return http.Response(error, status=401, headers={'WWW-Authenticate': 'Bearer'})
@ -27,9 +37,9 @@ def login(settings: Settings, json_data: http.RequestData, session: Session):
secret = settings['JWT'].get('SECRET')
payload = {
'exp': dt.datetime.utcnow() + dt.timedelta(days=0, minutes=60),
'iat': dt.datetime.utcnow(),
'sub': user.id
'exp': dt.datetime.utcnow() + dt.timedelta(days=0, minutes=60), # Expiration date of the token
'iat': dt.datetime.utcnow(), # the time the token was generated
'sub': user.id # the subject of the token
}
token = JWT.encode(payload, secret=secret)
@ -49,7 +59,7 @@ def logout():
# TODO Add user registration
def register(json_data: http.RequestData, session: Session, mail:Mail):
def register(json_data: http.RequestData, session: Session, mail: Mail):
user_id = json_data.get('email')
password = json_data.get('password')
@ -78,9 +88,14 @@ def register(json_data: http.RequestData, session: Session, mail:Mail):
return http.Response(message, status=200, headers=headers)
# TODO Add user profile endpoint
def user_profile():
pass
@annotate(authentication=[JWTAuthentication()])
def user_profile(auth: Auth, settings: Settings, session: Session):
token = JWT(token=auth.token, settings=settings)
user_id = token.payload.get('sub')
user = session.query(User).filter_by(id=user_id).one()
result = user.to_dict()
result.pop('password', None)
return result
# TODO Add email confirmation
@ -95,7 +110,8 @@ def reset():
routes = [
Route('/login', 'POST', login),
Route('/register', 'POST', register)
Route('/register', 'POST', register),
Route('/status', 'GET', user_profile)
]
auth_routes = [Include('/auth', routes)]

Loading…
Cancel
Save