Skip to content

Commit

Permalink
Merge pull request #38 from Mkadir/master
Browse files Browse the repository at this point in the history
Update with english
  • Loading branch information
amisadmin authored Mar 27, 2024
2 parents 900a975 + beaffef commit ed703b5
Show file tree
Hide file tree
Showing 12 changed files with 970 additions and 257 deletions.
254 changes: 114 additions & 140 deletions README.md

Large diffs are not rendered by default.

420 changes: 420 additions & 0 deletions README.zh.md

Large diffs are not rendered by default.

71 changes: 36 additions & 35 deletions fastapi_user_auth/admin/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from fastapi_amis_admin.crud.schema import BaseApiOut
from fastapi_amis_admin.models import Field
from fastapi_amis_admin.utils.pydantic import ModelField
from fastapi_amis_admin.utils.translation import i18n as _
from pydantic import BaseModel
from starlette.requests import Request
from starlette.responses import RedirectResponse
Expand Down Expand Up @@ -39,7 +40,7 @@ def get_admin_select_permission_rows(admin: PageSchemaAdmin) -> List[Dict[str, A
for perm in admin.select_permissions:
rows.append(
{
"label": "仅限数据-" + perm.label,
"label": _("Data only") + "-" + perm.label, # 仅限数据
"rol": f"{admin.unique_id}#page:select:{perm.name}#page:select",
"reverse": perm.reverse,
}
Expand Down Expand Up @@ -69,7 +70,7 @@ def get_admin_field_permission_rows(admin: PageSchemaAdmin, action: str) -> List
return []
rows.append(
{
"label": "全部",
"label": _("All"), # 全部
"rol": f"{admin.unique_id}#page:{action}:*#page:{action}",
}
)
Expand All @@ -93,7 +94,7 @@ def __init__(self, admin, **kwargs):
elif self.admin.model.__table__.name == User.__tablename__:
self._subject = "u"
else:
raise Exception("暂不支持的主体模型")
raise Exception(_("Subject model not supported yet")) # 暂不支持的主体模型

async def get_subject_by_id(self, item_id: str) -> str:
# 从数据库获取用户选择的数据列表
Expand All @@ -117,23 +118,23 @@ class UpdateSubRolesAction(BaseSubAction):
action = ActionType.Dialog(
name="update_subject_roles",
icon="fa fa-check",
tooltip="设置角色",
tooltip=_("Set up roles"), # 设置角色
dialog=amis.Dialog(),
level=LevelEnum.warning,
)

class schema(BaseModel):
role_keys: str = Field(
"",
title="角色列表",
title=_("role list"), # 角色列表
amis_form_item=amis.Transfer(
selectMode="table",
resultListModeFollowSelect=True,
columns=[
# {"name": "key", "label": "角色标识"},
{"name": "name", "label": "角色名称"},
{"name": "desc", "label": "角色描述"},
{"name": "role_names", "label": "子角色"},
{"name": "name", "label": _("Role Name")}, # 角色名称
{"name": "desc", "label": _("Role description")}, # 角色描述
{"name": "role_names", "label": _("sub-role")}, # 子角色
],
source="",
valueField="key",
Expand All @@ -158,18 +159,18 @@ async def get_init_data(self, request: Request, **kwargs) -> BaseApiOut[Any]:
return BaseApiOut(data=self.schema())
subject = await self.get_subject_by_id(item_id)
if not subject:
return BaseApiOut(status=0, msg="暂不支持的模型")
return BaseApiOut(status=0, msg=_("Models not supported yet")) # 暂不支持的模型
role_keys = await self.site.auth.enforcer.get_roles_for_user(subject)
return BaseApiOut(data=self.schema(role_keys=",".join(role_keys).replace("r:", "")))

async def handle(self, request: Request, item_id: List[str], data: schema, **kwargs):
"""更新角色Casbin权限"""
subject = await self.get_subject_by_id(item_id[0])
if not subject:
return BaseApiOut(status=0, msg="暂不支持的模型")
return BaseApiOut(status=0, msg=_("Models not supported yet")) # 暂不支持的模型
identity = await self.site.auth.get_current_user_identity(request) or SystemUserEnum.GUEST
if subject == "u:" + identity:
return BaseApiOut(status=0, msg="不能修改自己的权限")
return BaseApiOut(status=0, msg=_("Cannot modify own permissions")) # 不能修改自己的权限
enforcer: AsyncEnforcer = self.site.auth.enforcer
role_keys = [f"r:{role}" for role in data.role_keys.split(",") if role]
if role_keys and identity not in [SystemUserEnum.ROOT, SystemUserEnum.ADMIN]:
Expand All @@ -190,7 +191,7 @@ class BaseSubPermAction(BaseSubAction):
action = ActionType.Dialog(
name="view_subject_permissions",
icon="fa fa-check",
tooltip="查看权限",
tooltip=_("View permissions"), # 查看权限
dialog=amis.Dialog(),
level=LevelEnum.warning,
)
Expand All @@ -199,7 +200,7 @@ class BaseSubPermAction(BaseSubAction):
class schema(BaseModel):
permissions: str = Field(
"",
title="权限列表",
title=_("Permission list"), # 权限列表
amis_form_item=amis.InputTree(
multiple=True,
source="",
Expand Down Expand Up @@ -236,7 +237,7 @@ class ViewSubPagePermAction(BaseSubPermAction):
action = ActionType.Dialog(
name="view_subject_page_permissions",
icon="fa fa-check",
tooltip="查看页面权限",
tooltip=_("View page permissions"), # 查看页面权限
dialog=amis.Dialog(actions=[]),
level=LevelEnum.warning,
)
Expand All @@ -254,13 +255,13 @@ async def get_init_data(self, request: Request, **kwargs) -> BaseApiOut[Any]:
return BaseApiOut(data=self.schema())
subject = await self.get_subject_by_id(item_id)
if not subject:
return BaseApiOut(status=0, msg="暂不支持的模型")
return BaseApiOut(status=0, msg=_("Models not supported yet")) # 暂不支持的模型
permissions = await get_subject_page_permissions(self.site.auth.enforcer, subject=subject, implicit=self._implicit)
permissions = [perm.replace("#allow", "") for perm in permissions if perm.endswith("#allow")]
return BaseApiOut(data=self.schema(permissions=",".join(permissions)))

async def handle(self, request: Request, item_id: List[str], data: BaseModel, **kwargs):
return BaseApiOut(status=1, msg="请通过的【设置权限】更新设置!")
return BaseApiOut(status=1, msg=_("Please update settings through [Setting Permissions]!")) # 请通过的【设置权限】更新设置!


class UpdateSubDataPermAction(BaseSubPermAction):
Expand All @@ -271,18 +272,18 @@ class UpdateSubDataPermAction(BaseSubPermAction):
action = ActionType.Dialog(
name="update_subject_data_permissions",
icon="fa fa-gavel",
tooltip="更新数据权限",
dialog=amis.Dialog(actions=[amis.Action(actionType="submit", label="保存", close=False, primary=True)]),
tooltip=_("Update data permissions"), # 更新数据权限
dialog=amis.Dialog(actions=[amis.Action(actionType="submit", label=_("Save"), close=False, primary=True)]), # 保存
level=LevelEnum.warning,
)

# 创建动作表单数据模型
class schema(BaseSubPermAction.schema):
effect_matrix: list = Field(
[],
title="当前权限",
title=_("Current permissions"), # 当前权限
amis_form_item=amis.MatrixCheckboxes(
rowLabel="权限名称",
rowLabel=_("Permission name"), # 权限名称
multiple=False,
singleSelectMode="row",
source="",
Expand All @@ -291,9 +292,9 @@ class schema(BaseSubPermAction.schema):
)
policy_matrix: list = Field(
[],
title="权限配置",
title=_("Rights Profile"), # 权限配置
amis_form_item=amis.MatrixCheckboxes(
rowLabel="名称",
rowLabel=_("Name"), # 名称
multiple=False,
singleSelectMode="row",
yCheckAll=True,
Expand Down Expand Up @@ -333,15 +334,15 @@ async def get_admin_action_perm_options(
):
columns = [
{
"label": "默认",
"label": _("default"), # 默认
"col": "default",
},
{
"label": "是",
"label": _("allow"), # 是
"col": "allow",
},
{
"label": "否",
"label": _("deny"), # 否
"col": "deny",
},
]
Expand All @@ -355,7 +356,7 @@ async def get_admin_action_perm_options(
)
if not permission:
return out
unique_id, action, *_ = permission_decode(permission)
unique_id, action, *a = permission_decode(permission)
admin, parent = self.site.get_page_schema_child(unique_id)
if not admin:
return out
Expand Down Expand Up @@ -392,7 +393,7 @@ async def handle(self, request: Request, item_id: List[str], data: BaseModel, **
subject = await self.get_subject_by_id(item_id[0])
identity = await self.site.auth.get_current_user_identity(request) or SystemUserEnum.GUEST
if subject == "u:" + identity:
return BaseApiOut(status=0, msg="不能修改自己的权限")
return BaseApiOut(status=0, msg=_("Cannot modify own permissions")) # 不能修改自己的权限
msg = await update_subject_data_permissions(
self.site.auth.enforcer,
subject=subject,
Expand All @@ -410,7 +411,7 @@ class UpdateSubPagePermsAction(ViewSubPagePermAction):
action = ActionType.Dialog(
name="update_subject_page_permissions",
icon="fa fa-gavel",
tooltip="更新页面权限",
tooltip=_("Update page permissions"), # 更新页面权限
dialog=amis.Dialog(),
level=LevelEnum.warning,
)
Expand All @@ -419,10 +420,10 @@ async def handle(self, request: Request, item_id: List[str], data: BaseModel, **
"""更新角色Casbin权限"""
subject = await self.get_subject_by_id(item_id[0])
if not subject:
return BaseApiOut(status=0, msg="暂不支持的模型")
return BaseApiOut(status=0, msg=_("Models not supported yet")) # 暂不支持的模型
identity = await self.site.auth.get_current_user_identity(request) or SystemUserEnum.GUEST
if subject == "u:" + identity:
return BaseApiOut(status=0, msg="不能修改自己的权限")
return BaseApiOut(status=0, msg=_("Cannot modify own permissions")) # 不能修改自己的权限
# 权限列表
permissions = [perm for perm in data.permissions.split(",") if perm and perm.endswith("#page")] # 分割权限列表,去除空值
enforcer: AsyncEnforcer = self.site.auth.enforcer
Expand All @@ -439,20 +440,20 @@ class CopyUserAuthLinkAction(ModelAction):
action = amis.ActionType.Dialog(
name="copy_user_auth_link",
icon="fa fa-link",
tooltip="用户免登录链接",
tooltip=_("User login-free link"), # 用户免登录链接
level=amis.LevelEnum.danger,
dialog=amis.Dialog(
size=amis.SizeEnum.md,
title="用户免登录链接",
title=_("User login-free link"), # 用户免登录链接
),
)
form_init = True
form = amis.Form(static=True, disabled=True) # type: ignore # 禁用表单

class schema(UsernameMixin, PkMixin):
auth_url: str = Field(
title="授权链接",
description="复制链接到浏览器打开即可免登录",
title=_("Authorization link"), # 授权链接
description=_("Copy the link to your browser and open it without logging in"), # 复制链接到浏览器打开即可免登录
amis_form_item=amis.Static(
copyable=True,
),
Expand All @@ -470,7 +471,7 @@ async def get_init_data(self, request: Request, **kwargs) -> BaseApiOut[Any]:
}
token = await auth.backend.token_store.write_token(token_data)
return BaseApiOut(
msg="操作成功",
msg=_("Successful operation"), # 操作成功
data={**token_data, "auth_url": f"{str(request.base_url)[:-1]}{self.site.router_path}/login_by_token?token={token}"},
)

Expand Down
28 changes: 19 additions & 9 deletions fastapi_user_auth/admin/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,15 +271,20 @@ class UserAdmin(AuthFieldModelAdmin, AuthSelectModelAdmin, SoftDeleteModelAdmin,
lambda admin: UpdateSubPagePermsAction(
admin=admin,
name="update_subject_page_permissions",
tooltip="更新用户页面权限",
tooltip=_("Update user page permissions"), # 更新用户页面权限
),
lambda admin: UpdateSubDataPermAction(
admin=admin,
name="update_subject_data_permissions",
tooltip="更新用户数据权限",
tooltip=_("Update user data permissions"), # 更新用户数据权限
),
lambda admin: UpdateSubRolesAction(
admin=admin, name="update_subject_roles", tooltip="更新用户角色", icon="fa fa-user", flags="item"
admin=admin,
name="update_subject_roles",
tooltip=_("Update user role"),
icon="fa fa-user",
flags="item"
# 更新用户角色
),
lambda admin: CopyUserAuthLinkAction(admin),
]
Expand Down Expand Up @@ -328,15 +333,20 @@ class RoleAdmin(AutoTimeModelAdmin, FootableModelAdmin):
lambda admin: UpdateSubPagePermsAction(
admin=admin,
name="update_subject_page_permissions",
tooltip="更新角色页面权限",
tooltip=_("Update role page permissions"), # 更新角色页面权限
),
lambda admin: UpdateSubDataPermAction(
admin=admin,
name="update_subject_data_permissions",
tooltip="更新角色数据权限",
tooltip=_("Update role data permissions"), # 更新角色数据权限
),
lambda admin: UpdateSubRolesAction(
admin=admin, name="update_subject_roles", tooltip="更新子角色", icon="fa fa-user", flags="item"
admin=admin,
name="update_subject_roles",
tooltip=_("Update sub-roles"),
icon="fa fa-user",
flags="item"
# 更新子角色
),
]

Expand Down Expand Up @@ -364,7 +374,7 @@ class CasbinRuleAdmin(ReadOnlyModelAdmin):
admin=admin,
action=ActionType.Ajax(
id="refresh",
label="刷新权限",
label=_("Refresh permissions"), # 刷新权限
icon="fa fa-refresh",
level=LevelEnum.success,
api=f"GET:{admin.router_path}/load_policy",
Expand All @@ -390,14 +400,14 @@ def register_router(self):
async def _load_policy():
await self.load_policy()
get_admin_action_options.cache_clear() # 清除系统菜单缓存
return BaseApiOut(data="刷新成功")
return BaseApiOut(data=_("Refresh successful")) # 刷新成功

return super().register_router()


class LoginHistoryAdmin(ReadOnlyModelAdmin):
unique_id = "Auth>LoginHistoryAdmin"
page_schema = PageSchema(label="登录历史", icon="fa fa-history")
page_schema = PageSchema(label=_("Login history"), icon="fa fa-history") # 登录历史
model = LoginHistory
search_fields = [LoginHistory.login_name, LoginHistory.ip, LoginHistory.login_status, LoginHistory.user_agent]
list_display = [
Expand Down
13 changes: 10 additions & 3 deletions fastapi_user_auth/admin/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from casbin import AsyncEnforcer
from fastapi_amis_admin.admin import FormAdmin, ModelAdmin, PageSchemaAdmin
from fastapi_amis_admin.admin.admin import AdminGroup, BaseActionAdmin, BaseAdminSite
from fastapi_amis_admin.utils.translation import i18n as _

from fastapi_user_auth.auth.schemas import SystemUserEnum
from fastapi_user_auth.utils.casbin import permission_encode, permission_enforce
Expand All @@ -28,10 +29,16 @@ def get_admin_action_options(
if isinstance(admin, BaseActionAdmin):
item["children"] = []
if isinstance(admin, ModelAdmin):
item["children"].append({"label": "查看列表", "value": permission_encode(admin.unique_id, "page:list", "page")})
item["children"].append({"label": "筛选列表", "value": permission_encode(admin.unique_id, "page:filter", "page")})
item["children"].append(
{"label": _("View list"), "value": permission_encode(admin.unique_id, "page:list", "page")}
) # 查看列表
item["children"].append(
{"label": _("Filter list"), "value": permission_encode(admin.unique_id, "page:filter", "page")}
) # 筛选列表
elif isinstance(admin, FormAdmin) and "submit" not in admin.registered_admin_actions:
item["children"].append({"label": "提交", "value": permission_encode(admin.unique_id, "page:submit", "page")})
item["children"].append(
{"label": _("submit"), "value": permission_encode(admin.unique_id, "page:submit", "page")}
) # 提交
for admin_action in admin.registered_admin_actions.values():
# todo admin_action 下可能有多个action,需要遍历
item["children"].append(
Expand Down
6 changes: 3 additions & 3 deletions fastapi_user_auth/auth/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,15 +303,15 @@ async def request_login(self, request: Request, response: Response, username: st
login_name=username,
ip=request.client.host,
user_agent=request.headers.get("user-agent"),
login_status="登录成功",
login_status=_("Login successful"), # 登录成功
forwarded_for=forwarded_for,
)
self.db.add(history)
if not user:
history.login_status = "密码错误"
history.login_status = _("Wrong password") # 密码错误
return BaseApiOut(status=-1, msg=_("Incorrect username or password!"))
if not user.is_active:
history.login_status = "用户未激活"
history.login_status = _("User is not activated") # 用户未激活
return BaseApiOut(status=-2, msg=_("Inactive user status!"))
request.scope["user"] = user
token_info = UserLoginOut.parse_obj(request.user)
Expand Down
Loading

0 comments on commit ed703b5

Please sign in to comment.