{"id":13595024,"url":"https://github.com/amisadmin/fastapi-user-auth","last_synced_at":"2025-05-13T16:19:03.254Z","repository":{"id":41908297,"uuid":"467075076","full_name":"amisadmin/fastapi-user-auth","owner":"amisadmin","description":"FastAPI-User-Auth is a simple and powerful FastAPI user RBAC authentication and authorization library. Based on FastAPI-Amis-Admin and provides a freely extensible visual management interface.","archived":false,"fork":false,"pushed_at":"2024-06-25T07:55:06.000Z","size":462,"stargazers_count":344,"open_issues_count":18,"forks_count":43,"subscribers_count":7,"default_branch":"master","last_synced_at":"2024-11-06T17:44:55.699Z","etag":null,"topics":["fastapi","fastapi-admin","fastapi-amis-admin","fastapi-auth","fastapi-jwt-auth","fastapi-rbac","fastapi-user","fastapi-user-auth"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/amisadmin.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-03-07T11:59:38.000Z","updated_at":"2024-10-29T11:02:47.000Z","dependencies_parsed_at":"2024-01-12T06:52:44.713Z","dependency_job_id":"c8e9609c-a02c-4db1-8e2f-d97db19abc1a","html_url":"https://github.com/amisadmin/fastapi-user-auth","commit_stats":null,"previous_names":["amisadmin/fastapi_user_auth"],"tags_count":18,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/amisadmin%2Ffastapi-user-auth","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/amisadmin%2Ffastapi-user-auth/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/amisadmin%2Ffastapi-user-auth/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/amisadmin%2Ffastapi-user-auth/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/amisadmin","download_url":"https://codeload.github.com/amisadmin/fastapi-user-auth/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248020593,"owners_count":21034459,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["fastapi","fastapi-admin","fastapi-amis-admin","fastapi-auth","fastapi-jwt-auth","fastapi-rbac","fastapi-user","fastapi-user-auth"],"created_at":"2024-08-01T16:01:42.573Z","updated_at":"2025-04-09T10:32:35.979Z","avatar_url":"https://github.com/amisadmin.png","language":"Python","funding_links":[],"categories":["Python"],"sub_categories":[],"readme":"[简体中文](https://github.com/Mkadir/fastapi-user-auth/blob/master/README.zh.md)\n| [English](https://github.com/Mkadir/fastapi-user-auth)\n# Project Introduction\n\u003ch2 align=\"center\"\u003e\n  FastAPI-User-Auth\n\u003c/h2\u003e\u003cp align=\"center\"\u003e\n    \u003cem\u003eFastAPI-User-Auth is a simple and powerful FastAPI user authentication and authorization library based on Casbin.\u003c/em\u003e\u003cbr/\u003e\n    \u003cem\u003eBased on FastAPI-Amis-Admin and provides a freely extensible visual management interface.\u003c/em\u003e\n\u003c/p\u003e\n\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://github.com/amisadmin/fastapi_amis_admin/actions/workflows/pytest.yml\" target=\"_blank\"\u003e\n        \u003cimg src=\"https://github.com/amisadmin/fastapi_amis_admin/actions/workflows/pytest.yml/badge.svg\" alt=\"Pytest\"\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://pypi.org/project/fastapi_user_auth\" target=\"_blank\"\u003e\n        \u003cimg src=\"https://badgen.net/pypi/v/fastapi-user-auth?color=blue\" alt=\"Package version\"\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://pepy.tech/project/fastapi-user-auth\" target=\"_blank\"\u003e\n        \u003cimg src=\"https://pepy.tech/badge/fastapi-user-auth\" alt=\"Downloads\"\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://gitter.im/amisadmin/fastapi-amis-admin\"\u003e\n        \u003cimg src=\"https://badges.gitter.im/amisadmin/fastapi-amis-admin.svg\" alt=\"Chat on Gitter\"/\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://jq.qq.com/?_wv=1027\u0026k=U4Dv6x8W\" target=\"_blank\"\u003e\n        \u003cimg src=\"https://badgen.net/badge/qq%E7%BE%A4/229036692/orange\" alt=\"229036692\"\u003e\n    \u003c/a\u003e\n\u003c/p\u003e\n\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://github.com/amisadmin/fastapi_user_auth\" target=\"_blank\"\u003eSource code\u003c/a\u003e\n  ·\n  \u003ca href=\"http://user-auth.demo.amis.work/\" target=\"_blank\"\u003eOnline demo\u003c/a\u003e\n  ·\n  \u003ca href=\"http://docs.amis.work\" target=\"_blank\"\u003eDocumentation\u003c/a\u003e\n  ·\n  \u003ca href=\"http://docs.gh.amis.work\" target=\"_blank\"\u003e can't open the document ？\u003c/a\u003e\n\u003c/p\u003e\n\n------\n`FastAPI-User-Auth` is a API based on [FastAPI-Amis-Admin](https://github.com/amisadmin/fastapi_amis_admin)\nThe application plug-in is deeply integrated with `FastAPI-Amis-Admin` to provide user authentication and authorization.\nCasbin-based RBAC permission management supports multiple verification methods, multiple databases, and multiple granularity permission controls.\n\n### Permission types\n- **Page Permissions**: Control whether the user can access a certain menu page. If it is not accessible, the menu will not be displayed, and all routes under the page will be inaccessible.\n- **Action Permission**: Controls whether the user can perform an action and whether the button is displayed. For example: add, update, delete, etc.\n- **Field permissions**: Control whether users can operate a certain field. For example: list display fields, filter fields, add fields, update fields, etc.\n- **Data permissions**: Control the range of data that users can operate. For example: they can only operate the data they created, only the data of the last 7 days, etc.\n\n\n## Installation\n```bash\npip install fastapi-user-auth\n```\n## Simple example\n```python\nfrom fastapi import FastAPI\nfrom fastapi_amis_admin.admin.settings import Settings\nfrom fastapi_user_auth.admin.site import AuthAdminSite\nfrom starlette.requests import Request\nfrom sqlmodel import SQLModel\n\n# Create FastAPI application\napp = FastAPI()\n\n# Create AdminSite instance\nsite = AuthAdminSite(settings=Settings(database_url='sqlite:///amisadmin.db?check_same_thread=False'))\nauth = site.auth\n# Mount the backend management system\nsite.mount_app(app)\n\n\n# Create initial database table\n@app.on_event(\"startup\")\nasync def startup():\n    await site.db.async_run_sync(SQLModel.metadata.create_all, is_session=False)\n    # Create a default administrator, username: admin, password: admin, please change the password in time!!!\n    await auth.create_role_user(\"admin\")\n    #Create the default super administrator, username: root, password: root, please change the password in time!!!    await auth.create_role_user(\"root\")\n    # Run the startup method of the site, load the casbin strategy, etc.\n    await site.router.startup()\n    #Add a default casbin rule\n    if not auth.enforcer.enforce(\"u:admin\", site.unique_id, \"page\", \"page\"):\n        await auth.enforcer.add_policy(\"u:admin\", site.unique_id, \"page\", \"page\", \"allow\")\n\n\n# Requirements: User must be logged in\n@app.get(\"/auth/get_user\")\n@auth.requires()\ndef get_user(request: Request):\n    return request.user\n\n\nif __name__ == '__main__':\n    import uvicorn\n\n    uvicorn.run(app)\n\n```\n\n## Authentication methods\n### Decorator\n- Recommended scenario: Single route. Supports synchronous/asynchronous routing.\n```python\n# Requirements: User must be logged in\n@app.get(\"/auth/user\")\n@auth.requires()\ndef user(request: Request):\n    return request.user  # Current request user object.\n\n\n# Verify routing: user has admin role\n@app.get(\"/auth/admin_roles\")\n@auth.requires('admin')\ndef admin_roles(request: Request):\n    return request.user\n\n\n# Requirement: User has VIP role\n#Support synchronous/asynchronous routing\n@app.get(\"/auth/vip_roles\")\n@auth.requires(['vip'])\nasync def vip_roles(request: Request):\n    return request.user\n\n\n# Requirement: User has admin role or vip role\n@app.get(\"/auth/admin_or_vip_roles\")\n@auth.requires(roles=['admin', 'vip'])\ndef admin_or_vip_roles(request: Request):\n    return request.user\n```\n### Dependencies (recommended)\n- Recommended scenarios: single route, route set, FastAPI application.\n\n```python\nfrom fastapi import Depends\nfrom fastapi_user_auth.auth.models import User\n\n\n# Route parameter dependencies, this method is recommended\n@app.get(\"/auth/admin_roles_depend_1\")\ndef admin_roles(user: User = Depends(auth.get_current_user)):\n    return user  # Current request user object.\n\n\n# Path manipulation decorator dependencies\n@app.get(\"/auth/admin_roles_depend_2\", dependencies=[Depends(auth.requires('admin')())])\ndef admin_roles(request: Request):\n    return request.user\n\n\n# Global dependencies\n# All requests under the app require the admin role\napp = FastAPI(dependencies=[Depends(auth.requires('admin')())])\n\n\n@app.get(\"/auth/admin_roles_depend_3\")\ndef admin_roles(request: Request):\n    return request.user\n\n```\n### Middleware\n- Recommended scenario: FastAPI application\n```python\napp = FastAPI()\n# Attach `request.auth` and `request.user` objects before each request is processed under the app application\nauth.backend.attach_middleware(app)\n```\n\n### Call directly\n\n- Recommended scenario: non-routing method\n```python\nfrom fastapi_user_auth.auth.models import User\n\n\nasync def get_request_user(request: Request) -\u003e Optional[User]:\n    # user= await auth.get_current_user(request)\n    if await auth.requires('admin', response=False)(request):\n        return request.user\n    else:\n        return None\n```\n\n## Token Storage Backend\n`fastapi-user-auth` supports multiple token storage methods. The default is: `DbTokenStore`, it is recommended to customize it to: `JwtTokenStore`\n\n### JwtTokenStore\n- ` pip install fastapi-user-auth[jwt] `\n\n```python\nfrom fastapi_user_auth.auth.backends.jwt import JwtTokenStore\nfrom sqlalchemy_database import Database\nfrom fastapi_user_auth.auth import Auth\nfrom fastapi_amis_admin.admin.site import AuthAdminSite\n\n#Create a sync database engine\ndb = Database.create(url=\"sqlite:///amisadmin.db?check_same_thread=False\")\n\n# Use `JwtTokenStore` to create an auth object\nauth = Auth(\n    db=db,\n    token_store=JwtTokenStore(secret_key='09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7')\n)\n\n# Pass auth object to AdminSite\nsite = AuthAdminSite(\n    settings=Settings(),\n    db=db,\n    auth=auth\n)\n\n```\n\n### DbTokenStore\n```python\n# Create an auth object using `DbTokenStore`\nfrom fastapi_user_auth.auth.backends.db import DbTokenStore\n\nauth = Auth(\n    db=db,\n    token_store=DbTokenStore(db=db)\n)\n```\n### RedisTokenStore\n\n- `pip install fastapi-user-auth[redis] `\n\n```python\n# Use `RedisTokenStore` to create an auth object\nfrom fastapi_user_auth.auth.backends.redis import RedisTokenStore\nfrom redis.asyncio import Redis\n\nauth = Auth(\n    db=db,\n    token_store=RedisTokenStore(redis=Redis.from_url('redis://localhost?db=0'))\n)\n```\n## RBAC model\nThis system adopts the `Casbin RBAC` model and runs a role-based priority strategy.\n- Permissions can be assigned to roles or directly to users.\n- Users can have multiple roles.\n- A role can have multiple sub-roles.\n- The permission policy owned by the user has a higher priority than the permission policy of the role it owns.\n\n```mermaid\nflowchart LR\n    User -. m:n .-\u003e Role\n    User -. m:n .-\u003e CasbinRule\n    Role -. m:n .-\u003e Role\n    Role -. m:n .-\u003e CasbinRule \n```\n\n## Advanced expansion\n### Extend the `User` model\n\n```python\nfrom datetime import date\n\nfrom fastapi_amis_admin.models.fields import Field\nfrom fastapi_user_auth.auth.models import BaseUser\n\n# Customize the `User` model, inherit `BaseUser`\nclass MyUser(BaseUser, table = True):\n    point: float = Field(default = 0, title = 'Point', description = 'User points')\n    phone: str = Field(None, title = 'Phone', max_length = 15)\n    parent_id: int = Field(None, title = \"Superior\", foreign_key = \"auth_user.id\")\n    birthday: date = Field(None, title = \"date of birth\")\n    location: str = Field(None, title = \"Location\")\n\n# Use custom `User` model to create auth object\nauth = Auth(db = AsyncDatabase(engine), user_model = MyUser)\n```\n\n### Extend the `Role` model\n\n```python\nfrom fastapi_amis_admin.models.fields import Field\nfrom fastapi_user_auth.auth.models import Role\n\n\n# Customize `Role` model, inherit `Role`;\nclass MyRole(Role, table=True):\n    icon: str = Field(None, title='图标')\n    is_active: bool = Field(default=True, title=\"是否激活\")\n\n```\n\n### Customize `User Auth App` default management class\n\nThe default management classes can be overridden and replaced through inheritance.\nFor example: `UserLoginFormAdmin`, `UserRegFormAdmin`, `UserInfoFormAdmin`,\n`UserAdmin`,`RoleAdmin`\n\n```python\n# Customize the model management class, inherit and override the corresponding default management class\nclass MyRoleAdmin(admin.ModelAdmin):\n    page_schema = PageSchema(label='User group management', icon='fa fa-group')\n    model = MyRole\n    readonly_fields = ['key']\n\n\n# Customize user authentication application, inherit and override the default user authentication application\nclass MyUserAuthApp(UserAuthApp):\n    RoleAdmin = MyRoleAdmin\n\n\n# Customize the user management site, inherit and override the default user management site\nclass MyAuthAdminSite(AuthAdminSite):\n    UserAuthApp = MyUserAuthApp\n\n\n# Use the custom `AuthAdminSite` class to create a site object\nsite = MyAuthAdminSite(settings, auth=auth)\n```\n\n## ModelAdmin permission control\n\n### Field permissions\n\n- Inherit the `AutoField ModelAdmin` class to achieve field permission control. By assigning user and role permissions in the background.\n\n- `perm_fields_exclude`: Specify fields that do not require permission control.\n\n```python\nfrom fastapi_user_auth.mixins.admin import AuthFieldModelAdmin\nfrom fastapi_amis_admin.amis import PageSchema\nfrom fastapi_amis_admin.admin import FieldPermEnum\n\nclass AuthFieldArticleAdmin(AuthFieldModelAdmin):\n    page_schema = PageSchema(label=\"文章管理\")\n    model = Article\n    # Specify fields that do not need permission control. \n    perm_fields_exclude = {\n        FieldPermEnum.CREATE: [\"title\", \"description\", \"content\"],\n    }\n```\n\n### Data permissions\n\n- Inherit the `AuthSelectModelAdmin` class to achieve data permission control. By assigning user and role permissions in the background.\n- `select_permisions`: Specify permissions to query data.\n\n```python\nfrom fastapi_user_auth.mixins.admin import AuthSelectModelAdmin\nfrom fastapi_amis_admin.amis import PageSchema\nfrom fastapi_amis_admin.admin import RecentTimeSelectPerm, UserSelectPerm, SimpleSelectPerm\n\n\nclass AuthSelectArticleAdmin(AuthSelectModelAdmin):\n    page_schema = PageSchema(label=\"Dataset control article management\")\n    model = Article\n    select_permissions = [\n        # Data created in the last 7 days. reverse=True indicates reverse selection, that is, the data within the last 7 days is selected by default.\n        RecentTimeSelectPerm(name=\"recent7_create\", label=\"Created in the last 7 days\", td=60 * 60 * 24 * 7, reverse=True),\n        # Data created in the last 30 days\n        RecentTimeSelectPerm(name=\"recent30_create\", label=\"Created in the last 30 days\", td=60 * 60 * 24 * 30),\n        #Data updated in the last 3 days\n        RecentTimeSelectPerm(name=\"recent3_update\", label=\"Updated in the last 3 days\", td=60 * 60 * 24 * 3, time_column=\"update_time\"),\n        # You can only select the data you created. reverse=True means reverse selection, that is, the data you created is selected by default.\n        \n        UserSelectPerm(name=\"self_create\", label=\"Create yourself\", user_column=\"user_id\", reverse=True),\n        # # You can only select the data you updated\n        # UserSelectPerm(name=\"self_update\", label=\"Update yourself\", user_column=\"update_by\"),\n        # Only published data can be selected\n        SimpleSelectPerm(name=\"published\", label=\"Published\", column=\"is_published\", values=[True]),\n        # Only data with status [1,2,3] can be selected\n        SimpleSelectPerm(name=\"status_1_2_3\", label=\"Status is 1_2_3\", column=\"status\", values=[1, 2, 3]),\n    ]\n```\n\n## Interface preview\n\n- Open `http://127.0.0.1:8000/admin/auth/form/login` in your browser:\n\n![Login](https://s2.loli.net/2022/03/20/SZy6sjaVlBT8gin.png)\n\n- Open `http://127.0.0.1:8000/admin/` in your browser:\n\n![ModelAdmin](https://s2.loli.net/2022/03/20/ItgFYGUONm1jCz5.png)\n\n- Open `http://127.0.0.1:8000/admin/docs` in your browser:\n\n![Docs](https://s2.loli.net/2022/03/20/1GcCiPdmXayxrbH.png)\n\n## License Agreement\n\n- `fastapi-amis-admin` is open source and free to use based on `Apache2.0` and can be used for commercial purposes for free, but please clearly display the copyright information about FastAPI-Amis-Admin in the display interface.\n## Thanks\n\nThanks to the following developers for their contributions to FastAPI-User-Auth:\n\n\u003ca href=\"https://github.com/amisadmin/fastapi_user_auth/graphs/contributors\"\u003e\n  \u003cimg src=\"https://contrib.rocks/image?repo=amisadmin/fastapi_user_auth\"  alt=\"\"/\u003e\n\u003c/a\u003e","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Famisadmin%2Ffastapi-user-auth","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Famisadmin%2Ffastapi-user-auth","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Famisadmin%2Ffastapi-user-auth/lists"}