예제 #1
0
def users(
    temp_db_instance_helper: INS_HELPER["User"], ) -> Iterator[List["User"]]:
    from smorest_sfs.modules.users.models import User, UserInfo
    from smorest_sfs.modules.groups.models import Group
    from smorest_sfs.modules.roles.models import Role

    for _ in temp_db_instance_helper(
            User(
                username="******",
                password="******",
                userinfo=UserInfo(),
                roles=Role.where(name__in=["c", "f"]).all(),
                groups=Group.where(name="group_with_c_f").all(),
            ),
            User(
                username="******",
                password="******",
                userinfo=UserInfo(),
                roles=Role.where(name__in=["a", "b", "c"]).all(),
                groups=Group.where(name="group_with_a_b_c").all(),
            ),
            User(
                username="******",
                password="******",
                userinfo=UserInfo(),
                roles=Role.where(name__in=["f"]).all(),
                groups=Group.where(name="group_with_f").all(),
            ),
    ):
        yield _
예제 #2
0
def create_user(user: User, is_admin: bool = False) -> User:
    """
    创建用户

    :param              user: User                  用户ORM
    :param              is_admin: bool              是否admin

    创建头像信息,创建用户基本信息
    """
    user.roles = Role.get_by_user_default(is_admin)
    avator = Storages(**ADMIN_AVATOR) if is_admin else Storages(**USER_AVATOR)
    user.userinfo.avator = avator
    return user.save()
예제 #3
0
def test_model_creation(db: SQLAlchemy) -> None:
    from smorest_sfs.modules.users.models import User, UserInfo

    user = User.create(username="******", password="******", userinfo=UserInfo())
    db.session.commit()

    assert (
        user.nickname == "1212"
        and user.password == "1212"
        and str(user.userinfo) == "1212"
    )

    UserInfo.where(id_=user.userinfo.id_).delete()
    User.where(id_=user.id_).delete()
예제 #4
0
def init_development_users(password: Optional[str] = None) -> None:
    """
    初始化数据
    """
    su_role = Role.get_by_name(name="SuperUser")
    if not password:
        print("请输入初始超级用户密码")
        password = getpass("Password:"******"wisdom",
        password=password,
        email="*****@*****.**",
        phonenum="1234567",
        active=True,
        confirmed_at=datetime.utcnow(),
    )
    avator = Storages(
        name="AdminAvator.jpg",
        storetype="avator",
        saved=True,
        filetype="image/jpeg",
        path="default/AdminAvator.jpg",
        uid=1,
        store=load_avator_from_path("default/AdminAvator.jpg"),
    )
    UserInfo.create(user=root, avator=avator)
    root.roles.append(su_role)
    root.save()
예제 #5
0
def init():
    """
    初始化数据
    """
    su_role = Role.get_by_name(name="SuperUser")

    # create super user
    root = User.create(
        username="******",
        password="******",
        email="*****@*****.**",
        phonenum="1234567",
        active=True,
        confirmed_at=datetime.utcnow(),
    )
    avator = Storages(
        name="AdminAvator.jpg",
        storetype="avator",
        saved=True,
        filetype="image/jpeg",
        path="default/AdminAvator.jpg",
        uid=1,
    )
    UserInfo.create(user=root, avator=avator)
    root.roles.append(su_role)
    root.save()
예제 #6
0
def get_roles(res: Dict[str, Any]) -> Set[str]:
    from smorest_sfs.modules.users.models import User

    uids = [i["id"] for i in res["users"]]
    roles_iter = iter(  # type: ignore
        set(r.name for r in user.roles) for user in User.id_in(uids).all()
    )
    return reduce(lambda x, y: x & y, roles_iter)
예제 #7
0
파일: auth.py 프로젝트: ssfdust/smorest-sfs
    def _check_user(self) -> bool:
        self.user = User.get_by_keyword(self.email)

        if self.user.active is not True:
            logger.warning(f"{self.user.email} 未激活,尝试登录")
            abort(403, message="用户未激活")

        return True
예제 #8
0
def create_user(context, email, is_admin=True, is_active=True):
    # pylint: disable=unused-argument
    """
    新建用户
    """
    from smorest_sfs.services.users import create_user as _create_user
    from smorest_sfs.modules.users.models import User, UserInfo

    username = email.split("@")[0]
    password = getpass.getpass("Password:"******"L")

    _create_user(user, is_admin)
예제 #9
0
 def test_register(self):
     with self.flask_app.test_request_context():
         data = self._get_data(
             username="******", email="*****@*****.**", phonenum="1234"
         )
         url = url_for("User.UserRegisterView")
         resp = self.flask_app_client.put(url, json=data)
         fake_user = User.get_by_keyword("fake_user")
         assert resp.status_code == 200 and {r.name for r in fake_user.roles} == {
             ROLES.User
         }
예제 #10
0
def fake_users(
    flask_app: Flask,
    temp_db_instance_helper: Callable[..., Iterator[Any]],
) -> Iterator[Tuple[User, ...]]:
    # pylint: disable=W0613
    for _ in temp_db_instance_helper(
            User(
                username="******",
                password="******",
                email="fake_1",
                active=True,
                roles=Role.where(name__in=["f", "a"]).all(),
                userinfo=UserInfo(),
            ),
            User(
                username="******",
                password="******",
                email="fake_2",
                active=True,
                roles=Role.where(name__in=["c", "a", "b"]).all(),
                groups=[Group.find_or_fail(4)],
                userinfo=UserInfo(),
            ),
            User(
                username="******",
                password="******",
                email="fake_3",
                active=True,
                groups=[Group.find(5)],
                roles=Role.where(name__in=["f", "c"]).all(),
                userinfo=UserInfo(),
            ),
            User(
                username="******",
                password="******",
                email="fake_4",
                active=True,
                roles=Role.where(name__in=["f", "a", "c", "d", "e"]).all(),
                groups=[Group.find(6)],
                userinfo=UserInfo(),
            ),
            User(
                username="******",
                password="******",
                email="fake_5",
                active=True,
                userinfo=UserInfo(),
            ),
            User(
                username="******",
                password="******",
                email="fake_6",
                active=True,
                userinfo=UserInfo(),
            ),
    ):
        yield _
예제 #11
0
    def post(
        self, args: Dict[str, str]
    ) -> Dict[str, Union[int, str, Dict[str, Dict[str, str]]]]:
        """
        用户登录

        用户名密码登录后,返回基本信息以及token,
        登录方式为token方式
        """
        user = User.get_by_keyword(args["email"])
        with UserLoginChecker(user, args["password"], args["captcha"],
                              args["token"]).check() as user:
            data = login_user(user)

        return {"code": 0, "msg": "success", "data": data}
예제 #12
0
    def test_register(self) -> None:
        from smorest_sfs.modules.users.models import User

        with self.flask_app.test_request_context():
            data = self._get_data(
                username="******", email="*****@*****.**", phonenum="1234"
            )
            url = url_for("User.UserRegisterView")
            resp = self.flask_app_client.put(url, json=data)
            fake_user = User.get_by_keyword("fake_user")
            assert (
                resp.status_code == 200
                and {r.name for r in fake_user.roles} >= {"a", "User"}
                and {g.name for g in fake_user.groups} >= {"默认用户组"}
            )
예제 #13
0
def confirm_current_token(token_type: str, revoked: bool = True) -> User:
    """
    验证token

    :param jti: str jti字符串
    :param token_type: str token类型
    :param revoked 是否撤销token
    :return (state, user)
    """
    try:
        jti = get_raw_jwt()["jti"]
        token = TokenBlackList.where(jti=jti, token_type=token_type).one()
        token.update(revoked=revoked)
        user = User.get_by_keyword(token.user_identity)
    except NoResultFound:
        abort(403, message="token无效")
    return user
예제 #14
0
def create_user(user: User, is_admin: bool = False) -> User:
    """
    创建用户

    :param              user: User                  用户ORM
    :param              is_admin: bool              是否admin

    创建头像信息,创建用户基本信息
    """
    user.roles = Role.get_by_user_default(is_admin)
    avator = (
        Storages(  # type: ignore
            store=load_avator_from_path(ADMIN_AVATOR["path"]),
            saved=True,
            **ADMIN_AVATOR) if is_admin else Storages(  # type: ignore
                store=load_avator_from_path(USER_AVATOR["path"]),
                saved=True,
                **USER_AVATOR))
    user.userinfo.update(avator=avator)
    return user
예제 #15
0
    def post(self, email: str) -> Dict[str, Union[str, int]]:
        """
        忘记密码

        发送忘记密码邮件到请求的email
        """
        user = User.get_by_keyword(email)
        if not user:
            abort(404, message="用户不存在")
        logger.info(f"{user.email}发起了忘记密码申请")

        token = generate_confirm_token(user, "passwd")
        url = url_for("Auth.ResetForgotPasswordView",
                      token=token,
                      _external=True)
        sender = PasswdMailSender(to=user.email,
                                  content={
                                      "url": url,
                                      "message": "找回密码"
                                  })
        sender.send()

        return {"code": 0, "msg": "success"}
예제 #16
0
def generate_user_instance(
    user_id: Optional[int] = None,
    username: Optional[str] = "username",
    phonenum: Optional[str] = None,
    password: Optional[str] = None,
    email: Optional[str] = None,
    is_active: bool = True,
) -> User:
    """
    Returns:
        user_instance (User) - an not committed to DB instance of a User model.
    """

    if password is None:
        password = "******" % username
    user_instance = User(id=user_id,
                         phonenum=phonenum or "12345678",
                         active=is_active,
                         username=username,
                         email=email or "*****@*****.**" % username,
                         password=password,
                         userinfo=UserInfo(sex=1, age=1))
    return user_instance
예제 #17
0
def generate_user_instance(
    username: str = "username",
    phonenum: Optional[str] = None,
    is_active: bool = True,
    **kwargs: Any
) -> "User":
    """
    Returns:
        user_instance (User) - an not committed to DB instance of a User model.
    """
    from smorest_sfs.modules.users.models import User, UserInfo

    password = "******" % username
    user_instance = User(
        id_=kwargs.get("user_id", None),
        phonenum=phonenum or "12345678",
        active=is_active,
        username=username,
        email="*****@*****.**" % username,
        password=password,
        userinfo=UserInfo(sex=1, age=1),
    )
    return user_instance
예제 #18
0
def get_user(identity: str) -> User:
    return User.get_by_keyword(identity)
예제 #19
0
def test_get_by_unique(regular_user, key):
    user = User.get_by_keyword(key)
    assert user is regular_user
예제 #20
0
def test_get_by_unique(regular_user: "******", key: str) -> None:
    from smorest_sfs.modules.users.models import User

    user = User.get_by_keyword(key)
    assert user is regular_user
예제 #21
0
def get_roles(res: Dict[str, Any]) -> Set[str]:
    uids = [i["id"] for i in res["users"]]
    roles_iter = iter(
        set(r.name for r in user.roles) for user in User.where(id__in=uids).all()
    )
    return reduce(lambda x, y: x & y, roles_iter)