Esempio n. 1
0
def login(json: LoginSchema):
    """
    用户登录
    """
    # 校对验证码
    if current_app.config.get("LOGIN_CAPTCHA"):
        tag = request.headers.get("tag")
        secret_key = current_app.config.get("SECRET_KEY")
        serializer = JWSSerializer(secret_key)
        if g.captcha != serializer.loads(tag):
            raise Failed("验证码校验失败")  # type: ignore

    user = manager.user_model.verify(g.username, g.password)
    # 用户未登录,此处不能用装饰器记录日志
    Log.create_log(
        message=f"{user.username}登录成功获取了令牌",
        user_id=user.id,
        username=user.username,
        status_code=200,
        method="post",
        path="/cms/user/login",
        permission="",
        commit=True,
    )
    access_token, refresh_token = get_tokens(user)
    return LoginTokenSchema(access_token=access_token,
                            refresh_token=refresh_token)
Esempio n. 2
0
def check_user_token(token):
    serializer = JWSSerializer(settings.SECRET_KEY, 3600)
    try:
        data = serializer.loads(token)
    except BadData:
        data = None
    return data
Esempio n. 3
0
    def generate_auth_token(self):
        s = JWSSerializer(current_app.config.get('SECRET_KEY'))
        payload = {
            'user_id': self.id,
            'type': constants.AUTH_TOKEN,
            'gen_time': datetime.now().strftime("%m/%d/%Y, %H:%M:%S")
        }
        token = s.dumps(payload).decode()

        return token
Esempio n. 4
0
def get_captcha():
    """
    获取图形验证码
    """
    if not current_app.config.get("LOGIN_CAPTCHA"):
        return CaptchaSchema()  # type: ignore
    image, code = CaptchaTool().get_verify_code()
    secret_key = current_app.config.get("SECRET_KEY")
    serializer = JWSSerializer(secret_key)
    tag = serializer.dumps(code)
    return {"tag": tag, "image": image}
Esempio n. 5
0
    def verify_auth_token(token):
        s = JWSSerializer(current_app.config.get('SECRET_KEY'))
        try:
            data = s.loads(token)
            user_id = data['user_id']
            if data['type'] != constants.AUTH_TOKEN:
                raise ValueError('Invalid token type')
        except:
            return None

        return User.query.get(user_id)
Esempio n. 6
0
    def init_app(self, app):
        if not app:
            return

        self.secret_key = app.config["SECRET_KEY"]
        self.salt = app.config.get("JWT_SALT")
        self.expires_in = app.config.get("JWT_EXPIRES_IN")
        self.algorithm = app.config.get("JWT_ALGORITHM")
        self.serializer = JWSSerializer(self.secret_key, self.expires_in,
                                        salt=self.salt,
                                        algorithm_name=self.algorithm)
Esempio n. 7
0
    def init_app(self, app):
        if not app:
            return

        self.secret_key = app.config['SECRET_KEY']
        self.salt = app.config.get('JWT_SALT')
        expires_in = app.config.get('JWT_EXPIRES_IN')
        self.algorithm = app.config.get('JWT_ALGORITHM')
        self.serializer = JWSSerializer(
            self.secret_key, expires_in,
            salt=self.salt, algorithm_name=self.algorithm)
Esempio n. 8
0
def get_captcha():
    """
    获取图形验证码
    """
    if not current_app.config.get("LOGIN_CAPTCHA"):
        return {"tag": "", "image": ""}
    image, code = CaptchaTool().get_verify_code()
    secret_key = current_app.config.get("SECRET_KEY")
    serializer = JWSSerializer(secret_key)
    tag = str(serializer.dumps(code), encoding="utf-8")
    image = str(image, encoding="utf-8")
    return {"tag": tag, "image": image}
Esempio n. 9
0
    def validate(self, token):
        if token == 'AIRFLOW_REQUEST_TOKEN':  # for airflow
            return True

        if token == 'a1IYz2uuhGvlaCTARHpqiAbhMdvOGnpf':  # 后端请求导入sales_tagert时使用
            return True

        serializer = JWSSerializer(current_app.secret_key)
        try:
            data = serializer.loads(token)
            return data["username"] == "etl"
        except Exception:
            return False
Esempio n. 10
0
    def confirm(self, token):
        s = JWSSerializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except:
            return False

        if data.get('confirm') != self.id:
            print(data.get('confirm'), self.id)
            return False

        self.confirmed = True
        db.session.add(self)
        db.session.commit()
        return True
Esempio n. 11
0
    def generate_verify_email_url(self):
        """
        生成对应用户的邮箱验证的连接地址
        """
        # 组织用户数据
        data = {'id': self.id, 'email': self.eamil}

        # 进行加密
        serializer = JWSSerializer(settings.SECRET_KEY,
                                   constants.VERIFY_EMAIL_TOKEN_EXPIRES)
        token = serializer.dumps(data).decode()

        # 拼接验证的连接地址
        verify_url = 'http://www.meiduo.site:8000/success_verify_email.html?token=' + token

        return verify_url
Esempio n. 12
0
    def check_verify_email_token(token):
        """校验邮箱验证的token是否有效"""
        serializer = JWSSerializer(settings.SECRET_KEY)

        try:
            data = serializer.loads(token)
        except BadData:
            return None
        else:
            # 获取用户id和email
            id = data.get('id')
            email = data.get('email')

            user = User.objects.get(id=id, email=email)

            return user
Esempio n. 13
0
def login():
    form = LoginForm().validate_for_api()
    # 校对验证码
    if current_app.config.get("LOGIN_CAPTCHA"):
        tag = request.headers.get("tag")
        secret_key = current_app.config.get("SECRET_KEY")
        serializer = JWSSerializer(secret_key)
        if form.captcha.data != serializer.loads(tag):
            raise Failed("验证码校验失败")

    user = manager.user_model.verify(form.username.data, form.password.data)
    # 用户未登录,此处不能用装饰器记录日志
    Log.create_log(
        message=f"{user.username}登录成功获取了令牌",
        user_id=user.id,
        username=user.username,
        status_code=200,
        method="post",
        path="/cms/user/login",
        permission="",
        commit=True,
    )
    access_token, refresh_token = get_tokens(user)
    return {"access_token": access_token, "refresh_token": refresh_token}
Esempio n. 14
0
def generate_save_user_token(openid):
    serializer = JWSSerializer(settings.SECRET_KEY, 3600)
    data = {'openid': openid}
    token = serializer.dumps(data)
    return token.decode()
Esempio n. 15
0
def make_jws_serializer():
    jws_serializer = JWSSerializer(settings.SECRET_KEY, 3600)
    return jws_serializer
Esempio n. 16
0
 def generate_confirm_token(self, expiration=3600):
     s = JWSSerializer(current_app.config['SECRET_KEY'], expiration)
     print('generate user id:', self.id)
     return s.dumps({'confirm': self.id})
Esempio n. 17
0
 def login(self, username, password):
     if username != "etl" or password != "chaomengdata":
         raise LoginFailed()
     serializer = JWSSerializer(current_app.secret_key,
                                expires_in=24 * 60 * 60)
     return serializer.dumps({"username": "******"}).decode("utf-8")