Skip to content

Commit

Permalink
v0.2.1
Browse files Browse the repository at this point in the history
  • Loading branch information
amisadmin committed Aug 31, 2022
1 parent 207e33b commit 19d5b95
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 51 deletions.
89 changes: 39 additions & 50 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,32 +58,29 @@ from sqlmodel import SQLModel
app = FastAPI()

# 创建AdminSite实例
site = AuthAdminSite(settings=Settings(database_url_async='sqlite+aiosqlite:///amisadmin.db'))
site = AuthAdminSite(settings = Settings(database_url_async = 'sqlite+aiosqlite:///amisadmin.db'))
auth = site.auth
# 挂载后台管理系统
site.mount_app(app)


# 创建初始化数据库表
@app.on_event("startup")
async def startup():
await site.db.async_run_sync(SQLModel.metadata.create_all, is_session=False)
await site.db.async_run_sync(SQLModel.metadata.create_all, is_session = False)
# 创建默认测试用户, 请及时修改密码!!!
await auth.create_role_user('admin')
await auth.create_role_user('vip')


# 要求: 用户必须登录
@app.get("/auth/get_user")
@auth.requires()
def get_user(request: Request):
return request.user


if __name__ == '__main__':
import uvicorn

uvicorn.run(app, debug=True)
uvicorn.run(app, debug = True)

```

Expand All @@ -100,46 +97,40 @@ if __name__ == '__main__':
def user(request: Request):
return request.user # 当前请求用户对象.


# 验证路由: 用户拥有admin角色
@app.get("/auth/admin_roles")
@auth.requires('admin')
def admin_roles(request: Request):
return request.user


# 要求: 用户拥有vip角色
# 支持同步/异步路由
@app.get("/auth/vip_roles")
@auth.requires(['vip'])
async def vip_roles(request: Request):
return request.user


# 要求: 用户拥有admin角色 或 vip角色
@app.get("/auth/admin_or_vip_roles")
@auth.requires(roles=['admin', 'vip'])
@auth.requires(roles = ['admin', 'vip'])
def admin_or_vip_roles(request: Request):
return request.user


# 要求: 用户属于admin用户组
@app.get("/auth/admin_groups")
@auth.requires(groups=['admin'])
@auth.requires(groups = ['admin'])
def admin_groups(request: Request):
return request.user


# 要求: 用户拥有admin角色 且 属于admin用户组
@app.get("/auth/admin_roles_and_admin_groups")
@auth.requires(roles=['admin'], groups=['admin'])
@auth.requires(roles = ['admin'], groups = ['admin'])
def admin_roles_and_admin_groups(request: Request):
return request.user


# 要求: 用户拥有vip角色 且 拥有`article:update`权限
@app.get("/auth/vip_roles_and_article_update")
@auth.requires(roles=['vip'], permissions=['article:update'])
@auth.requires(roles = ['vip'], permissions = ['article:update'])
def vip_roles_and_article_update(request: Request):
return request.user

Expand All @@ -155,23 +146,19 @@ from typing import Tuple
from fastapi_user_auth.auth import Auth
from fastapi_user_auth.auth.models import User


# 路由参数依赖项, 推荐使用此方式
@app.get("/auth/admin_roles_depend_1")
@app.get("/auth/admin_roles_depend_1")
def admin_roles(user: User = Depends(auth.get_current_user)):
return user # or request.user

return user # or request.user

# 路径操作装饰器依赖项
@app.get("/auth/admin_roles_depend_2", dependencies=[Depends(auth.requires('admin')())])
@app.get("/auth/admin_roles_depend_2", dependencies = [Depends(auth.requires('admin')())])
def admin_roles(request: Request):
return request.user


# 全局依赖项
# 在app应用下全部请求都要求拥有admin角色
app = FastAPI(dependencies=[Depends(auth.requires('admin')())])

app = FastAPI(dependencies = [Depends(auth.requires('admin')())])

@app.get("/auth/admin_roles_depend_3")
def admin_roles(request: Request):
Expand All @@ -197,10 +184,9 @@ auth.backend.attach_middleware(app)
```python
from fastapi_user_auth.auth.models import User


async def get_request_user(request: Request) -> Optional[User]:
# user= await auth.get_current_user(request)
if await auth.requires('admin', response=False)(request):
if await auth.requires('admin', response = False)(request):
return request.user
else:
return None
Expand All @@ -219,14 +205,18 @@ from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy_database import AsyncDatabase

# 创建异步数据库引擎
engine = create_async_engine(url='sqlite+aiosqlite:///amisadmin.db', future=True)
engine = create_async_engine(url = 'sqlite+aiosqlite:///amisadmin.db', future = True)
# 使用`JwtTokenStore`创建auth对象
auth = Auth(db=AsyncDatabase(engine),
token_store=JwtTokenStore(secret_key='09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7'))
auth = Auth(
db = AsyncDatabase(engine),
token_store = JwtTokenStore(secret_key = '09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7')
)

# 将auth对象传入AdminSite
site = AuthAdminSite(settings=Settings(database_url_async='sqlite+aiosqlite:///amisadmin.db'),
auth=auth)
site = AuthAdminSite(
settings = Settings(database_url_async = 'sqlite+aiosqlite:///amisadmin.db'),
auth = auth
)

```

Expand All @@ -236,8 +226,10 @@ site = AuthAdminSite(settings=Settings(database_url_async='sqlite+aiosqlite:///a
# 使用`DbTokenStore`创建auth对象
from fastapi_user_auth.auth.backends.db import DbTokenStore

auth = Auth(db=AsyncDatabase(engine),
token_store=DbTokenStore(db=AsyncDatabase(engine)))
auth = Auth(
db = AsyncDatabase(engine),
token_store = DbTokenStore(db = AsyncDatabase(engine))
)
```

### RedisTokenStore
Expand All @@ -247,8 +239,10 @@ auth = Auth(db=AsyncDatabase(engine),
from fastapi_user_auth.auth.backends.redis import RedisTokenStore
from aioredis import Redis

auth = Auth(db=AsyncDatabase(engine),
token_store=RedisTokenStore(redis=Redis.from_url('redis://localhost?db=0')))
auth = Auth(
db = AsyncDatabase(engine),
token_store = RedisTokenStore(redis = Redis.from_url('redis://localhost?db=0'))
)
```

## RBAC模型
Expand All @@ -275,25 +269,23 @@ from datetime import date
from fastapi_amis_admin.models.fields import Field
from fastapi_user_auth.auth.models import BaseUser


# 自定义`User`模型,继承`BaseUser`
class MyUser(BaseUser, table=True):
birthday: date = Field(None, title="出生日期")
location: str = Field(None, title="位置")

class MyUser(BaseUser, table = True):
birthday: date = Field(None, title = "出生日期")
location: str = Field(None, title = "位置")

# 使用自定义的`User`模型,创建auth对象
auth = Auth(db=AsyncDatabase(engine), user_model=MyUser)
auth = Auth(db = AsyncDatabase(engine), user_model = MyUser)
```

### 拓展`Role`,`Group`,`Permission`模型

```python
# 自定义`Group`模型,继承`BaseRBAC`;覆盖`Role`,`Permission`模型类似,区别在于表名.
class MyGroup(BaseRBAC, table=True):
class MyGroup(BaseRBAC, table = True):
__tablename__ = 'auth_group' # 数据库表名,必须是这个才能覆盖默认模型
icon: str = Field(None, title='图标')
is_active: bool = Field(default=True, title="是否激活")
icon: str = Field(None, title = '图标')
is_active: bool = Field(default = True, title = "是否激活")

```

Expand All @@ -307,24 +299,21 @@ class MyGroup(BaseRBAC, table=True):
# 自定义模型管理类,继承重写对应的默认管理类
class MyGroupAdmin(admin.ModelAdmin):
group_schema = None
page_schema = PageSchema(label='用户组管理', icon='fa fa-group')
page_schema = PageSchema(label = '用户组管理', icon = 'fa fa-group')
model = MyGroup
link_model_fields = [Group.roles]
readonly_fields = ['key']


# 自定义用户认证应用,继承重写默认的用户认证应用
class MyUserAuthApp(UserAuthApp):
GroupAdmin = MyGroupAdmin


# 自定义用户管理站点,继承重写默认的用户管理站点
class MyAuthAdminSite(AuthAdminSite):
UserAuthApp = MyUserAuthApp


# 使用自定义的`AuthAdminSite`类,创建site对象
site = MyAuthAdminSite(settings, auth=auth)
site = MyAuthAdminSite(settings, auth = auth)
```

## 界面预览
Expand All @@ -350,6 +339,6 @@ site = MyAuthAdminSite(settings, auth=auth)
感谢以下开发者对 FastAPI-User-Auth 作出的贡献:

<a href="https://github.com/amisadmin/fastapi_user_auth/graphs/contributors">
<img src="https://contrib.rocks/image?repo=amisadmin/fastapi_user_auth" />
<img src="https://contrib.rocks/image?repo=amisadmin/fastapi_user_auth" alt=""/>
</a>

2 changes: 1 addition & 1 deletion fastapi_user_auth/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
__version__ = "0.2.0"
__version__ = "0.2.1"
__url__ = "https://github.com/amisadmin/fastapi_user_auth"

import gettext
Expand Down

0 comments on commit 19d5b95

Please sign in to comment.