Пример #1
0
def register(json: UserRegisterSchema):
    """
    注册新用户
    """
    if manager.user_model.count_by_username(g.username) > 0:
        raise Duplicated("用户名重复,请重新输入")  # type: ignore
    if g.email and g.email.strip() != "":
        if manager.user_model.count_by_email(g.email) > 0:
            raise Duplicated("注册邮箱重复,请重新输入")  # type: ignore
    # create a user
    with db.auto_commit():
        user = manager.user_model()
        user.username = g.username
        if g.email and g.email.strip() != "":
            user.email = g.email
        db.session.add(user)
        db.session.flush()
        user.password = g.password
        group_ids = g.group_ids
        # 如果没传分组数据,则将其设定为 guest 分组
        if len(group_ids) == 0:
            from lin import GroupLevelEnum

            group_ids = [GroupLevelEnum.GUEST.value]
        for group_id in group_ids:
            user_group = manager.user_group_model()
            user_group.user_id = user.id
            user_group.group_id = group_id
            db.session.add(user_group)

    return Success("用户创建成功")  # type: ignore
Пример #2
0
def update_user(uid: int, json: UpdateUserInfoSchema):
    """
    更新用户信息
    """
    user = manager.user_model.get(id=uid)
    if user is None:
        raise NotFound("用户不存在")
    if user.email != g.email:
        exists = manager.user_model.get(email=g.email)
        if exists:
            raise ParameterError("邮箱已被注册,请重新输入邮箱")
    with db.auto_commit():
        user.email = g.email
        group_ids = g.group_ids
        # 清空原来的所有关联关系
        manager.user_group_model.query.filter_by(user_id=user.id).delete(
            synchronize_session=False)
        # 根据传入分组ids 新增关联记录
        user_group_list = list()
        # 如果没传分组数据,则将其设定为 guest 分组
        if not group_ids:
            group_ids = [
                manager.group_model.get(level=GroupLevelEnum.GUEST.value).id
            ]
        for group_id in group_ids:
            user_group = manager.user_group_model()
            user_group.user_id = user.id
            user_group.group_id = group_id
            user_group_list.append(user_group)
        db.session.add_all(user_group_list)
    return Success("操作成功")
Пример #3
0
def update_group(gid, json: GroupBaseSchema):
    """
    更新一个分组基本信息
    """
    exists = manager.group_model.get(id=gid)
    if not exists:
        raise NotFound("分组不存在,更新失败")
    exists.update(name=g.name, info=g.info, commit=True)
    return Success("更新成功")
Пример #4
0
def delete_book(id):
    """
    传入id删除对应图书
    """
    book = Book.get(id=id)
    if book:
        # 删除图书,软删除
        book.delete(commit=True)
        return Success(14)
    raise BookNotFound
Пример #5
0
def upload():
    image = request.files.get("image", None)
    if not image:
        raise ParameterError("没有找到图片")
    if image and allowed_file(image.filename):
        path = os.path.join(lin_config.get_config("oss.upload_folder"),
                            image.filename)
        image.save(path)
    else:
        raise ParameterError("图片类型不允许或图片key不合法")
    return Success()
Пример #6
0
def change_password(json: ChangePasswordSchema):
    """
    修改密码
    """
    user = get_current_user()
    ok = user.change_password(g.old_password, g.new_password)
    if ok:
        db.session.commit()
        return Success("密码修改成功")
    else:
        return Failed("修改密码失败")
Пример #7
0
def remove_auths(json: GroupIdWithPermissionIdListSchema):
    """
    删除多个权限
    """

    with db.auto_commit():
        db.session.query(manager.group_permission_model).filter(
            manager.group_permission_model.permission_id.in_(g.permission_ids),
            manager.group_permission_model.group_id == g.group_id,
        ).delete(synchronize_session=False)

    return Success("删除权限成功")
Пример #8
0
def change_user_password(uid: int, json: ResetPasswordSchema):
    """
    修改用户密码
    """

    user = manager.find_user(id=uid)
    if not user:
        raise NotFound("用户不存在")

    with db.auto_commit():
        user.reset_password(g.new_password)

    return Success("密码修改成功")
Пример #9
0
def update_book(id, json: BookInSchema):
    """
    更新图书信息
    """
    book = Book.get(id=id)
    if book:
        book.update(
            id=id,
            **json.dict(),
            commit=True,
        )
        return Success(13)
    raise BookNotFound
Пример #10
0
def dispatch_auths(json: GroupIdWithPermissionIdListSchema):
    """
    分配多个权限
    """
    with db.auto_commit():
        for permission_id in g.permission_ids:
            one = manager.group_permission_model.get(
                group_id=g.group_id, permission_id=permission_id)
            if not one:
                manager.group_permission_model.create(
                    group_id=g.group_id,
                    permission_id=permission_id,
                )
    return Success("添加权限成功")
Пример #11
0
def delete_user(uid):
    """
    删除用户
    """
    user = manager.user_model.get(id=uid)
    if user is None:
        raise NotFound("用户不存在")
    groups = manager.group_model.select_by_user_id(uid)
    # 超级管理员分组的用户仅有一个分组
    if groups[0].level == GroupLevelEnum.ROOT.value:
        raise Forbidden("无法删除此用户")
    with db.auto_commit():
        manager.user_group_model.query.filter_by(user_id=uid).delete(
            synchronize_session=False)
        user.hard_delete()
    return Success("操作成功")
Пример #12
0
def update(json: UserBaseInfoSchema):
    """
    更新用户信息
    """
    user = get_current_user()

    if g.email and user.email != g.email:
        exists = manager.user_model.get(email=g.email)
        if exists:
            raise ParameterError("邮箱已被注册,请重新输入邮箱")
    with db.auto_commit():
        if g.email:
            user.email = g.email
        if g.nickname:
            user.nickname = g.nickname
        if g.avatar:
            user._avatar = g.avatar
    return Success("用户信息更新成功")
Пример #13
0
def delete_group(gid):
    """
    删除一个分组
    """
    exist = manager.group_model.get(id=gid)
    if not exist:
        raise NotFound("分组不存在,删除失败")
    guest_group = manager.group_model.get(level=GroupLevelEnum.GUEST.value)
    root_group = manager.group_model.get(level=GroupLevelEnum.ROOT.value)
    if gid in (guest_group.id, root_group.id):
        raise Forbidden("不可删除此分组")
    if manager.user_model.select_page_by_group_id(gid, root_group.id):
        raise Forbidden("分组下存在用户,不可删除")
    with db.auto_commit():
        # 删除group id 对应的关联记录
        manager.group_permission_model.query.filter_by(group_id=gid).delete(
            synchronize_session=False)
        # 删除group
        exist.delete()
    return Success("删除分组成功")
Пример #14
0
def create_group(json: CreateGroupSchema):
    """
    新建分组
    """
    exists = manager.group_model.get(name=g.name)
    if exists:
        raise Forbidden("分组已存在,不可创建同名分组")
    with db.auto_commit():
        group = manager.group_model.create(
            name=g.name,
            info=g.info,
        )
        db.session.flush()
        group_permission_list = list()
        for permission_id in g.permission_ids:
            gp = manager.group_permission_model()
            gp.group_id = group.id
            gp.permission_id = permission_id
            group_permission_list.append(gp)
        db.session.add_all(group_permission_list)
    return Success("新建分组成功")
Пример #15
0
    resp=DocResponse(r=BookSchemaList),
    tags=["图书"],
)
def search(query: BookQuerySearchSchema):
    """
    关键字搜索图书
    """
    return Book.query.filter(
        Book.title.like("%" + g.q + "%"), Book.is_deleted == False
    ).all()


@book_api.route("", methods=["POST"])
@login_required
@api.validate(
    resp=DocResponse(Success(12)),
    security=[AuthorizationBearerSecurity],
    tags=["图书"],
)
def create_book(json: BookInSchema):
    """
    创建图书
    """
    Book.create(**json.dict(), commit=True)
    return Success(12)


@book_api.route("/<int:id>", methods=["PUT"])
@login_required
@api.validate(
    resp=DocResponse(Success(13)),
Пример #16
0
    total_page = math.ceil(total / g.count)
    page = get_page_from_query()
    return AdminUserPageSchema(count=g.count,
                               total=total,
                               total_page=total_page,
                               page=page,
                               items=users)


@admin_api.route("/user/<int:uid>/password", methods=["PUT"])
@permission_meta(name="修改用户密码", module="管理员", mount=False)
@admin_required
@api.validate(
    tags=["管理员"],
    resp=DocResponse(NotFound("用户不存在"), Success("密码修改成功")),
    security=[AuthorizationBearerSecurity],
)
def change_user_password(uid: int, json: ResetPasswordSchema):
    """
    修改用户密码
    """

    user = manager.find_user(id=uid)
    if not user:
        raise NotFound("用户不存在")

    with db.auto_commit():
        user.reset_password(g.new_password)

    return Success("密码修改成功")
Пример #17
0
def create_book(json: BookInSchema):
    """
    创建图书
    """
    Book.create(**json.dict(), commit=True)
    return Success(12)
Пример #18
0
    UserSchema,
)
from app.util.captcha import CaptchaTool
from app.util.common import split_group

user_api = Blueprint("user", __name__)


@user_api.route("/register", methods=["POST"])
@permission_meta(name="注册", module="用户", mount=False)
@Logger(template="管理员新建了一个用户")  # 记录日志
@admin_required
@api.validate(
    tags=["用户"],
    security=[AuthorizationBearerSecurity],
    resp=DocResponse(Success("用户创建成功"), Duplicated("字段重复,请重新输入")),
)
def register(json: UserRegisterSchema):
    """
    注册新用户
    """
    if manager.user_model.count_by_username(g.username) > 0:
        raise Duplicated("用户名重复,请重新输入")  # type: ignore
    if g.email and g.email.strip() != "":
        if manager.user_model.count_by_email(g.email) > 0:
            raise Duplicated("注册邮箱重复,请重新输入")  # type: ignore
    # create a user
    with db.auto_commit():
        user = manager.user_model()
        user.username = g.username
        if g.email and g.email.strip() != "":