Spaces:
Sleeping
Sleeping
File size: 2,162 Bytes
b77c0a2 6830bc7 01ae535 b77c0a2 6830bc7 b77c0a2 01ae535 b77c0a2 6830bc7 b77c0a2 01ae535 6830bc7 01ae535 6830bc7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from auth import authenticate_user, get_current_user
from custom_auth import (
create_token_for_user,
get_current_user_from_token,
get_token,
remove_token,
)
from models import Token, UserCreate, User
from database import get_users, create_account
router = APIRouter()
@router.post("/token", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
"""
Endpoint to get an access token using username and password
"""
user = authenticate_user(get_users(), form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
# Create a new token for the user (this will remove any existing token)
access_token = create_token_for_user(user.username)
return Token(access_token=access_token, token_type="bearer")
@router.post("/register")
async def register_user(user_data: UserCreate):
"""
Endpoint to register a new account
"""
success, message = create_account(user_data.username, user_data.password)
if not success:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=message)
return {"message": message}
@router.post("/logout")
async def logout(
current_user: User = Depends(get_current_user_from_token),
token: str = Depends(get_token),
):
"""
Endpoint to logout (invalidate the current token)
"""
success = remove_token(token)
if success:
return {"message": "Logout successful"}
else:
return {"message": "Token already invalid or expired"}
@router.get("/me")
async def get_current_user_info(
current_user: User = Depends(get_current_user_from_token),
):
"""
Get the current user's information
"""
return {
"username": current_user.username,
"email": current_user.email,
"full_name": current_user.full_name,
}
|