chore: update users

This commit is contained in:
xtaodada 2024-11-07 14:12:47 +08:00
parent a63b96ae80
commit 986fc90826
Signed by: xtaodada
GPG Key ID: 4CBB3F4FA8C85659
7 changed files with 51 additions and 18 deletions

13
alembic/README.md Normal file
View File

@ -0,0 +1,13 @@
# 数据库迁移文件
## 生成数据库迁移文件
```shell
alembic revision --autogenerate -m "create table user"
```
## 执行数据库迁移
```shell
alembic upgrade head
```

View File

@ -1,8 +1,8 @@
"""users """users
Revision ID: 3785e9a2a0c0 Revision ID: 1d50ca81be81
Revises: Revises:
Create Date: 2024-11-04 19:12:43.374773 Create Date: 2024-11-07 13:45:48.829209
""" """
@ -12,7 +12,7 @@ import sqlmodel
from fastapi_user_auth.utils.sqltypes import SecretStrType from fastapi_user_auth.utils.sqltypes import SecretStrType
# revision identifiers, used by Alembic. # revision identifiers, used by Alembic.
revision = "3785e9a2a0c0" revision = "1d50ca81be81"
down_revision = None down_revision = None
branch_labels = None branch_labels = None
depends_on = None depends_on = None
@ -162,6 +162,12 @@ def upgrade() -> None:
sqlmodel.sql.sqltypes.AutoString(length=255), sqlmodel.sql.sqltypes.AutoString(length=255),
nullable=True, nullable=True,
), ),
sa.Column("sex", sqlmodel.sql.sqltypes.AutoString(length=15), nullable=True),
sa.Column(
"real_name",
sqlmodel.sql.sqltypes.AutoString(length=15),
nullable=True,
),
sa.Column("phone", sqlmodel.sql.sqltypes.AutoString(length=15), nullable=True), sa.Column("phone", sqlmodel.sql.sqltypes.AutoString(length=15), nullable=True),
sa.Column( sa.Column(
"student_id", "student_id",

View File

@ -34,22 +34,22 @@ class UserRoutes(Plugin):
@handler.post("/register", admin=False) @handler.post("/register", admin=False)
async def register(self, data: UserRegIn): async def register(self, data: UserRegIn):
if data.username.upper() in SystemUserEnum.__members__: if data.username.upper() in SystemUserEnum.__members__:
return BaseApiOut(status=500, msg="用户名已被注册", data=None) return BaseApiOut(status=500, msg="用户名已被注册")
user = await self.user_services.get_user(username=data.username) user = await self.user_services.get_user(username=data.username)
if user: if user:
return BaseApiOut(status=500, msg="用户名已被注册", data=None) return BaseApiOut(status=500, msg="用户名已被注册")
role = UserRoleEnum.STUDENT.value role = UserRoleEnum.STUDENT.value
if not (data.student_id or data.phone): if not (data.student_id or data.phone):
return BaseApiOut(status=500, msg="学号或手机号至少填写一项", data=None) return BaseApiOut(status=500, msg="学号或手机号至少填写一项")
if data.student_id: if data.student_id:
user = await self.user_services.get_user(student_id=data.student_id) user = await self.user_services.get_user(student_id=data.student_id)
if user: if user:
return BaseApiOut(status=500, msg="学号已被注册", data=None) return BaseApiOut(status=500, msg="学号已被注册")
role = UserRoleEnum.STUDENT.value role = UserRoleEnum.STUDENT.value
if data.phone: if data.phone:
user = await self.user_services.get_user(phone=data.phone) user = await self.user_services.get_user(phone=data.phone)
if user: if user:
return BaseApiOut(status=500, msg="手机号已被注册", data=None) return BaseApiOut(status=500, msg="手机号已被注册")
role = UserRoleEnum.OUT.value role = UserRoleEnum.OUT.value
# 检查通过,注册用户 # 检查通过,注册用户
try: try:
@ -58,6 +58,7 @@ class UserRoutes(Plugin):
password=data.password, password=data.password,
student_id=data.student_id, student_id=data.student_id,
phone=data.phone, phone=data.phone,
real_name=data.real_name,
) )
if not await self.user_role_services.is_user_in_role_group( if not await self.user_role_services.is_user_in_role_group(
data.username, role data.username, role
@ -124,7 +125,3 @@ class UserRoutes(Plugin):
) )
response.set_cookie("Authorization", f"bearer {token_info.access_token}") response.set_cookie("Authorization", f"bearer {token_info.access_token}")
return BaseApiOut(code=0, data=token_info) return BaseApiOut(code=0, data=token_info)
@handler.get("/need_login", student=True, out=True)
async def need_login(self):
return {}

View File

@ -13,7 +13,15 @@ class PhoneMixin(SQLModel):
phone: Optional[str] = Field("", title="电话号码", max_length=15) phone: Optional[str] = Field("", title="电话号码", max_length=15)
class UserModel(BaseUser, StudentIdMixin, PhoneMixin, table=True): class RealNameMixin(SQLModel):
__table_args__ = {"extend_existing": True} real_name: Optional[str] = Field("", title="真实姓名", max_length=15)
email: Optional[str] = None
class SexMixin(SQLModel):
sex: Optional[str] = Field("", title="性别", max_length=15)
class UserModel(
BaseUser, StudentIdMixin, PhoneMixin, RealNameMixin, SexMixin, table=True
):
__table_args__ = {"extend_existing": True}

View File

@ -3,7 +3,6 @@ from typing import Optional
from fastapi_user_auth.auth import Auth from fastapi_user_auth.auth import Auth
from fastapi_user_auth.auth.backends.redis import RedisTokenStore from fastapi_user_auth.auth.backends.redis import RedisTokenStore
from fastapi_user_auth.auth.models import CasbinRule, LoginHistory from fastapi_user_auth.auth.models import CasbinRule, LoginHistory
from fastapi_user_auth.utils.casbin import update_subject_roles
from persica.factory.component import AsyncInitializingComponent from persica.factory.component import AsyncInitializingComponent
from pydantic import SecretStr from pydantic import SecretStr
from sqlmodel import select from sqlmodel import select
@ -44,6 +43,7 @@ class UserRepo(AsyncInitializingComponent):
password: SecretStr, password: SecretStr,
student_id: Optional[str], student_id: Optional[str],
phone: Optional[str], phone: Optional[str],
real_name: Optional[str],
): ):
password = self.AUTH.pwd_context.hash(password.get_secret_value()) password = self.AUTH.pwd_context.hash(password.get_secret_value())
values = { values = {
@ -51,6 +51,7 @@ class UserRepo(AsyncInitializingComponent):
"password": password, "password": password,
"student_id": student_id, "student_id": student_id,
"phone": phone, "phone": phone,
"real_name": real_name,
} }
user = self.user_model.model_validate(values) user = self.user_model.model_validate(values)
async with AsyncSession(self.engine) as session: async with AsyncSession(self.engine) as session:

View File

@ -8,7 +8,7 @@ from fastapi_user_auth.utils.sqltypes import SecretStrType
from pydantic import BaseModel, SecretStr from pydantic import BaseModel, SecretStr
from sqlmodel import Field from sqlmodel import Field
from .models import UserModel, StudentIdMixin, PhoneMixin from .models import UserModel, StudentIdMixin, PhoneMixin, RealNameMixin, SexMixin
class BaseTokenData(BaseModel): class BaseTokenData(BaseModel):
@ -35,7 +35,13 @@ class UserLoginOut(UserModel):
) )
class UserRegIn(UsernameMixin, PasswordMixin, StudentIdMixin, PhoneMixin): class UserRegIn(
UsernameMixin,
PasswordMixin,
StudentIdMixin,
PhoneMixin,
RealNameMixin,
):
"""用户注册""" """用户注册"""
password2: str = Field(title=_("Confirm Password"), max_length=128) password2: str = Field(title=_("Confirm Password"), max_length=128)

View File

@ -23,12 +23,14 @@ class UserServices(AsyncInitializingComponent):
password: SecretStr, password: SecretStr,
student_id: Optional[str], student_id: Optional[str],
phone: Optional[str], phone: Optional[str],
real_name: Optional[str],
): ):
return await self.repo.register_user( return await self.repo.register_user(
username, username,
password, password,
student_id, student_id,
phone, phone,
real_name,
) )
async def login_user(self, user: "UserModel") -> str: async def login_user(self, user: "UserModel") -> str: