예제 #1
0
def get_token_status(token, operation, return_data=False):
    """Returns the expired status, invalid status, the user and optionally
    the content of the JSON Web Signature token.

    :param token: A valid JSON Web Signature token.
    :param operation: The function of the token.
    :param return_data: If set to ``True``, it will also return the content
                        of the token.
    """
    s = TimedJSONWebSignatureSerializer(current_app.config['SECRET_KEY'])
    user, data = None, None
    expired, invalid = False, False

    try:
        data = s.loads(token)
    except SignatureExpired:
        expired = True
    except (BadSignature, TypeError, ValueError):
        invalid = True

    if data is not None:
        # check if the operation matches the one from the token
        if operation == data.get("op", None):
            user = User.query.filter_by(id=data.get('id')).first()
        else:
            invalid = True

    if return_data:
        return expired, invalid, user, data

    return expired, invalid, user
예제 #2
0
 def verify_auth_token(token):
     s = Serializer(current_app.config['SECRET_KEY'])
     try:
         data = s.loads(token)
     except:
         return None
     return User.query.get(data['id'])
예제 #3
0
 def verify_auth_token(token):
     s = Serializer(app.config['SECRET_KEY'])
     try:
         data = s.loads(token)
         # just to make sure what is inside data
         # app.logger.info('The data inside token :' + str(data['id']))
     except SignatureExpired:
         # this line below is not necessary et al
         # comment this line to avoid error: local variable 'data' referenced before assignment
         # Sess.query.filter_by(user_id=data['id']).first().logged_in = False
         db.session.commit()
         app.logger.info('TOKEN :: Token expired.')
         return None # valid token, but expired
     # logout stuck in here. dunno why
     except BadSignature:
         # comment this line to avoid error: local variable 'data' referenced before assignment
         # Sess.query.filter_by(user_id=data['id']).first().logged_in = False
         db.session.commit()
         app.logger.info('TOKEN :: Invalid token.')
         return None # invalid token
     if not Sess.query.filter_by(user_id=data['id']).first().logged_in:
         app.logger.info('TOKEN :: Not login yet')
         return None 
     user = User.query.get(data['id'])
     return user
예제 #4
0
파일: api.py 프로젝트: eldoroshi/project
def generate_auth_token():

	s = Serializer(app.config['SECRET_KEY'], expires_in=3600)

        token = s.dumps({"id": "2"})
	
	return token
예제 #5
0
파일: models.py 프로젝트: GradPaul/GradPaul
 def verify_auth_token(token):
     s = Serializer('SECRET_KEY')
     try:
         data = s.loads(token)
     except:
         return None
     return User.objects(student_id=data['id']).first()
예제 #6
0
    def generate_confirmation_token(self, expiration=3600):
        """generate_confirmation_token:生成token

        :param expiration:
        """
        s = Serializer(current_app.config['SECRET_KEY'], expiration)
        return s.dumps({'confirm': self.id})
예제 #7
0
    def generate_reset_token(self, expiration=3600):
        """generate_reset_token:重置token信息

        :param expiration:
        """
        s = Serializer(current_app.config['SECRET_KEY'], expiration)
        return s.dumps({'reset': self.id})
예제 #8
0
파일: auth.py 프로젝트: xfilipe/socialcat
def get_user_by_token(token):
    s = Serializer(current_app.config['SECRET_KEY'])
    try:
        data = s.loads(token)
    except:
        return None
    return mongo.db.users.find_one(ObjectId(data['id']))
예제 #9
0
 def generate_confirmation_token(self, expiration=3600):
     """
     # 生成一个令牌,有效期默认是一个小时,
     令牌是个名值对,名字是confirm,值是根据id生成的。
     """
     s = Serializer(current_app.config['SECRET_KEY'], expiration)
     return s.dumps({'confirm': self.id})
예제 #10
0
 def generate_auth_token(self, expiration):
     """generate a token"""
     s = Serializer(
         current_app.config['SECRET_KEY'],
         expiration
     )
     return s.dumps({'id': self.id})
예제 #11
0
 def generate_auth_token(self, expiration=3600):
     """
     generate an authorization token used for API accesss
     """
     s = Serializer(
         current_app.config.get('SECRET_KEY'), expires_in=expiration)
     return s.dumps(str(self.id))
예제 #12
0
파일: models.py 프로젝트: xu00wei/flasky
 def confirm_uid_token(token):
     s = Serializer(current_app.config["CONVEY_UID_KEY"])
     try:
         data = s.loads(token)
     except:
         return None
     return User.query.get(data["id"])
예제 #13
0
파일: models.py 프로젝트: xu00wei/flasky
 def confirm_auth_token(token):
     s = Serializer(current_app.config["SECRET_KEY"])
     try:
         data = s.loads(token)
     except:
         return None
     return User.query.get(data["id"])
예제 #14
0
 def generate_auth_token(self, expiration = 600):
     s = Serializer(secret_key, expires_in=expiration)
     print ("secret key = ", secret_key)
     print ("dumps = ", s.dumps({"id": self.id}))
     serializedData = s.dumps({"id": self.id})
     print ("dumps = ", s.loads(serializedData))
     return s.dumps({"id": self.id})
예제 #15
0
파일: models.py 프로젝트: drowolath/dvbbox
 def verify_auth_token(token):
     s = Serializer(current_app.config['SECRET_KEY'])
     try:
         data = s.loads(token)
         return User(data['username'])
     except:
         return None
예제 #16
0
파일: models.py 프로젝트: CludeX/guisheng2
 def generate_auth_token(self, expiration):
     """ 生成验证token:验证字段id """
     s = Serializer(
             current_app.config["SECRET_KEY"],
             expiration
             )
     return s.dumps({'id': self.id}).decode('ascii')
예제 #17
0
def load_token(token, key, secret_key=os.environ.get('SECRET_KEY')):
    s = Serializer(secret_key)
    try:
        data = s.loads(token)
    except:
        return None
    return data.get(key)
예제 #18
0
    def get_auth_token(self):
        """
        Return an authentication token for the user. The auth token uniquely
        identifies the user and includes the salted hash of the password, then
        encrypted with a Timed serializer.

        The token_validity_duration can be set in application configuration
        using TOKEN_VALIDITY_DURATION
        """
        serializer = TimedJSONWebSignatureSerializer(
            current_app.secret_key,
            expires_in=current_app.token_validity_duration
        )
        local_txn = None
        if Transaction().cursor is None:
            # Flask-Login can call get_auth_token outside the context
            # of a nereid transaction. If that is the case, launch a
            # new transaction here.
            local_txn = Transaction().start(
                current_app.database_name, 0, readonly=True
            )
            self = self.__class__(self.id)
        try:
            return serializer.dumps({'id': self.id, 'password': self.password})
        finally:
            if local_txn is not None:
                Transaction().stop()
예제 #19
0
    def test_make_token_auth(self):
        user = self.us.create(u'warlock', u'*****@*****.**', u'qwerty')

        s = TokenSerializer(config.SECRET_KEY, expires_in=config.SESSION_EXPIRES)
        token = s.dumps({u'login': user[u'login']})

        self.assertEqual(token, self.us.make_auth_token(user), u'Tokens are not equal.')
예제 #20
0
 def verify_reset_token(token):
     s = Serializer(current_app.config['SECRET_KEY'])
     try:
         user_id = s.loads(token)['user_id']
     except:
         return None
     return User.query.get(user_id)
예제 #21
0
    def load_user_from_token(cls, token):
        """
        Implements the token_loader method for Flask-Login

        :param token: The token sent in the user's request
        """
        serializer = TimedJSONWebSignatureSerializer(
            current_app.secret_key,
            expires_in=current_app.token_validity_duration
        )

        try:
            data = serializer.loads(token)
        except SignatureExpired:
            return None     # valid token, but expired
        except BadSignature:
            return None     # invalid token

        user = cls(data['id'])
        if user.password != data['password']:
            # The password has been changed by the user. So the token
            # should also be invalid.
            return None

        return user
예제 #22
0
파일: users.py 프로젝트: thundernet8/Plog
 def reset_user_password(token, new_password):
     """
     重置用户密码
     :param token: 用于验证的 token
     :param new_password: 新密码
     :return: 成功返回 True,否则返回 False
     """
     s = Serializer(current_app.config['SECRET_KEY'])
     try:
         data = s.loads(token)
     except:
         return False
     user = User(email=data.get('email'))
     if not user or not user.user_id:
         return False
     if data.get('reset_uid') != user.user_id:
         return False
     user.raw_password = new_password
     mongo.db.users.update_one({
         'user_id': user.user_id
     }, {
         '$set': {
             'password': user.password
         }
     })
     return True
예제 #23
0
파일: models.py 프로젝트: cymoo/very-simple
 def confirm_token(token):
     s = Serializer(db.app.config['SECRET_KEY'])
     try:
         data = s.loads(token)
     except:
         return False
     return data.get('user_id')
예제 #24
0
파일: misc.py 프로젝트: ismix/frewmo
def detokenize(token, field=None):
    s = Serializer(flask.current_app.config['SECRET_KEY'])
    try:
        item = s.loads(token)
        return item.get(field,None) if field else item
    except BadSignature:
        return None
예제 #25
0
파일: views.py 프로젝트: LiGhT1EsS/PISS
def register():
    register_form = RegisterForm()
    data = {
        'title': 'Register',
        'form': register_form,
    }

    if register_form.validate_on_submit():
        # get data from form
        username = register_form.username.data
        password = register_form.password.data
        confirm_password = register_form.confirmPassword.data
        email = register_form.email.data

        # check data
        if len(username) < 2:
            flash(u'用户名长度不能小于2!', 'danger')
            return redirect(url_for('register'))
        if password != confirm_password:
            flash(u'两次密码不匹配!', 'danger')
            return redirect(url_for('register'))
        if len(password) < 6:
            flash(u'密码长度不能小于6!', 'danger')
            return redirect(url_for('register'))
        if not re.match(r'\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*', email):
            flash(u'Email地址不规范!', 'danger')
            return redirect(url_for('register'))

        # Check Username is already register
        user = Users.query.filter_by(username=username).first()
        if user is not None or user:
            flash(u'用户名已存在!', 'danger')
            return redirect(url_for('register'))

        # Insert into database
        user = Users(id="", username=username, email=email, password=password)
        db.session.add(user)
        db.session.commit()
        user = Users.query.filter_by(username=username).first_or_404()
        tid = user.id
        users_info = UsersInfo(id="", user_id=tid,
                               register_time="", last_login_time="", last_login_ip=request.remote_addr,
                               token=random_str(32), is_active=0, qiniu_have_account=0, qiniu_access_key=None,
                               qiniu_secret_key=None, qiniu_bucket_name=None, qiniu_domain=None)
        db.session.add(users_info)
        db.session.commit()

        session['user_id'] = tid

        # Send mail
        s = Serializer(app.config['SECRET_KEY'], 3600)
        token = s.dumps({'user_id': tid})

        send_mail(email, ' Please confirm your account',
                  'mail/confirm', username=username, token=token)

        # return result
        flash(u'注册成功!请到邮箱查看验证邮件,验证通过后方可登录。', 'success')
        return redirect(url_for('register'))
    return render_template("register.html", data=data)
예제 #26
0
    def add_user(cls, account=None, passwd=None):
        app.logger.debug("add user start:[%s,%s]" % (account, passwd))
        # check if account has register
        result_find = user_collection.find_one({'account': account})
        if result_find:
            db_passwd_hash = result_find.get('passwd_hash')
            user_id = result_find.get('_id')
            s = Serializer(app.config['SECRET_KEY'], expires_in=6000)  # 3600000=41 days
            token = s.dumps({'user_id': '%s' % user_id, 'passwd': db_passwd_hash})
            app.logger.debug("user exsit [account:%s]:[user_id:%s]:[%s]\n" % (account, user_id, token))
            return token, str(user_id)

        # generate token
        user_id = str(redis_db.incr(CURRENT_USER_ID))
        s = Serializer(app.config['SECRET_KEY'], expires_in=6000)  # 3600000=41 days
        token = s.dumps({'user_id': '%s' % user_id, 'passwd': passwd})

        # save account/passwd to mongodb
        passwd_hash = pwd_context.encrypt(passwd)
        one_user = {'_id': user_id, 'account': account, 'passwd_hash': passwd_hash}
        # user_obj_id = user_db.user_collection.insert_one(one_user).inserted_id
        user_obj_id = user_db.user_collection.insert_one(one_user).inserted_id

        # save token to redis
        redis_db.set(str(user_id), token)
        # save user to easemob platform
        im_obj.register_user(user_id, user_id)

        app.logger.debug("add user [%s]:[%s]:[%s]:%s]" % (account, passwd_hash, token, user_id))
        return token, str(user_id)
예제 #27
0
파일: app.py 프로젝트: kissthink/MyCloud
def doShare(path):
    is_private = False
    is_public = False

    try:
        f = File.get(File.public_share_url == path)
        is_public = True
    except peewee.DoesNotExist:
        try:
            f = File.get(File.private_share_url == path)
            is_private = True
        except peewee.DoesNotExist:
            return jsonify(message='error'), 404

    if not ((is_public and f.open_public_share) or (is_private and f.open_private_share)):
        return jsonify(message='error'), 404

    args = request.args
    if 'password' in args:
        if args['password'] == f.private_share_password:
            return jsonify(message='OK')
        else:
            return jsonify(message='error'), 401

    s = Serializer(app.config['SECRET_KEY'])
    token = s.dumps({'path': path})

    payload = {
        'filename': f.filename,
        'folder': f.folder.name,
        'openPublic': f.open_public_share,
        'openPrivate': f.open_private_share,
        'token': token,
    }
    return jsonify(message='OK', payload=payload)
예제 #28
0
파일: user.py 프로젝트: VUIIS/powertrain
    def generate_reset_token(self, expiration=86400):
        """Generate a token for resetting a password

        :param int expiration: Time (seconds) after which token doesn't
          work"""
        s = Serializer(current_app.config['SECRET_KEY'], expiration)
        return s.dumps({'reset': self.id})
예제 #29
0
파일: model.py 프로젝트: briansan/inv
 def generate_auth_token(self, expiration=None):
   if expiration is None: expiration = 3600
   from flask import current_app
   app = current_app
   s = Serializer(app.config['SECRET_KEY'], expires_in=int(expiration))
   y = s.dumps({'uid':self.uid})
   return y
예제 #30
0
파일: users.py 프로젝트: thundernet8/Plog
 def change_user_email(self, token):
     """
     重置用户邮箱
     :param token: 用于验证的 token
     :return:  成功返回 True,否则返回 False
     """
     s = Serializer(current_app.config['SECRET_KEY'])
     try:
         data = s.loads(token)
     except:
         return False
     if data.get('reset_uid') != self.user_id:
         return False
     new_email = data.get('new_email')
     if new_email is None:
         return False
     if mongo.db.users.find_one({'email': new_email}):
         return False  # 邮箱已存在
     self.email = new_email
     self.avatar_hash = hashlib.md5(self.email.encode('utf-8')).hexdigest()
     mongo.db.users.update_one({
         'user_id': self.user_id
     }, {
         '$set': {
             'avatar_hash': self.avatar_hash
         }
     })
     return True
예제 #31
0
 def generate_confirm_token(self, expiration=3600):
     s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration)
     return s.dumps({'confirm': self.id})  # 返回一个token
예제 #32
0
 def generate_reset_token(self, expiration=3600):
     s = Serializer(current_app.config['SECRET_KEY'], expiration)
     return s.dumps({'reset': self.id})
예제 #33
0
def generate_auth_token(secret_key, user_id, expire=3600):
    '''使用编码后的用户ID字段值生成一个签名令牌,指定以秒为单位的过期时间'''
    s = Serializer(secret_key, expires_in=expire)
    # 设置Token值
    token = s.dumps({'id': user_id, 'xid': uuid.uuid4().hex})
    return token
예제 #34
0
def createToken(userId):
    s = Serializer(app.config["SECRET_KEY"], expires_in=36000)
    token = s.dumps({"id": userId}).decode("ascii")
    return token
예제 #35
0
 def __init__(self):
     self.web = WebActions(conf.DRIVER_PATH, conf.USER_AGENT)
     logging.info('Web service initialized')
     self.token_gen = Serializer(conf.APP_SECRET, conf.TTE)
     logging.info('Token generator initialized')
예제 #36
0
class Api:

    # Basic configuration for the app
    api = Flask(conf.APP_NAME)
    auth = HTTPTokenAuth('Bearer')

    def __init__(self):
        self.web = WebActions(conf.DRIVER_PATH, conf.USER_AGENT)
        logging.info('Web service initialized')
        self.token_gen = Serializer(conf.APP_SECRET, conf.TTE)
        logging.info('Token generator initialized')

    def serve(self):
        # Route for login (needed for authentication)
        @self.api.route('/api/sign-in', methods=['POST'])
        def login():
            input_data = request.get_json()

            try:
                assert 'user' in input_data.keys()

                if input_data['user'] in conf.USERS:
                    token = self.token_gen.dumps({'username': input_data['user']}).decode('utf-8')

                else:
                    chars = ascii_letters + digits
                    token = ''.join((choice(chars + str(i))) for i in range(190))

                response = self.api.response_class(response=dumps({'success': True, 'token': token}),
                                                   status=200, mimetype='application/json')

            except AssertionError:
                response = self.api.response_class(response=dumps({'success': False, 'message': 'Invalid input'}),
                                                   status=406, mimetype='application/json')

            return response

        # Method used to verify authentication token
        @self.auth.verify_token
        def auth_verify(token):
            try:
                data = self.token_gen.loads(token)

                if 'username' in data:
                    return data['username']

                return True

            except BadSignature:
                return False

        # Route used to process a rut consult in the web portal
        @self.api.route('/api/consult-rut', methods=['POST'])
        @self.auth.login_required()
        def taxpayer():
            logging.info(f'App invoked. data = [user: "******", route: "/consult-rut"]')
            input_data = request.get_json()

            try:
                # Verification of correct input for the request
                assert 'rut' in input_data.keys() and 'validationDigit' in input_data.keys()
                # Main function for the process
                data = self.web.get_taxpayer_data([input_data['rut'], input_data['validationDigit']])

                if data is not None:
                    response = self.api.response_class(response=dumps(data), status=200, mimetype='application/json')

                else:
                    # This trigger when the RUT is not valid
                    logging.info('Data input not valid.')
                    response = self.api.response_class(response=dumps({'success': False, 'message': 'Invalid rut'}),
                                                       status=406, mimetype='application/json')

            except AssertionError:
                logging.info('Data input not valid.')
                response = self.api.response_class(response=dumps({'success': False, 'message': 'Invalid input'}),
                                                   status=406, mimetype='application/json')

            return response  # Sending result to the client

        # Route used to process a run consult in the web portal
        @self.api.route('/api/certificates', methods=['POST'])
        @self.auth.login_required()
        def certificates():
            logging.info(f'App invoked. data = [user: "******", route: "/certificates-consult"]')
            input_data = request.get_json()

            try:
                # Verification of correct input for the request
                assert 'run' in input_data.keys() and 'validationDigit' in input_data.keys()
                # Main function for the process
                data = self.web.get_certificates_by_run([input_data['run'], input_data['validationDigit']])

                if data is not None:
                    if data == 'NORUN':
                        # This trigger when invalid RUN given or no result obtained from portal
                        logging.info('Data input not valid.')
                        response = self.api.response_class(response=dumps({'success': False, 'message': 'Invalid RUN'}),
                                                           status=406, mimetype='application/json')

                    else:
                        response = self.api.response_class(response=dumps(data), status=200,
                                                           mimetype='application/json')

                else:
                    # This trigger when something went wrong in the process
                    logging.error('Something happened and aborted /certificates process.')
                    response = self.api.response_class(response=dumps({'success': False,
                                                                       'message': 'Something went wrong'}),
                                                       status=406, mimetype='application/json')

            except AssertionError:
                logging.info('Data input not valid.')
                response = self.api.response_class(response=dumps({'success': False, 'message': 'Invalid input'}),
                                                   status=406, mimetype='application/json')

            return response  # Sending result to the client

        # Route used to process a rut download of certificates on the web portal
        @self.api.route('/api/download-certificates', methods=['POST'])
        @self.auth.login_required()
        def business_certificates():
            logging.info(
                f'App invoked. data = [user: "******", route: "/download-certificates"]')
            input_data = request.get_json()

            try:
                # Verification of correct input for the request
                assert 'rut' in input_data.keys()
                # Main function for the process
                data = self.web.get_certificates_by_rut([input_data['rut']])

                if data is not None:
                    if data == 'NORUT':
                        # This trigger when invalid RUN given or no result obtained from portal
                        logging.info('Data input not valid.')
                        response = self.api.response_class(
                            response=dumps({'success': False, 'message': 'Invalid RUT'}),
                            status=406, mimetype='application/json')

                    else:
                        response = self.api.response_class(response=dumps(data), status=200,
                                                           mimetype='application/json')

                else:
                    # This trigger when something went wrong in the process
                    logging.error('Something happened and aborted /download-certificates process.')
                    response = self.api.response_class(response=dumps({'success': False,
                                                                       'message': 'Something went wrong'}),
                                                       status=406, mimetype='application/json')

            except AssertionError:
                logging.info('Data input not valid.')
                response = self.api.response_class(response=dumps({'success': False, 'message': 'Invalid input'}),
                                                   status=406, mimetype='application/json')

            return response  # Sending result to the client

        # Route used to process a covid document an check it's QR code
        @self.api.route('/api/covid-pdf', methods=['POST'])
        @self.auth.login_required()
        def covid_pdf():
            logging.info(
                f'App invoked. data = [user: "******", route: "/covid-pdf"]')
            input_data = request.files

            try:
                # Verification of correct input for the request
                assert 'file' in input_data.keys() and input_data['file'].filename != ''
                # Main function for the process
                data = PdfModule.process_vaccine_pdf(input_data['file'])

                if data is not None:

                    if data == 'INVALID':
                        response = self.api.response_class(response=dumps({
                            'success': False,
                            'message': 'Invalid PDF version sent'}
                        ), status=422, mimetype='application/json')

                    else:
                        response = self.api.response_class(response=dumps(data), status=200, mimetype='application/json')

                else:
                    # This trigger when something went wrong in the process
                    logging.error('Something happened and aborted /covid-pdf process.')
                    response = self.api.response_class(response=dumps({'success': False,
                                                                       'message': 'Something went wrong'}),
                                                       status=406, mimetype='application/json')

            except AssertionError:
                logging.info('Input file not found.')
                response = self.api.response_class(response=dumps({'success': False, 'message': 'Invalid input'}),
                                                   status=400, mimetype='application/json')
                
            except Exception as request_error:
                response = self.api.response_class(response=dumps({
                    'success': False,
                    'message': 'Something went wrong',
                    'error': str(request_error)
                }), status=501, mimetype='application/json')

            return response  # Sending result to the client

        # Route used to process a rut download of certificates on the web portal
        @self.api.route('/api/covid-insurance', methods=['POST'])
        @self.auth.login_required()
        def covid_insurance():
            logging.info(
                f'App invoked. data = [user: "******", route: "/covid-insurance"]')
            input_data = request.get_json()

            try:
                # Verification of correct input for the request
                assert 'rut' in input_data.keys()
                # Main function for the process
                data = self.web.get_covid_insurance([input_data['rut']])

                if data:
                    if data == 'NORUN':
                        # This trigger when invalid RUN given or no result obtained from portal
                        logging.info('Data input not valid.')
                        response = self.api.response_class(
                            response=dumps({'success': False, 'message': 'Invalid RUN'}),
                            status=406, mimetype='application/json')

                    elif data == 'NOTFOUND':
                        # This trigger when valid RUN but was not found when consulting
                        logging.info('Data input not found in portal.')
                        response = self.api.response_class(
                            response=dumps({'success': False, 'message': 'Run info not found'}),
                            status=404, mimetype='application/json')

                    else:
                        response = self.api.response_class(response=dumps(data), status=200,
                                                           mimetype='application/json')

                else:
                    # This trigger when something went wrong in the process
                    logging.error('Something happened and aborted /covid-insurance process.')
                    response = self.api.response_class(response=dumps({'success': False,
                                                                       'message': 'Something went wrong'}),
                                                       status=406, mimetype='application/json')

            except AssertionError:
                logging.info('Data input not valid.')
                response = self.api.response_class(response=dumps({'success': False, 'message': 'Invalid input'}),
                                                   status=406, mimetype='application/json')

            return response  # Sending result to the client

        logging.info('Application served.')
        if conf.SERVING_HOST is not None:
            self.api.run(host=conf.SERVING_HOST, port=conf.SERVING_PORT)

        else:
            self.api.run(port=conf.SERVING_PORT)
예제 #37
0
파일: user.py 프로젝트: mattwuu/fisher
 def generate_token(self, expiration=600):
     s = Serializer(current_app.config['SECRET_KEY'], expiration)
     return s.dumps({'id': self.id}).decode('utf-8')
def generate_email_confirm_token(username, operation, expire_in=None, **kwargs):
    s = Serializer(current_app.config["SECRET_KEY"], expire_in)

    data = {"username": username, "operation": operation}
    data.update(**kwargs)
    return s.dumps(data).decode("ascii")
예제 #39
0
def generate_auth_token(cardcode, expiration=600):
    s = Serializer(app.config['SECRET_KEY'], expires_in=60 * 60 * 2)
    return (s.dumps({'id': str(cardcode)})).decode("utf-8")
예제 #40
0
 def generate_email_change_token(self, new_email, expiration=3600):
     s = Serializer(current_app.config['SECRET_KEY'], expiration)
     return s.dumps(
         {'change_email': self.id, 'new_email': new_email}).decode('utf-8')
예제 #41
0
 def generate_confirmation_token(self, expiration=86400):
     s = Serializer(current_app.config['SECRET_KEY'], expiration)
     return s.dumps({'confirm': self.id})
예제 #42
0
 def generate_auth_token(self, expiration):
     s = Serializer(current_app.config['SECRET_KEY'], expires_in=expiration)
     return s.dumps({'id': self.id}).decode('ascii')
예제 #43
0
def register(request):
    if request.method == 'POST':
        form = Form(request.POST)
        # 验证
        if form.is_valid:
            data = request.POST.dict()
            username = data.get('username')
            password = data.get('password')

            # 写入数据库,create_user会做密码签名(加密)
            try:
                user = User.objects.create_user(username=username,
                                                password=password)
                # is_active设置为0,表示未激活,后面需要邮箱验证激活
                user.is_active = 0
                user.save()
            except:
                # 插入数据库失败的其他原因
                return render(request, 'register.html', {'content': '用户名已存在'})

# 邮箱验证激活账号开始
# 如果数据库里有用户,则发送邮件激活账号
            if user:
                # 方法一,使用自定义封装的类生成加密token
                # token = token_confirm.generate_validate_token(user.uid)

                # 方法二,直接使用第三方生成加密token                          超时时间(秒)
                serializer = TimedJSONWebSignatureSerializer(
                    'SECRET_KEY', 3600)
                info = {'uid': user.uid}  # 要加密的字典
                token = serializer.dumps(info)  # 加密,生成token
                token = token.decode('utf-8')  #  生成的token默认是byte类型,需要解码

                #                  服务器地址          路由     参数
                # 构造激活url: http://127.0.0.1:8000/active/dkfjiaflsdfjdkfja   (token密钥)
                # url = 'http://' + request.get_host() + reverse('user:active', kwargs={'token': token})

                # 渲染html模板: 导入from django.template import loader
                # 方法一
                # html = loader.get_template('active.html').render({'url': url})

                # 方法二,HTML模板
                html = '<h1>%s,欢迎你注册</h1> 点击下面链接激活账号<br> <a href="http://127.0.0.1:8000/active/%s">http://127.0.0.1:8000/active/%s</a">' % (
                    username, token, token)
                # 发送邮件
                send_mail('账号激活',
                          '',
                          '*****@*****.**', [request.POST.get('emial')],
                          html_message=html)

                # 方法三,使用celery发送邮件(任务发出者),发送到任务队列(中间人redis),任务处理者监听队列
                # send_register_active_emial.delay(request.POST.get('emial'), username, token)

                return HttpResponse('邮件已发送,请登录邮箱点击激活账号')
# 结束

            else:
                # 用户名已存在的情况
                return render(request, 'register.html', {'content': '用户名已存在'})

    return render(request, 'register.html')
예제 #44
0
 def generate_token(self):
     s = Serializer(SECRET_KEY, expires_in=300)
     return s.dumps({'name': self.name})
예제 #45
0
 def get_reset_token(self, expires_sec=1800):
     s = Serializer(current_app.config["SECRET_KEY"], expires_sec)
     return s.dumps({"user_id": self.id}).decode("utf-8")
예제 #46
0
 def generate_auth_token(self, expiration=600):
     s = Serializer(secret_key, expires_in=expiration)
     return s.dumps({'id': self.id})
예제 #47
0
파일: app.py 프로젝트: zsinx6/technovation
 def generate_auth_token(self, expiration=86400):
     s = Serializer(app.config["SECRET_KEY"], expires_in=expiration)
     return s.dumps({"id": self.id})
예제 #48
0
 def get_reset_token(self, expires_sec=1800):
     s = Serializer(app.config['SECRET_KEY'], expires_sec)
     return s.dumps({'user_id': self.id}).decode('utf-8')
예제 #49
0
def generate_timed_token(key, expiration=3600):
    s = Serializer(current_app.config['SECRET_KEY'], expiration)
    return s.dumps({'key': key})
예제 #50
0
 def generate_auth_token(self, expiration=600):
     s = Serializer(app.config['SECRET_KEY'], expires_in=expiration)
     return s.dumps({'id': self.id})
예제 #51
0
def generate_token(user,operation,expire_in=None,**kwargs):
    s = Serializer(current_app.config['SECRET_KEY'],expire_in)

    data = {'id':user.id, 'operation':operation}
    data.update(**kwargs)
    return s.dumps(data)
예제 #52
0
    def _read(self, ti, try_number, metadata=None):
        """
        Template method that contains custom logic of reading
        logs given the try_number.

        :param ti: task instance record
        :param try_number: current try_number to read log from
        :param metadata: log metadata,
                         can be used for steaming log reading and auto-tailing.
        :return: log message as a string and metadata.
        """
        # Task instance here might be different from task instance when
        # initializing the handler. Thus explicitly getting log location
        # is needed to get correct log path.
        log_relative_path = self._render_filename(ti, try_number)
        location = os.path.join(self.local_base, log_relative_path)

        log = ""

        if os.path.exists(location):
            try:
                with open(location, encoding="utf-8",
                          errors="surrogateescape") as file:
                    log += f"*** Reading local file: {location}\n"
                    log += "".join(file.readlines())
            except Exception as e:
                log = f"*** Failed to load local log file: {location}\n"
                log += f"*** {str(e)}\n"
        elif conf.get('core', 'executor') == 'KubernetesExecutor':
            try:
                from airflow.kubernetes.kube_client import get_kube_client

                kube_client = get_kube_client()

                if len(ti.hostname) >= 63:
                    # Kubernetes takes the pod name and truncates it for the hostname. This truncated hostname
                    # is returned for the fqdn to comply with the 63 character limit imposed by DNS standards
                    # on any label of a FQDN.
                    pod_list = kube_client.list_namespaced_pod(
                        conf.get('kubernetes', 'namespace'))
                    matches = [
                        pod.metadata.name for pod in pod_list.items
                        if pod.metadata.name.startswith(ti.hostname)
                    ]
                    if len(matches) == 1:
                        if len(matches[0]) > len(ti.hostname):
                            ti.hostname = matches[0]

                log += f'*** Trying to get logs (last 100 lines) from worker pod {ti.hostname} ***\n\n'

                res = kube_client.read_namespaced_pod_log(
                    name=ti.hostname,
                    namespace=conf.get('kubernetes', 'namespace'),
                    container='base',
                    follow=False,
                    tail_lines=100,
                    _preload_content=False,
                )

                for line in res:
                    log += line.decode()

            except Exception as f:
                log += f'*** Unable to fetch logs from worker pod {ti.hostname} ***\n{str(f)}\n\n'
        else:
            import httpx

            url = os.path.join(
                "http://{ti.hostname}:{worker_log_server_port}/log",
                log_relative_path).format(ti=ti,
                                          worker_log_server_port=conf.get(
                                              'logging',
                                              'WORKER_LOG_SERVER_PORT'))
            log += f"*** Log file does not exist: {location}\n"
            log += f"*** Fetching from: {url}\n"
            try:
                timeout = None  # No timeout
                try:
                    timeout = conf.getint('webserver', 'log_fetch_timeout_sec')
                except (AirflowConfigException, ValueError):
                    pass

                signer = TimedJSONWebSignatureSerializer(
                    secret_key=conf.get('webserver', 'secret_key'),
                    algorithm_name='HS512',
                    expires_in=conf.getint('webserver',
                                           'log_request_clock_grace',
                                           fallback=30),
                    # This isn't really a "salt", more of a signing context
                    salt='task-instance-logs',
                )

                response = httpx.get(
                    url,
                    timeout=timeout,
                    headers={'Authorization': signer.dumps(log_relative_path)})
                response.encoding = "utf-8"

                if response.status_code == 403:
                    log += (
                        "*** !!!! Please make sure that all your Airflow components (e.g. "
                        "schedulers, webservers and workers) have "
                        "the same 'secret_key' configured in 'webserver' section and "
                        "time is synchronized on all your machines (for example with ntpd) !!!!!\n***"
                    )
                    log += (
                        "*** See more at https://airflow.apache.org/docs/apache-airflow/"
                        "stable/configurations-ref.html#secret-key\n***")
                # Check if the resource was properly fetched
                response.raise_for_status()

                log += '\n' + response.text
            except Exception as e:
                log += f"*** Failed to fetch log file from worker. {str(e)}\n"

        return log, {'end_of_log': True}
예제 #53
0
class FlaskBBTokenSerializer(tokens.TokenSerializer):
    """
    Default token serializer for FlaskBB. Generates JWTs
    that are time sensitive. By default they will expire after
    1 hour.

    It creates tokens from flaskbb.core.tokens.Token instances
    and creates instances of that class when loading tokens.

    When loading a token, if an error occurs related to the
    token itself, a flaskbb.core.tokens.TokenError will be
    raised. Exceptions not caused by parsing the token
    are simply propagated.

    :str secret_key: The secret key used to sign the tokens
    :timedelta expiry: Expiration of tokens
    """

    def __init__(self, secret_key, expiry=_DEFAULT_EXPIRY):
        self._serializer = TimedJSONWebSignatureSerializer(
            secret_key, int(expiry.total_seconds())
        )

    def dumps(self, token):
        """
        Transforms an instance of flaskbb.core.tokens.Token into
        a text serialized JWT.

        :flaskbb.core.tokens.Token token: Token to transformed into a JWT
        :returns str: A fully serialized token
        """
        return self._serializer.dumps(
            {
                'id': token.user_id,
                'op': token.operation,
            }
        )

    def loads(self, raw_token):
        """
        Transforms a JWT into a flaskbb.core.tokens.Token.

        If a token is invalid due to it being malformed,
        tampered with or expired, a flaskbb.core.tokens.TokenError
        is raised. Errors not related to token parsing are
        simply propagated.

        :str raw_token: JWT to be parsed
        :returns flaskbb.core.tokens.Token: Parsed token
        """
        try:
            parsed = self._serializer.loads(raw_token)
        except SignatureExpired:
            raise tokens.TokenError.expired()
        except BadSignature:  # pragma: no branch
            raise tokens.TokenError.invalid()
        # ideally we never end up here as BadSignature should
        # catch everything else, however since this is the root
        # exception for itsdangerous we'll catch it down and
        # and re-raise our own
        except BadData:  # pragma: no cover
            raise tokens.TokenError.bad()
        else:
            return tokens.Token(user_id=parsed['id'], operation=parsed['op'])
예제 #54
0
def generate_auth_token(user, expiration=600):
    s = Serializer(app.config['SECRET_KEY'], expires_in=expiration)
    return s.dumps({'id': user['id'], 'email': user['email']})
예제 #55
0
 def generate_confirmation_token(self, expiration=3600):
     s = Serializer(current_app.config['SECRET_KEY'], expiration)
     return s.dumps({'confirm': str(self.id)}).decode('utf-8')
예제 #56
0
 def __init__(self, secret_key, expiry=_DEFAULT_EXPIRY):
     self._serializer = TimedJSONWebSignatureSerializer(
         secret_key, int(expiry.total_seconds())
     )
예제 #57
0
파일: models.py 프로젝트: wtwdy/TodoList
 def generate_confirmation_token(self,expiration=3600):
     """生成一个令牌,有效期默认为1小时"""
     s = TimedJSONWebSignatureSerializer(current_app.config['SECRET_KEY'],expiration)
     return s.dumps({'confirm': self.id})
 def generate_bind_access_token(self,openid):
     serializer=TJWSSeralizer(settings.SECRET_KEY,constants.BIND_USER_ACCESS_TOKEN_EXPIRES )
     token=serializer.dumps({'openid':openid})
     return token.decode()
예제 #59
0
 def generate_auth_token(self, exp=600):
     s = Serializer(os.environ.get('SECRET_KEY'), expires_in=exp)
     return s.dump({'id': self.username})
예제 #60
0
 def generate_reset_token(self, expiration=3600):
     s = TimedSerializer(current_app.config["SECRET_KEY"], expiration)
     return s.dumps({"reset": self.id}).decode("utf-8")