added login route for jwt authentication
parent
b317c8f4c2
commit
819496853f
@ -0,0 +1,55 @@
|
||||
import datetime as dt
|
||||
import json
|
||||
from apistar import Component, Settings, http, Route, Include
|
||||
from apistar.backends.sqlalchemy_backend import Session
|
||||
from apistar_jwt.authentication import get_jwt
|
||||
from apistar_jwt.token import JWT
|
||||
|
||||
from .models.schema import User
|
||||
|
||||
# /auth/register
|
||||
# /auth/login
|
||||
# /auth/logout
|
||||
# /auth/user
|
||||
|
||||
auth_components = [
|
||||
Component(JWT, init=get_jwt)
|
||||
]
|
||||
|
||||
|
||||
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()
|
||||
if not user.check_password(password):
|
||||
error = {'error': 'Password auth failed'},
|
||||
return http.Response(error, status=401, headers={'WWW-Authenticate': 'Bearer'})
|
||||
|
||||
SECRET = settings['JWT'].get('SECRET')
|
||||
|
||||
payload = {
|
||||
'exp': dt.datetime.utcnow() + dt.timedelta(days=0, seconds=5),
|
||||
'iat': dt.datetime.utcnow(),
|
||||
'sub': user.id
|
||||
}
|
||||
|
||||
token = JWT.encode(payload, secret=SECRET)
|
||||
|
||||
data = {
|
||||
'status': 'success',
|
||||
'message': 'Successfully logged in.',
|
||||
'auth_token': token
|
||||
}
|
||||
|
||||
headers = {
|
||||
'Authorization': 'Bearer {}'.format(token)
|
||||
}
|
||||
return http.Response(data, status=200, headers=headers)
|
||||
|
||||
|
||||
routes = [
|
||||
Route('/login', 'POST', login)
|
||||
]
|
||||
|
||||
auth_routes = [Include('/auth', routes)]
|
Loading…
Reference in New Issue