mirror of
https://github.com/fastapi-users/fastapi-users.git
synced 2025-08-16 11:53:40 +08:00
Revamp OAuth documentation
This commit is contained in:
@ -1,7 +1,7 @@
|
||||
from fastapi import Depends, FastAPI
|
||||
|
||||
from app.db import create_db_and_tables
|
||||
from app.models import UserDB
|
||||
from app.db import User, create_db_and_tables
|
||||
from app.schemas import UserCreate, UserRead, UserUpdate
|
||||
from app.users import (
|
||||
auth_backend,
|
||||
current_active_user,
|
||||
@ -14,18 +14,26 @@ 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_register_router(UserRead, UserCreate),
|
||||
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(),
|
||||
fastapi_users.get_verify_router(UserRead),
|
||||
prefix="/auth",
|
||||
tags=["auth"],
|
||||
)
|
||||
app.include_router(fastapi_users.get_users_router(), prefix="/users", tags=["users"])
|
||||
app.include_router(
|
||||
fastapi_users.get_users_router(UserRead, UserUpdate),
|
||||
prefix="/users",
|
||||
tags=["users"],
|
||||
)
|
||||
app.include_router(
|
||||
fastapi_users.get_oauth_router(google_oauth_client, auth_backend, "SECRET"),
|
||||
prefix="/auth/google",
|
||||
@ -34,7 +42,7 @@ app.include_router(
|
||||
|
||||
|
||||
@app.get("/authenticated-route")
|
||||
async def authenticated_route(user: UserDB = Depends(current_active_user)):
|
||||
async def authenticated_route(user: User = Depends(current_active_user)):
|
||||
return {"message": f"Hello {user.email}!"}
|
||||
|
||||
|
||||
|
@ -1,29 +1,27 @@
|
||||
from typing import AsyncGenerator
|
||||
from typing import AsyncGenerator, List
|
||||
|
||||
from fastapi import Depends
|
||||
from fastapi_users.db import (
|
||||
SQLAlchemyBaseOAuthAccountTable,
|
||||
SQLAlchemyBaseUserTable,
|
||||
SQLAlchemyBaseOAuthAccountTableUUID,
|
||||
SQLAlchemyBaseUserTableUUID,
|
||||
SQLAlchemyUserDatabase,
|
||||
)
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
|
||||
from sqlalchemy.ext.declarative import DeclarativeMeta, declarative_base
|
||||
from sqlalchemy.orm import relationship, sessionmaker
|
||||
|
||||
from app.models import UserDB
|
||||
|
||||
DATABASE_URL = "sqlite+aiosqlite:///./test.db"
|
||||
Base: DeclarativeMeta = declarative_base()
|
||||
|
||||
|
||||
class UserTable(Base, SQLAlchemyBaseUserTable):
|
||||
oauth_accounts = relationship("OAuthAccountTable")
|
||||
|
||||
|
||||
class OAuthAccountTable(SQLAlchemyBaseOAuthAccountTable, Base):
|
||||
class OAuthAccount(SQLAlchemyBaseOAuthAccountTableUUID, Base):
|
||||
pass
|
||||
|
||||
|
||||
class User(SQLAlchemyBaseUserTableUUID, Base):
|
||||
oauth_accounts: List[OAuthAccount] = relationship("OAuthAccount", lazy="joined")
|
||||
|
||||
|
||||
engine = create_async_engine(DATABASE_URL)
|
||||
async_session_maker = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
||||
|
||||
@ -39,4 +37,4 @@ async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
|
||||
|
||||
|
||||
async def get_user_db(session: AsyncSession = Depends(get_async_session)):
|
||||
yield SQLAlchemyUserDatabase(UserDB, session, UserTable, OAuthAccountTable)
|
||||
yield SQLAlchemyUserDatabase(session, User, OAuthAccount)
|
||||
|
@ -1,17 +0,0 @@
|
||||
from fastapi_users import models, schemas
|
||||
|
||||
|
||||
class User(schemas.BaseUser, schemas.BaseOAuthAccountMixin):
|
||||
pass
|
||||
|
||||
|
||||
class UserCreate(schemas.BaseUserCreate):
|
||||
pass
|
||||
|
||||
|
||||
class UserUpdate(schemas.BaseUserUpdate):
|
||||
pass
|
||||
|
||||
|
||||
class UserDB(User, schemas.BaseUserDB):
|
||||
pass
|
15
examples/sqlalchemy-oauth/app/schemas.py
Normal file
15
examples/sqlalchemy-oauth/app/schemas.py
Normal file
@ -0,0 +1,15 @@
|
||||
import uuid
|
||||
|
||||
from fastapi_users import schemas
|
||||
|
||||
|
||||
class UserRead(schemas.BaseUser[uuid.UUID]):
|
||||
pass
|
||||
|
||||
|
||||
class UserCreate(schemas.BaseUserCreate):
|
||||
pass
|
||||
|
||||
|
||||
class UserUpdate(schemas.BaseUserUpdate):
|
||||
pass
|
@ -1,8 +1,9 @@
|
||||
import os
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends, Request
|
||||
from fastapi_users import BaseUserManager, FastAPIUsers
|
||||
from fastapi_users import BaseUserManager, FastAPIUsers, UUIDIDMixin
|
||||
from fastapi_users.authentication import (
|
||||
AuthenticationBackend,
|
||||
BearerTransport,
|
||||
@ -11,33 +12,30 @@ from fastapi_users.authentication import (
|
||||
from fastapi_users.db import SQLAlchemyUserDatabase
|
||||
from httpx_oauth.clients.google import GoogleOAuth2
|
||||
|
||||
from app.db import get_user_db
|
||||
from app.models import User, UserCreate, UserDB, UserUpdate
|
||||
from app.db import User, get_user_db
|
||||
|
||||
SECRET = "SECRET"
|
||||
|
||||
|
||||
google_oauth_client = GoogleOAuth2(
|
||||
os.getenv("GOOGLE_OAUTH_CLIENT_ID", ""),
|
||||
os.getenv("GOOGLE_OAUTH_CLIENT_SECRET", ""),
|
||||
)
|
||||
|
||||
|
||||
class UserManager(BaseUserManager[UserCreate, UserDB]):
|
||||
user_db_model = UserDB
|
||||
class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
|
||||
reset_password_token_secret = SECRET
|
||||
verification_token_secret = SECRET
|
||||
|
||||
async def on_after_register(self, user: UserDB, request: Optional[Request] = None):
|
||||
async def on_after_register(self, user: User, 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
|
||||
self, user: User, 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
|
||||
self, user: User, token: str, request: Optional[Request] = None
|
||||
):
|
||||
print(f"Verification requested for user {user.id}. Verification token: {token}")
|
||||
|
||||
@ -58,13 +56,7 @@ auth_backend = AuthenticationBackend(
|
||||
transport=bearer_transport,
|
||||
get_strategy=get_jwt_strategy,
|
||||
)
|
||||
fastapi_users = FastAPIUsers(
|
||||
get_user_manager,
|
||||
[auth_backend],
|
||||
User,
|
||||
UserCreate,
|
||||
UserUpdate,
|
||||
UserDB,
|
||||
)
|
||||
|
||||
fastapi_users = FastAPIUsers[User, uuid.UUID](get_user_manager, [auth_backend])
|
||||
|
||||
current_active_user = fastapi_users.current_user(active=True)
|
||||
|
@ -1,4 +1,4 @@
|
||||
fastapi
|
||||
fastapi-users[sqlalchemy2,oauth]
|
||||
fastapi-users[sqlalchemy]
|
||||
uvicorn[standard]
|
||||
aiosqlite
|
||||
|
Reference in New Issue
Block a user