Example #1
0
 def __register_account(self, data):
     # 先往数据库生成一个账号
     AdminUser.register_account(account=data['account'],
                                login_pwd=data['password'])
     if not MerchantInfo.query_merchant(MerchantEnum.TEST):
         MerchantInfo.create_merchant(m_name=MerchantEnum.TEST,
                                      m_type=MerchantTypeEnum.TEST)
Example #2
0
    def post(self):
        """
        后台用户登录
        :return:
        """
        form, error = AuthLoginForm.request_validate()
        if error:
            return error.as_response()

        user = AdminUser.query_user(account=form.account.data)
        if not user:
            return LoginAccountError().as_response()

        # 验证用户名密码是否正确
        if not AdminUser.verify_login(account=form.account.data, password=form.password.data):
            return LoginPasswordError().as_response()

        # 验证成功后,调用login_user,会在session中记录已经登录
        user = AdminUser.query_user(account=form.account.data)

        # 记录登录状态
        token = AdminLoginToken.generate_token(user.uid)

        # current_app.logger.debug('login ok, path: %s', request.path)

        return AdminLoginResponse(bs_data=dict(token=token)).as_response()
Example #3
0
    def post(self):
        """
        修改登录密码
        :return:
        """
        # 格式验证
        form, error = ResetWordForm().request_validate()
        if error:
            return error.as_response()

        # 获取用户ID
        uid = g.user.uid

        if not AdminUser.verify_password(uid=uid, password=form.ori_password.data):
            return PasswordError().as_response()

        if AdminUser.verify_password(uid=uid, password=form.new_password.data):
            return RePasswordError().as_response()

        flag = AdminUser.reset_password(
            uid=uid,
            login_pwd=form.new_password.data
        )
        if not flag:
            return NoSourceError().as_response()

        return ResponseSuccess().as_response()
Example #4
0
    def get(self):
        """
        后台管理员操作日志
        :return:
        """
        if not request.args:
            return ResponseSuccess(
                message="参数规则:?account=panda&date=20190901&export=1"
            ).as_response()

        account = request.args['account']
        if account:
            user = AdminUser.query_user(account=account)
            if not user:
                return ResponseSuccess(message="用户不存在,请检查参数。account:%s" %
                                       account).as_response()

        try:
            date = request.args.get('date')
            if date:
                date = DateTimeKit.str_to_datetime(
                    date, DateTimeFormatEnum.TIGHT_DAY_FORMAT, to_date=True)
            else:
                date = DateTimeKit.get_cur_date()
        except:
            return ResponseSuccess(
                message="请输入有效的查询日期,格式为:20190901").as_response()

        events = AdminLog.query_by_date(date)
        if account:
            events = events.filter_by(account=account)

        rst = list()

        for event in events:
            rst.append(
                dict(
                    create_time=event.create_time,
                    account=event.account,
                    url=event.url,
                    ip=event.ip,
                    module=event.module.desc,
                    model=event.model,
                    model_id=event.model_id,
                    data_before=event.data_before,
                    data_after=event.data_after,
                ))

        rst = sorted(rst, key=lambda x: x['create_time'], reverse=True)
        for x in rst:
            x['create_time'] = DateTimeKit.datetime_to_str(x['create_time'])

        if rst and request.args.get('export'):
            filename = 'admin_log_%s.csv' % DateTimeKit.datetime_to_str(
                date, DateTimeFormatEnum.TIGHT_DAY_FORMAT)
            return CsvKit.send_csv(rst,
                                   filename=filename,
                                   fields=rst[0].keys())

        return ResponseSuccess(bs_data=rst).as_response()
Example #5
0
def verify_credential(token):
    """
    使用basic auth进行JWT token鉴权
    加了装饰器 @auth.login_required 的view都需要先进这个函数进行token鉴权
    :param token:
    :return:
    """

    # 初始化g对象的error属性
    g.error = None

    rst = AdminLoginToken.verify_token(token)
    if isinstance(rst, (APIException, )):
        # token 验证失败
        g.error = rst
        return False

    # 账户被封处理
    user = AdminUser.query_user(uid=rst['uid'])
    if not user:
        # 用户不存在
        g.error = AccountNotExistError()
        return False

    if not user.is_active:
        g.error = DisableUserError()
        return False

    g.user = user
    return True
Example #6
0
    def __test_admin_token_auth(self, data):
        self.path = '/merchant/balance/edit'

        user = AdminUser.query_user(account=data['account'])

        # 测试没有token
        post_data = dict(
            name=MerchantEnum.TEST.name,
            adjustment_type=ManualAdjustmentType.MINUS.name,
            amount="200.34",
            reason="因为要改,所有就改了",
        )
        response = self.do_request(post_data)
        self.assertEqual(TokenBadError.code, response.status_code,
                         response.json['message'])
        self.assertEqual(TokenBadError.error_code, response.json['error_code'],
                         response.json['message'])

        # 测试token错误
        response = self.do_request(post_data)
        self.assertEqual(TokenBadError.code, response.status_code,
                         response.json['message'])
        self.assertEqual(TokenBadError.error_code, response.json['error_code'],
                         response.json['message'])

        # 生成token
        self.token = AdminLoginToken.generate_token(user.uid)
        # 验证token
        rst = AdminLoginToken.verify_token(self.token)
        self.assertNotIsInstance(rst, (APIException, ))

        # 测试token验证通过
        response = self.do_request(post_data)
        self.assertEqual(MerchantUpdateError.code, response.status_code,
                         response.json['message'])
        self.assertEqual(MerchantUpdateError.error_code,
                         response.json['error_code'], response.json['message'])

        AdminLoginToken.remove_token(user.uid)

        # token被删除,验证失败
        response = self.do_request(post_data)
        self.assertEqual(TokenExpiredError.code, response.status_code,
                         response.json['message'])
        self.assertEqual(TokenExpiredError.error_code,
                         response.json['error_code'], response.json['message'])
Example #7
0
 def get_admin_user(cls):
     return AdminUser.query_user(account=cls.admin_user_account)
Example #8
0
 def init_admin_user(cls):
     if not cls.get_admin_user():
         AdminUser.register_account(account=cls.admin_user_account,
                                    login_pwd=cls.password)