mirror of
https://github.com/DarrylNixon/ghostforge
synced 2024-04-22 06:27:20 -07:00
77 lines
2.4 KiB
Python
77 lines
2.4 KiB
Python
import os
|
|
import uuid
|
|
from typing import Optional
|
|
|
|
from fastapi import APIRouter
|
|
from fastapi import Depends
|
|
from fastapi import Request
|
|
from fastapi_users import BaseUserManager
|
|
from fastapi_users import FastAPIUsers
|
|
from fastapi_users import schemas
|
|
from fastapi_users import UUIDIDMixin
|
|
from fastapi_users.authentication import AuthenticationBackend
|
|
from fastapi_users.authentication import BearerTransport
|
|
from fastapi_users.authentication import CookieTransport
|
|
from fastapi_users.authentication import JWTStrategy
|
|
from fastapi_users_db_sqlmodel import SQLModelUserDatabase
|
|
|
|
from ghostforge.db import get_user_db
|
|
from ghostforge.db import User
|
|
|
|
|
|
SECRET = os.environ.get("GHOSTFORGE_JWT_SECRET")
|
|
|
|
gf = APIRouter()
|
|
|
|
|
|
class UserRead(schemas.BaseUser[uuid.UUID]):
|
|
pass
|
|
|
|
|
|
class UserCreate(schemas.BaseUserCreate):
|
|
pass
|
|
|
|
|
|
class UserUpdate(schemas.BaseUserUpdate):
|
|
pass
|
|
|
|
|
|
class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
|
|
reset_password_token_secret = SECRET
|
|
verification_token_secret = SECRET
|
|
|
|
async def on_after_register(self, user: User, request: Optional[Request] = None):
|
|
print(f"User {user.id} has registered.")
|
|
|
|
async def on_after_forgot_password(self, user: User, token: str, request: Optional[Request] = None):
|
|
print(f"User {user.id} has forgot their password. Reset token: {token}")
|
|
|
|
async def on_after_request_verify(self, user: User, token: str, request: Optional[Request] = None):
|
|
print(f"Verification requested for user {user.id}. Verification token: {token}")
|
|
|
|
|
|
async def get_user_manager(user_db: SQLModelUserDatabase = Depends(get_user_db)):
|
|
yield UserManager(user_db)
|
|
|
|
|
|
bearer_transport = BearerTransport(tokenUrl="auth/jwt/login")
|
|
cookie_transport = CookieTransport(cookie_httponly=True, cookie_name="ghostforge", cookie_samesite="strict")
|
|
|
|
|
|
def get_jwt_strategy() -> JWTStrategy:
|
|
return JWTStrategy(secret=SECRET, lifetime_seconds=604800)
|
|
|
|
|
|
jwt_backend = AuthenticationBackend(
|
|
name="jwt",
|
|
transport=bearer_transport,
|
|
get_strategy=get_jwt_strategy,
|
|
)
|
|
|
|
web_backend = AuthenticationBackend(name="cookie", transport=cookie_transport, get_strategy=get_jwt_strategy)
|
|
|
|
fastapi_users = FastAPIUsers[User, uuid.UUID](get_user_manager, [web_backend, jwt_backend])
|
|
|
|
|
|
def get_current_user(active: bool = True, optional: bool = False) -> User:
|
|
return fastapi_users.current_user(active=active, optional=optional)
|