Package: nasone_userauth
简体中文|EnglishProject IntroductionFastAPI-User-AuthFastAPI-User-Auth is a simple and powerful FastAPI user RBAC authentication and authorization library.It is based on FastAPI-Amis-Admin and provides a freely extensible visual management interface.SourceCode·OnlineDemo·Documentation·Can't open the document？FastAPI-User-AuthIt is an application plug -in based onFastAPI-Amis-Admin, which is deeply integrated to provide user authentication and authorization..Installpipinstallfastapi-user-authSimple examplefromfastapiimportFastAPIfromfastapi_amis_admin.admin.settingsimportSettingsfromfastapi_user_auth.siteimportAuthAdminSitefromstarlette.requestsimportRequestfromsqlmodelimportSQLModel# Create Fast API applicationapp=FastAPI()# Create an Admin Site instancesite=AuthAdminSite(settings=Settings(database_url_async='sqlite+aiosqlite:///amisadmin.db'))auth=site.auth# Mount the Site management system to the FastAPI instancesite.mount_app(app)# Create initialization database table@app.on_event("startup")asyncdefstartup():awaitsite.db.async_run_sync(SQLModel.metadata.create_all,is_session=False)# Create default admin user,user name:admin,password:admin,please change it after login!!!awaitauth.create_role_user('admin')awaitauth.create_role_user('vip')# Requirements: User must be logged in@app.get("/auth/get_user")@auth.requires()defget_user(request:Request):returnrequest.userif__name__=='__main__':importuvicornuvicorn.run(app,debug=True)Ways of identifyingDecoratorRecommended scenario: Single route. Supports synchronous and asynchronous routing.# Requirements: User must be logged in@app.get("/auth/user")@auth.requires()defuser(request:Request):returnrequest.user# current request user object.# Authentication route: user has admin role@app.get("/auth/admin_roles")@auth.requires('admin')defadmin_roles(request:Request):returnrequest.user# Requirement: User has vip role# Support synchronous and asynchronous routing@app.get("/auth/vip_roles")@auth.requires(['vip'])asyncdefvip_roles(request:Request):returnrequest.user# Requirements: User has admin role or vip role@app.get("/auth/admin_or_vip_roles")@auth.requires(roles=['admin','vip'])defadmin_or_vip_roles(request:Request):returnrequest.user# Requirement: The user belongs to the admin user group@app.get("/auth/admin_groups")@auth.requires(groups=['admin'])defadmin_groups(request:Request):returnrequest.user# Requirements: The user has the admin role and belongs to the admin user group@app.get("/auth/admin_roles_and_admin_groups")@auth.requires(roles=['admin'],groups=['admin'])defadmin_roles_and_admin_groups(request:Request):returnrequest.user# Requirements: The user has the vip role and has the `article:update` permission@app.get("/auth/vip_roles_and_article_update")@auth.requires(roles=['vip'],permissions=['article:update'])defvip_roles_and_article_update(request:Request):returnrequest.userDependencies (recommended)Recommended scenarios: single route, route collection, FastAPI application.fromfastapiimportDependsfromtypingimportTuplefromfastapi_user_auth.authimportAuthfromfastapi_user_auth.auth.modelsimportUser# Route parameter dependencies, this method is recommended@app.get("/auth/admin_roles_depend_1")defadmin_roles(user:User=Depends(auth.get_current_user)):returnuser# or request.user# Path manipulation decorator dependencies@app.get("/auth/admin_roles_depend_2",dependencies=[Depends(auth.requires('admin')())])defadmin_roles(request:Request):returnrequest.user# Global dependencies# All requests under the app application require the admin roleapp=FastAPI(dependencies=[Depends(auth.requires('admin')())])@app.get("/auth/admin_roles_depend_3")defadmin_roles(request:Request):returnrequest.userMiddlewareRecommended Scenario: FastAPI Applicationapp=FastAPI()# Append `request.auth` and `request.user` objects before each request processing under the appauth.backend.attach_middleware(app)Call directlyRecommended scenarios: non-routing methodsfromfastapi_user_auth.auth.modelsimportUserasyncdefget_request_user(request:Request)->Optional[User]:# user= await auth.get_current_user(request)ifawaitauth.requires('admin',response=False)(request):returnrequest.userelse:returnNoneToken storage backendfastapi-user-authSupports multiple token storage methods. The default is:DbTokenStore, It is recommended to customize the modification to:JwtTokenStoreJwtTokenStorefromfastapi_user_auth.auth.backends.jwtimportJwtTokenStorefromsqlalchemy.ext.asyncioimportcreate_async_enginefromsqlalchemy_databaseimportAsyncDatabase# Create an asynchronous database engineengine=create_async_engine(url='sqlite+aiosqlite:///amisadmin.db',future=True)# Create auth object using `Jwt Token Store`auth=Auth(db=AsyncDatabase(engine),token_store=JwtTokenStore(secret_key='09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7'))# Pass the auth object into the Admin Sitesite=AuthAdminSite(settings=Settings(database_url_async='sqlite+aiosqlite:///amisadmin.db'),auth=auth)DbTokenStore# Create auth object using `Db Token Store`fromfastapi_user_auth.auth.backends.dbimportDbTokenStoreauth=Auth(db=AsyncDatabase(engine),token_store=DbTokenStore(db=AsyncDatabase(engine)))RedisTokenStore# Create auth object using `Redis Token Store`fromfastapi_user_auth.auth.backends.redisimportRedisTokenStorefromaioredisimportRedisauth=Auth(db=AsyncDatabase(engine),token_store=RedisTokenStore(redis=Redis.from_url('redis://localhost?db=0')))RBAC modelTheRBACmodel adopted by this system is as follows, you can also expand it according to your own needs.Reference:Design of Permission Systemflowchart LR
	 User -. m:n .-> Group 
	 User -. m:n .-> Role 
     Group -. m:n .-> Role 
	 Role -. m:n .-> PerimissionAdvanced Extension### Extending the `User` model```python
fromdatetimeimportdate

fromfastapi_amis_admin.models.fieldsimportField
fromfastapi_user_auth.auth.modelsimportUser# Customize `User` model, inherit `User`classMyUser(User,table=True):point:float=Field(default=0,title='Source',description='User source')phone:str=Field(None,title='Phone number',max_length=15)parent_id:int=Field(None,title="Superior",foreign_key="auth_user.id")birthday:date=Field(None,title="Date of birth")location:str=Field(None,title="Location")# Create an auth object using a custom `User` modelauth=Auth(db=AsyncDatabase(engine),user_model=MyUser)Extend theRole,Group,Permissionmodelsfromfastapi_amis_admin.models.fieldsimportFieldfromfastapi_user_auth.auth.modelsimportGroup# Customize the `Group` model, inherit `Base RBAC`; override the `Role`, the `Permission` model is similar,# the difference is the table name.classMyGroup(Group,table=True):__tablename__='auth_group'# Database table name, must be this to override the default modelicon:str=Field(None,title='Icon')is_active:bool=Field(default=True,title="Activate now")CustomUser Auth Appdefault management classDefault management classes can be overridden and replaced by inheritance.
For Example:UserLoginFormAdmin,UserRegFormAdmin,UserInfoFormAdmin,UserAdmin,GroupAdmin,RoleAdmin,PermissionAdmin# Customize the model management class, inherit and override the corresponding default management classclassMyGroupAdmin(admin.ModelAdmin):page_schema=PageSchema(label='用户组管理',icon='fa fa-group')model=MyGrouplink_model_fields=[Group.roles]readonly_fields=['key']# Customize the user authentication application, inherit and override the default user authentication applicationclassMyUserAuthApp(UserAuthApp):GroupAdmin=MyGroupAdmin# Customize the user management site, inherit and override the default user management siteclassMyAuthAdminSite(AuthAdminSite):UserAuthApp=MyUserAuthApp# Create a site object using a custom `Auth Admin Site` classsite=MyAuthAdminSite(settings,auth=auth)Interface/UI previewOpenhttp://127.0.0.1:8000/admin/auth/form/loginin your browser:Openhttp://127.0.0.1:8000/admin/in your browser:Openhttp://127.0.0.1:8000/admin/docsin your browser:Licensefastapi-amis-adminis based onApache2.0Open source is free to use and can be freely used for commercial purposes, but please clearly display the copyright information about Fast API-Amis-Admin in the display interface.ThanksThanks to the following developers for their contributions to FastAPI-User-Auth: