mirror of
				https://github.com/fastapi-users/fastapi-users.git
				synced 2025-11-04 14:45:50 +08:00 
			
		
		
		
	* Fix #68: use makefun to generate dynamic dependencies * Remove every Starlette imports * Split every routers and remove event handlers * Make users router optional * Pass after_update handler to get_users_router * Update documentation * Remove test file * Write migration doc for splitted routers
		
			
				
	
	
		
			41 lines
		
	
	
		
			1.3 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
			
		
		
	
	
			41 lines
		
	
	
		
			1.3 KiB
		
	
	
	
		
			Python
		
	
	
	
	
	
from fastapi import APIRouter, Depends, HTTPException, Response, status
 | 
						|
from fastapi.security import OAuth2PasswordRequestForm
 | 
						|
 | 
						|
from fastapi_users import models
 | 
						|
from fastapi_users.authentication import Authenticator, BaseAuthentication
 | 
						|
from fastapi_users.db import BaseUserDatabase
 | 
						|
from fastapi_users.router.common import ErrorCode
 | 
						|
 | 
						|
 | 
						|
def get_auth_router(
 | 
						|
    backend: BaseAuthentication,
 | 
						|
    user_db: BaseUserDatabase[models.BaseUserDB],
 | 
						|
    authenticator: Authenticator,
 | 
						|
) -> APIRouter:
 | 
						|
    """Generate a router with login/logout routes for an authentication backend."""
 | 
						|
    router = APIRouter()
 | 
						|
 | 
						|
    @router.post("/login")
 | 
						|
    async def login(
 | 
						|
        response: Response, credentials: OAuth2PasswordRequestForm = Depends()
 | 
						|
    ):
 | 
						|
        user = await user_db.authenticate(credentials)
 | 
						|
 | 
						|
        if user is None or not user.is_active:
 | 
						|
            raise HTTPException(
 | 
						|
                status_code=status.HTTP_400_BAD_REQUEST,
 | 
						|
                detail=ErrorCode.LOGIN_BAD_CREDENTIALS,
 | 
						|
            )
 | 
						|
 | 
						|
        return await backend.get_login_response(user, response)
 | 
						|
 | 
						|
    if backend.logout:
 | 
						|
 | 
						|
        @router.post("/logout")
 | 
						|
        async def logout(
 | 
						|
            response: Response, user=Depends(authenticator.get_current_active_user)
 | 
						|
        ):
 | 
						|
            return await backend.get_logout_response(user, response)
 | 
						|
 | 
						|
    return router
 |