mirror of
https://github.com/lorsanstand/Aether.git
synced 2026-09-18 14:18:20 +03:00
refractor structure project and add user endpoint
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from jose import jwt, JWTError
|
||||
|
||||
from app.utils.OAuth2WithCookie import OAuth2PasswordBearerWithCookie
|
||||
from app.core.config import settings
|
||||
from app.users.models import UserModel
|
||||
from app.users.service import UserService
|
||||
from app.core.exceptions import InvalidTokenException
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
oauth2_scheme = OAuth2PasswordBearerWithCookie(tokenUrl="/api/v1/auth/login")
|
||||
|
||||
async def get_current_user(token: str = Depends(oauth2_scheme)) -> Optional[UserModel]:
|
||||
try:
|
||||
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=settings.ALGORITHM)
|
||||
user_id = int(payload.get("sub"))
|
||||
log.debug("Successfully get current_user id", extra={"user_id": user_id})
|
||||
|
||||
if user_id is None:
|
||||
log.warning("User id is None")
|
||||
raise InvalidTokenException
|
||||
except (Exception, JWTError) as ex:
|
||||
if isinstance(ex, InvalidTokenException):
|
||||
raise ex
|
||||
|
||||
if isinstance(ex, JWTError):
|
||||
log.error("JWT error")
|
||||
raise ex
|
||||
|
||||
log.error("Unknown exception")
|
||||
raise ex
|
||||
|
||||
current_user = await UserService.get_user(user_id)
|
||||
|
||||
if not current_user.is_active:
|
||||
log.debug("User is not active", extra={"user_id": current_user.id})
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, detail="User is not active")
|
||||
|
||||
return current_user
|
||||
|
||||
|
||||
async def get_current_superuser(current_user: UserModel = Depends(get_current_user)) -> Optional[UserModel]:
|
||||
if not current_user.is_superuser:
|
||||
log.debug("User not enough privileges", extra={"user_id": current_user.id})
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, detail="Not enough privileges")
|
||||
|
||||
return current_user
|
||||
|
||||
async def get_current_verified_user(current_user: UserModel = Depends(get_current_user)):
|
||||
if not current_user.is_verified:
|
||||
log.debug("User has not confirmed the email.", extra={"user_id": str(current_user.id)})
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, detail="verify email")
|
||||
|
||||
return current_user
|
||||
@@ -0,0 +1,89 @@
|
||||
from typing import Dict
|
||||
import logging
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, status, Response, Depends, Request, HTTPException
|
||||
from fastapi.security import OAuth2PasswordRequestForm
|
||||
|
||||
from app.users.schemas import UserCreate, User
|
||||
from app.auth.schemas import Token
|
||||
from app.users.service import UserService
|
||||
from app.auth.service import AuthService
|
||||
from app.users.models import UserModel
|
||||
from app.core.exceptions import InvalidCredentialsException
|
||||
from app.auth.dependencies import get_current_user
|
||||
from app.core.config import settings
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["Auth"])
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
@router.post("/register", status_code=status.HTTP_201_CREATED)
|
||||
async def register(user: UserCreate) -> User:
|
||||
return await UserService.register_new_user(user)
|
||||
|
||||
@router.get("/verify/{token}")
|
||||
async def verify_email(token: uuid.UUID) -> Dict:
|
||||
await UserService.verify_email(token)
|
||||
return {"status": True, "message": "User successfully verified email"}
|
||||
|
||||
@router.post("/send/verify-email")
|
||||
async def resend_verify_email(user: UserModel = Depends(get_current_user)) -> Dict:
|
||||
if user.is_verified:
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, detail="Email already verified")
|
||||
|
||||
await UserService.send_verify_email(user)
|
||||
return {"status": True, "message": "Successfully send email letter"}
|
||||
|
||||
@router.post("/login")
|
||||
async def login(response: Response, credentials: OAuth2PasswordRequestForm = Depends()) -> Token:
|
||||
user = await AuthService.authenticate_user(credentials.username, credentials.password)
|
||||
if not user:
|
||||
log.warning("Failed login attempt", extra={"email or username": credentials.username})
|
||||
raise InvalidCredentialsException
|
||||
token = await AuthService.create_token(user.id)
|
||||
response.set_cookie(
|
||||
'access_token',
|
||||
token.access_token,
|
||||
max_age=settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60,
|
||||
httponly=True
|
||||
)
|
||||
response.set_cookie(
|
||||
'refresh_token',
|
||||
str(token.refresh_token),
|
||||
max_age=settings.REFRESH_TOKEN_EXPIRE_DAYS * 30 * 24 * 60,
|
||||
httponly=True
|
||||
)
|
||||
return token
|
||||
|
||||
@router.post("/refresh")
|
||||
async def refresh_token(request: Request, response: Response) -> Token:
|
||||
new_token = await AuthService.refresh_token(uuid.UUID(request.cookies.get("refresh_token")))
|
||||
|
||||
response.set_cookie(
|
||||
'access_token',
|
||||
new_token.access_token,
|
||||
max_age=settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60,
|
||||
httponly=True
|
||||
)
|
||||
response.set_cookie(
|
||||
'refresh_token',
|
||||
str(new_token.refresh_token),
|
||||
max_age=settings.REFRESH_TOKEN_EXPIRE_DAYS * 30 * 24 * 60,
|
||||
httponly=True
|
||||
)
|
||||
log.debug("Token refreshed via endpoint")
|
||||
return new_token
|
||||
|
||||
@router.post("/logout")
|
||||
async def logout(request: Request, response: Response, user: UserModel = Depends(get_current_user)) -> Dict:
|
||||
response.delete_cookie("access_token")
|
||||
response.delete_cookie("refresh_token")
|
||||
|
||||
await AuthService.logout(uuid.UUID(request.cookies.get("refresh_token")))
|
||||
return {"status": True, "message": "Logged out successfully"}
|
||||
|
||||
@router.post("/abort")
|
||||
async def abort_all_sessions(user: UserModel = Depends(get_current_user)) -> Dict:
|
||||
await AuthService.abort_all_sessions(user.id)
|
||||
return {"status": True, "message": "All sessions was aborted"}
|
||||
@@ -0,0 +1,9 @@
|
||||
import uuid
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class Token(BaseModel):
|
||||
access_token: str
|
||||
refresh_token: uuid.UUID
|
||||
token_type: str
|
||||
@@ -0,0 +1,102 @@
|
||||
import logging
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional
|
||||
|
||||
from jose import jwt
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app.utils.hash_password import verify_password
|
||||
from app.services.redis_service import RefreshTokenStorage
|
||||
from app.core.exceptions import InvalidTokenException
|
||||
from app.users.models import UserModel
|
||||
from app.users.dao import UserDAO
|
||||
from app.core.database import async_session_maker
|
||||
from app.auth.schemas import Token
|
||||
from app.core.config import settings
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AuthService:
|
||||
@classmethod
|
||||
async def create_token(cls, user_id: int) -> Token:
|
||||
|
||||
access_token = cls._create_access_token(user_id)
|
||||
refresh_token_expires = timedelta(
|
||||
days=settings.REFRESH_TOKEN_EXPIRE_DAYS)
|
||||
refresh_token = cls._create_refresh_token()
|
||||
|
||||
await RefreshTokenStorage.save_token(refresh_token, user_id, int(refresh_token_expires.total_seconds()))
|
||||
|
||||
log.info("Token created has user", extra={"user_id": user_id})
|
||||
return Token(access_token=access_token, refresh_token=refresh_token, token_type="bearer")
|
||||
|
||||
@classmethod
|
||||
async def logout(cls, token: uuid.UUID) -> None:
|
||||
user_id = await RefreshTokenStorage.getdel_token(token)
|
||||
log.info("User logged out", extra={"user_id": user_id})
|
||||
|
||||
@classmethod
|
||||
async def refresh_token(cls, token: uuid.UUID) -> Token:
|
||||
async with async_session_maker() as session:
|
||||
refresh_session = await RefreshTokenStorage.getdel_token(token)
|
||||
|
||||
if refresh_session is None:
|
||||
log.warning("Refresh token not found")
|
||||
raise InvalidTokenException
|
||||
|
||||
user = await UserDAO.find_one_or_none(session, id=int(refresh_session))
|
||||
if user is None:
|
||||
log.error("User not found during token refresh", extra={"user_id": str(refresh_session.user_id)})
|
||||
raise InvalidTokenException
|
||||
|
||||
access_token = cls._create_access_token(user.id)
|
||||
refresh_token_expires = timedelta(
|
||||
days=settings.REFRESH_TOKEN_EXPIRE_DAYS)
|
||||
refresh_token = cls._create_refresh_token()
|
||||
|
||||
await RefreshTokenStorage.save_token(
|
||||
refresh_token,
|
||||
user.id,
|
||||
int(refresh_token_expires.total_seconds())
|
||||
)
|
||||
|
||||
await session.commit()
|
||||
log.info("Token refreshed for user", extra={"user_id": str(user.id)})
|
||||
return Token(access_token=access_token, refresh_token=refresh_token, token_type="bearer")
|
||||
|
||||
@classmethod
|
||||
async def authenticate_user(cls, email_or_username: str, password: str) -> Optional[UserModel]:
|
||||
async with async_session_maker() as session:
|
||||
db_user = await UserDAO.find_one_or_none(
|
||||
session,
|
||||
or_(
|
||||
UserModel.email==email_or_username,
|
||||
UserModel.username==email_or_username
|
||||
)
|
||||
)
|
||||
if db_user and verify_password(password, db_user.hashed_password):
|
||||
log.info("User authenticated successfully", extra={"username": db_user.username})
|
||||
return db_user
|
||||
log.warning("Authentication failed", extra={"email": email_or_username})
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
async def abort_all_sessions(cls, user_id: int):
|
||||
await RefreshTokenStorage.abort_all_tokens(user_id)
|
||||
|
||||
@classmethod
|
||||
def _create_access_token(cls, user_id: int) -> str:
|
||||
to_encode = {
|
||||
"sub": str(user_id),
|
||||
"exp": datetime.utcnow() + timedelta(
|
||||
minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
}
|
||||
encoded_jwt = jwt.encode(
|
||||
to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
||||
return f'Bearer {encoded_jwt}'
|
||||
|
||||
@classmethod
|
||||
def _create_refresh_token(cls) -> uuid.UUID:
|
||||
return uuid.uuid4()
|
||||
Reference in New Issue
Block a user