mirror of
https://github.com/fastapi-users/fastapi-users.git
synced 2025-08-26 04:25:46 +08:00
Revamp authentication (#831)
* Implement Transport classes * Implement authentication strategy classes * Revamp authentication with Transport and Strategy * Revamp strategy and OAuth so that they can use a callable dependency * Update docstring * Make ErrorCode a proper Enum and cleanup unused OpenAPI utils * Remove useless check * Tweak typing in authenticator * Update docs * Improve logout/destroy token logic * Update docs * Update docs * Update docs and full examples * Apply formatting to examples * Update OAuth doc and examples * Add migration doc * Implement Redis session token * Add Redis Session documentation * RedisSession -> Redis * Fix links in docs
This commit is contained in:
0
examples/tortoise-oauth/app/__init__.py
Normal file
0
examples/tortoise-oauth/app/__init__.py
Normal file
47
examples/tortoise-oauth/app/app.py
Normal file
47
examples/tortoise-oauth/app/app.py
Normal file
@ -0,0 +1,47 @@
|
||||
from fastapi import Depends, FastAPI
|
||||
from tortoise.contrib.fastapi import register_tortoise
|
||||
|
||||
from app.db import DATABASE_URL
|
||||
from app.models import UserDB
|
||||
from app.users import (
|
||||
auth_backend,
|
||||
current_active_user,
|
||||
fastapi_users,
|
||||
google_oauth_client,
|
||||
)
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
app.include_router(
|
||||
fastapi_users.get_auth_router(auth_backend), prefix="/auth/jwt", tags=["auth"]
|
||||
)
|
||||
app.include_router(fastapi_users.get_register_router(), prefix="/auth", tags=["auth"])
|
||||
app.include_router(
|
||||
fastapi_users.get_reset_password_router(),
|
||||
prefix="/auth",
|
||||
tags=["auth"],
|
||||
)
|
||||
app.include_router(
|
||||
fastapi_users.get_verify_router(),
|
||||
prefix="/auth",
|
||||
tags=["auth"],
|
||||
)
|
||||
app.include_router(fastapi_users.get_users_router(), prefix="/users", tags=["users"])
|
||||
app.include_router(
|
||||
fastapi_users.get_oauth_router(google_oauth_client, auth_backend, "SECRET"),
|
||||
prefix="/auth/google",
|
||||
tags=["auth"],
|
||||
)
|
||||
|
||||
|
||||
@app.get("/authenticated-route")
|
||||
async def authenticated_route(user: UserDB = Depends(current_active_user)):
|
||||
return {"message": f"Hello {user.email}!"}
|
||||
|
||||
|
||||
register_tortoise(
|
||||
app,
|
||||
db_url=DATABASE_URL,
|
||||
modules={"models": ["app.models"]},
|
||||
generate_schemas=True,
|
||||
)
|
9
examples/tortoise-oauth/app/db.py
Normal file
9
examples/tortoise-oauth/app/db.py
Normal file
@ -0,0 +1,9 @@
|
||||
from fastapi_users.db import TortoiseUserDatabase
|
||||
|
||||
from app.models import OAuthAccount, UserDB, UserModel
|
||||
|
||||
DATABASE_URL = "sqlite://./test.db"
|
||||
|
||||
|
||||
async def get_user_db():
|
||||
yield TortoiseUserDatabase(UserDB, UserModel, OAuthAccount)
|
30
examples/tortoise-oauth/app/models.py
Normal file
30
examples/tortoise-oauth/app/models.py
Normal file
@ -0,0 +1,30 @@
|
||||
from fastapi_users import models
|
||||
from fastapi_users.db import TortoiseBaseOAuthAccountModel, TortoiseBaseUserModel
|
||||
from tortoise import fields
|
||||
from tortoise.contrib.pydantic import PydanticModel
|
||||
|
||||
|
||||
class User(models.BaseUser, models.BaseOAuthAccountMixin):
|
||||
pass
|
||||
|
||||
|
||||
class UserCreate(models.BaseUserCreate):
|
||||
pass
|
||||
|
||||
|
||||
class UserUpdate(models.BaseUserUpdate):
|
||||
pass
|
||||
|
||||
|
||||
class UserModel(TortoiseBaseUserModel):
|
||||
pass
|
||||
|
||||
|
||||
class UserDB(User, models.BaseUserDB, PydanticModel):
|
||||
class Config:
|
||||
orm_mode = True
|
||||
orig_model = UserModel
|
||||
|
||||
|
||||
class OAuthAccount(TortoiseBaseOAuthAccountModel):
|
||||
user = fields.ForeignKeyField("models.UserModel", related_name="oauth_accounts")
|
70
examples/tortoise-oauth/app/users.py
Normal file
70
examples/tortoise-oauth/app/users.py
Normal file
@ -0,0 +1,70 @@
|
||||
import os
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends, Request
|
||||
from fastapi_users import BaseUserManager, FastAPIUsers
|
||||
from fastapi_users.authentication import (
|
||||
AuthenticationBackend,
|
||||
BearerTransport,
|
||||
JWTStrategy,
|
||||
)
|
||||
from fastapi_users.db import TortoiseUserDatabase
|
||||
from httpx_oauth.clients.google import GoogleOAuth2
|
||||
|
||||
from app.db import get_user_db
|
||||
from app.models import User, UserCreate, UserDB, UserUpdate
|
||||
|
||||
SECRET = "SECRET"
|
||||
|
||||
|
||||
google_oauth_client = GoogleOAuth2(
|
||||
os.environ["GOOGLE_OAUTH_CLIENT_ID"],
|
||||
os.environ["GOOGLE_OAUTH_CLIENT_SECRET"],
|
||||
)
|
||||
|
||||
|
||||
class UserManager(BaseUserManager[UserCreate, UserDB]):
|
||||
user_db_model = UserDB
|
||||
reset_password_token_secret = SECRET
|
||||
verification_token_secret = SECRET
|
||||
|
||||
async def on_after_register(self, user: UserDB, request: Optional[Request] = None):
|
||||
print(f"User {user.id} has registered.")
|
||||
|
||||
async def on_after_forgot_password(
|
||||
self, user: UserDB, 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: UserDB, token: str, request: Optional[Request] = None
|
||||
):
|
||||
print(f"Verification requested for user {user.id}. Verification token: {token}")
|
||||
|
||||
|
||||
async def get_user_manager(user_db: TortoiseUserDatabase = Depends(get_user_db)):
|
||||
yield UserManager(user_db)
|
||||
|
||||
|
||||
bearer_transport = BearerTransport(tokenUrl="auth/jwt/login")
|
||||
|
||||
|
||||
def get_jwt_strategy() -> JWTStrategy:
|
||||
return JWTStrategy(secret=SECRET, lifetime_seconds=3600)
|
||||
|
||||
|
||||
auth_backend = AuthenticationBackend(
|
||||
name="jwt",
|
||||
transport=bearer_transport,
|
||||
get_strategy=get_jwt_strategy,
|
||||
)
|
||||
fastapi_users = FastAPIUsers(
|
||||
get_user_manager,
|
||||
[auth_backend],
|
||||
User,
|
||||
UserCreate,
|
||||
UserUpdate,
|
||||
UserDB,
|
||||
)
|
||||
|
||||
current_active_user = fastapi_users.current_user(active=True)
|
4
examples/tortoise-oauth/main.py
Normal file
4
examples/tortoise-oauth/main.py
Normal file
@ -0,0 +1,4 @@
|
||||
import uvicorn
|
||||
|
||||
if __name__ == "__main__":
|
||||
uvicorn.run("app.app:app", host="0.0.0.0", port=5000, log_level="info")
|
3
examples/tortoise-oauth/requirements.txt
Normal file
3
examples/tortoise-oauth/requirements.txt
Normal file
@ -0,0 +1,3 @@
|
||||
fastapi
|
||||
fastapi-users[tortoise-orm,oauth]
|
||||
uvicorn[standard]
|
Reference in New Issue
Block a user