Skip to content

Commit

Permalink
Create login resource
Browse files Browse the repository at this point in the history
  • Loading branch information
campb303 committed Jun 16, 2021
1 parent a4a669b commit 86ec831
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/webqueue2api/api/resources/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .login import Login
51 changes: 51 additions & 0 deletions src/webqueue2api/api/resources/login.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
from flask import request, after_this_request
from flask_restful import Resource
from flask_jwt_extended import create_access_token, create_refresh_token, set_refresh_cookies
from ..auth import user_is_valid



class Login(Resource):
def post(self) -> tuple:
"""Validates username/password, sets refresh token cookie and returns access token.
Return Codes:
200 (OK): On success.
401 (Unauthroized): When username or password are incorrect.
422 (Unprocessable Entitiy): When the username or password can't be parsed.
Example:
curl -X POST
-H "Content-Type: application/json"
-d '{"username": "bob", "password": "super_secret"}'
{ "access_token": fjr09hfp09h932jp9ruj3.3r8ihf8h0w8hr08ifhj804h8i.8h48ith08ity409hip0t4 }
Returns:
tuple: Response containing tokens and HTTP response code.
"""
if not request.is_json:
return ({ "message": "JSON missing from request body"}, 422)

data = request.json

fields_to_check = ["username", "password"]
for field in fields_to_check:
if field not in data.keys():
return ({ "message": f"{field} missing from request body"}, 422)

if not user_is_valid(data["username"], data["password"]):
return ({ "message": "Username or password is invalid"}, 401)

access_token = create_access_token(data["username"])
refresh_token = create_refresh_token(data["username"])

# This decorator is needed because Flask-RESTful's 'resourceful routing`
# doesn't allow for direct modification to the Flask response object.
# See: https://flask-restful.readthedocs.io/en/latest/quickstart.html#resourceful-routing
@after_this_request
def set_refresh_cookie_callback(response):
set_refresh_cookies(response, refresh_token)
return response

return ({ "access_token": access_token }, 200)

0 comments on commit 86ec831

Please sign in to comment.