set up auth

This commit is contained in:
mungai-njoroge
2024-04-25 18:18:52 +03:00
parent b1de2c7321
commit 04957dd5a9
15 changed files with 350 additions and 6 deletions
+28 -4
View File
@@ -8,6 +8,7 @@ from flask_compress import Compress
from flask_openapi3 import Info
from flask_openapi3 import OpenAPI
from flask_jwt_extended import JWTManager
from app.settings import Keys
from .plugins import lyrics as lyrics_plugin
@@ -27,6 +28,7 @@ from app.api import (
logger,
home,
getall,
auth,
)
# TODO: Move this description to a separate file
@@ -60,13 +62,34 @@ def create_api():
app = OpenAPI(__name__, info=api_info, doc_prefix="/docs")
CORS(app, origins="*")
Compress(app)
# JWT CONFIGS
app.config["JWT_SECRET_KEY"] = Keys.JWT_SECRET_KEY
app.config["JWT_TOKEN_LOCATION"] = ["cookies"]
app.config["JWT_COOKIE_CSRF_PROTECT"] = False
app.config["JWT_ACCESS_TOKEN_EXPIRES"] = datetime.timedelta(days=1)
# CORS
CORS(app, origins="*", supports_credentials=True)
# RESPONSE COMPRESSION
Compress(app)
app.config["COMPRESS_MIMETYPES"] = [
"application/json",
]
# JWT
jwt = JWTManager(app)
@jwt.user_identity_loader
def user_identity_lookup(user):
return user
@jwt.user_lookup_loader
def user_lookup_callback(_jwt_header, jwt_data):
identity = jwt_data["sub"]
return identity
# Register all the API blueprints
with app.app_context():
app.register_api(album.api)
app.register_api(artist.api)
@@ -89,8 +112,9 @@ def create_api():
# Home
app.register_api(home.api)
# Flask Restful
app.register_api(getall.api)
# Auth
app.register_api(auth.api)
return app
+67
View File
@@ -0,0 +1,67 @@
from dataclasses import asdict
from flask import jsonify
from flask_jwt_extended import create_access_token, current_user, set_access_cookies
from pydantic import BaseModel, Field
from flask_openapi3 import Tag
from flask_openapi3 import APIBlueprint
from app.db.sqlite.auth import SQLiteAuthMethods as authdb
from app.utils.auth import check_password
bp_tag = Tag(name="Auth", description="Authentication")
api = APIBlueprint("auth", __name__, url_prefix="/auth", abp_tags=[bp_tag])
class LoginBody(BaseModel):
username: str = Field(description="The username", example="user0")
password: str = Field(description="The password", example="password0")
@api.post("/login")
def login(body: LoginBody):
"""
Authenticate using username and password
"""
res = jsonify({"msg": f"Logged in as {body.username}"})
user = authdb.get_user_by_username(body.username)
if user is None:
return {"msg": "User not found"}, 404
password_ok = check_password(body.password, user.password)
if not password_ok:
return {"msg": "Invalid password"}, 401
access_token = create_access_token(identity=user.todict())
set_access_cookies(res, access_token)
return res
@api.get("/logout")
def logout():
"""
Log out
"""
res = jsonify({"msg": "Logged out"})
res.delete_cookie("access_token_cookie")
return res
@api.get("/users")
def get_all_users():
"""
Get all users
"""
users = authdb.get_all_users()
return [user.todict_simplified() for user in users]
@api.route("/user")
def get_logged_in_user():
"""
Get logged in user
"""
print("current_user", current_user)
return dict(current_user)
+1
View File
@@ -162,6 +162,7 @@ mapp = {
@api.get("")
def get_all_settings():
"""
Get all settings