mirror of
https://github.com/rommapp/romm.git
synced 2026-11-29 01:58:41 +01:00
Switch to cookie based auth
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
from typing import Annotated
|
||||
from datetime import timedelta
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Response
|
||||
from fastapi.security import OAuth2PasswordRequestForm
|
||||
from pydantic import BaseModel, BaseConfig
|
||||
|
||||
@@ -17,11 +17,6 @@ from utils.auth import (
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class TokenSchema(BaseModel):
|
||||
access_token: str
|
||||
token_type: str
|
||||
|
||||
|
||||
class UserSchema(BaseModel):
|
||||
username: str
|
||||
disabled: bool
|
||||
@@ -30,8 +25,10 @@ class UserSchema(BaseModel):
|
||||
orm_mode = True
|
||||
|
||||
|
||||
@router.post("/token", response_model=TokenSchema)
|
||||
def login_with_password(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):
|
||||
@router.post("/token", response_model=UserSchema)
|
||||
def login_with_password(
|
||||
form_data: Annotated[OAuth2PasswordRequestForm, Depends()], response: Response
|
||||
):
|
||||
user = authenticate_user(form_data.username, form_data.password)
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
@@ -45,16 +42,31 @@ def login_with_password(form_data: Annotated[OAuth2PasswordRequestForm, Depends(
|
||||
data={"sub": user.username}, expires_delta=access_token_expires
|
||||
)
|
||||
|
||||
return {"access_token": access_token, "token_type": "bearer"}
|
||||
response.set_cookie("access_token", access_token, httponly=True)
|
||||
|
||||
return user
|
||||
|
||||
|
||||
@router.get("/users/me/", response_model=UserSchema)
|
||||
def current_user(current_user: Annotated[User, Depends(get_current_active_user)]):
|
||||
@router.get(
|
||||
"/users/",
|
||||
dependencies=[Depends(get_current_active_user)],
|
||||
)
|
||||
def users() -> list[UserSchema]:
|
||||
return dbh.get_users()
|
||||
|
||||
|
||||
@router.get("/users/me/")
|
||||
def current_user(
|
||||
current_user: Annotated[User, Depends(get_current_active_user)]
|
||||
) -> UserSchema:
|
||||
return current_user
|
||||
|
||||
|
||||
@router.post("/users/", response_model=UserSchema)
|
||||
def create_user(username: str, password: str):
|
||||
@router.post(
|
||||
"/users/",
|
||||
dependencies=[Depends(get_current_active_user)],
|
||||
)
|
||||
def create_user(username: str, password: str) -> UserSchema:
|
||||
user = User(
|
||||
username=username, hashed_password=get_password_hash(password), disabled=False
|
||||
)
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from typing import Annotated
|
||||
from datetime import datetime, timedelta
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from fastapi import Depends, HTTPException, status, Request
|
||||
from jose import JWTError, jwt
|
||||
from passlib.context import CryptContext
|
||||
|
||||
@@ -15,7 +14,6 @@ ALGORITHM = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES = 30
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
|
||||
|
||||
|
||||
def verify_password(plain_password, hashed_password):
|
||||
@@ -50,24 +48,28 @@ def create_access_token(data: dict, expires_delta: timedelta | None = None):
|
||||
return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
|
||||
|
||||
|
||||
async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
|
||||
credentials_exception = HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
async def get_current_user(request: Request):
|
||||
authentication_exception = HTTPException(
|
||||
status_code=status.HTTP_302_FOUND,
|
||||
detail="Not authenticated",
|
||||
headers={"Location": "/login"},
|
||||
)
|
||||
|
||||
token = request.cookies.get('access_token')
|
||||
if token is None:
|
||||
raise authentication_exception
|
||||
|
||||
try:
|
||||
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
||||
username: str = payload.get("sub")
|
||||
if username is None:
|
||||
raise credentials_exception
|
||||
raise authentication_exception
|
||||
except JWTError:
|
||||
raise credentials_exception
|
||||
raise authentication_exception
|
||||
|
||||
user = dbh.get_user(username)
|
||||
if user is None:
|
||||
raise credentials_exception
|
||||
raise authentication_exception
|
||||
|
||||
return user
|
||||
|
||||
|
||||
Reference in New Issue
Block a user