当前位置: 首页>>代码示例>>Python>>正文


Python itsdangerous.TimedSerializer类代码示例

本文整理汇总了Python中itsdangerous.TimedSerializer的典型用法代码示例。如果您正苦于以下问题:Python TimedSerializer类的具体用法?Python TimedSerializer怎么用?Python TimedSerializer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了TimedSerializer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: reset_password

def reset_password(data=None):
    if data is not None and request.method == "GET":
        return render_template('reset_password.html', mode='set')
    if data is not None and request.method == "POST":
        try:
            s = TimedSerializer(app.config['SECRET_KEY'])
            name = s.loads(urllib.unquote_plus(data.decode('base64')), max_age=1800)
        except BadTimeSignature:
            return render_template('reset_password.html', errors=['Your link has expired'])
        except:
            return render_template('reset_password.html', errors=['Your link appears broken, please try again.'])
        team = Teams.query.filter_by(name=name).first_or_404()
        team.password = bcrypt_sha256.encrypt(request.form['password'].strip())
        db.session.commit()
        db.session.close()
        return redirect(url_for('auth.login'))

    if request.method == 'POST':
        email = request.form['email'].strip()
        team = Teams.query.filter_by(email=email).first()
        if not team:
            return render_template('reset_password.html', errors=['If that account exists you will receive an email, please check your inbox'])
        s = TimedSerializer(app.config['SECRET_KEY'])
        token = s.dumps(team.name)
        text = """
Did you initiate a password reset?

{0}/{1}

""".format(url_for('auth.reset_password', _external=True), urllib.quote_plus(token.encode('base64')))

        utils.sendmail(email, text)

        return render_template('reset_password.html', errors=['If that account exists you will receive an email, please check your inbox'])
    return render_template('reset_password.html')
开发者ID:semprix,项目名称:CTFIgniter,代码行数:35,代码来源:auth.py

示例2: reset_password

def reset_password(data=None):
    if data is not None and request.method == "GET":
        return render_template('reset_password.html', mode='set')
    if data is not None and request.method == "POST":
        try:
            s = TimedSerializer(app.config['SECRET_KEY'])
            name = s.loads(data.decode('base64'), max_age=1800)
        except BadTimeSignature:
            return render_template('reset_password.html', errors=['Your link has expired'])
        team = Teams.query.filter_by(name=name).first()
        team.password = bcrypt_sha256.encrypt(request.form['password'].strip())
        db.session.commit()
        db.session.close()
        return redirect(url_for('auth.login'))

    if request.method == 'POST':
        email = request.form['email'].strip()
        team = Teams.query.filter_by(email=email).first()
        if not team:
            return render_template('reset_password.html', errors=['Check your email'])
        s = TimedSerializer(app.config['SECRET_KEY'])
        token = s.dumps(team.name)
        text = """
Did you initiate a password reset? 

{0}/reset_password/{1}

""".format(app.config['HOST'], token.encode('base64'))

        sendmail(email, text)

        return render_template('reset_password.html', errors=['Check your email'])
    return render_template('reset_password.html')
开发者ID:HackUCF,项目名称:CTFd,代码行数:33,代码来源:auth.py

示例3: BaseConsumer

class BaseConsumer(object):
    def __init__(self, base_url, public_key, private_key):
        self.base_url = base_url
        self.public_key = public_key
        self.signer = TimedSerializer(private_key)
    
    def consume(self, path, data, max_age=None):
        if not path.startswith('/'):
            raise ValueError("Paths must start with a slash")
        signed_data = self.signer.dumps(data)
        headers = {
            PUBLIC_KEY_HEADER: self.public_key,
            'Content-Type': 'application/json',
        }
        url = self.build_url(path)
        body = self.send_request(url, data=signed_data, headers=headers)
        return self.handle_response(body, max_age)
    
    def handle_response(self, body, max_age):
        return self.signer.loads(body, max_age=max_age)
    
    def send_request(self, url, data, headers):
        raise NotImplementedError("Implement send_request on BaseConsumer subclasses")
    
    def raise_for_status(self, status_code, message):
        if status_code == 400:
            raise BadRequest(message)
        elif status_code >= 300:
            raise WebserviceError(message)
    
    def build_url(self, path):
        path = path.lstrip('/')
        return urlparse.urljoin(self.base_url, path)
开发者ID:pombredanne,项目名称:webservices,代码行数:33,代码来源:models.py

示例4: get_payouts

def get_payouts():
    """ Used by remote procedure call to retrieve a list of transactions to
    be processed. Transaction information is signed for safety. """
    s = TimedSerializer(current_app.config['rpc_signature'])
    args = s.loads(request.data)
    current_app.logger.info("get_payouts being called, args of {}!".format(args))
    lock = False
    merged = None
    if isinstance(args, dict) and args['lock']:
        lock = True
    if isinstance(args, dict) and args['merged']:
        merged = args['merged']

    with Benchmark("Fetching payout information"):
        pids = [(p.user, p.amount, p.id) for p in Payout.query.filter_by(transaction_id=None, locked=False, merged_type=merged).
                join(Payout.block, aliased=True).filter_by(mature=True)]
        bids = [(p.user, p.amount, p.id) for p in BonusPayout.query.filter_by(transaction_id=None, locked=False, merged_type=merged).
                join(BonusPayout.block, aliased=True).filter_by(mature=True)]

        if lock:
            if bids:
                current_app.logger.info("Locking {} bonus ids at retriever request."
                                        .format(len(bids)))
                (BonusPayout.query.filter(BonusPayout.id.in_(p[2] for p in bids))
                 .update({BonusPayout.locked: True}, synchronize_session=False))
            if pids:
                current_app.logger.info("Locking {} payout ids at retriever request."
                                        .format(len(pids)))
                (Payout.query.filter(Payout.id.in_(p[2] for p in pids))
                 .update({Payout.locked: True}, synchronize_session=False))
            db.session.commit()
    return s.dumps([pids, bids, lock])
开发者ID:AlphaBuffalo,项目名称:simplevert,代码行数:32,代码来源:rpc_views.py

示例5: reset_password

def reset_password(data=None):
    if data is not None and request.method == "GET":
        return render_template("reset_password.html", mode="set")
    if data is not None and request.method == "POST":
        try:
            s = TimedSerializer(app.config["SECRET_KEY"])
            name = s.loads(data.decode("base64"), max_age=1800)
        except BadTimeSignature:
            return render_template("reset_password.html", errors=["Your link has expired"])
        team = Teams.query.filter_by(name=name).first()
        team.password = bcrypt_sha256.encrypt(request.form["password"].strip())
        db.session.commit()
        db.session.close()
        return redirect(url_for("auth.login"))

    if request.method == "POST":
        email = request.form["email"].strip()
        team = Teams.query.filter_by(email=email).first()
        if not team:
            return render_template("reset_password.html", errors=["Check your email"])
        s = TimedSerializer(app.config["SECRET_KEY"])
        token = s.dumps(team.name)
        text = """
Did you initiate a password reset?

{0}/reset_password/{1}

""".format(
            url_for("auth.reset_password", _external=True), token.encode("base64")
        )

        sendmail(email, text)

        return render_template("reset_password.html", errors=["Check your email"])
    return render_template("reset_password.html")
开发者ID:breadchris,项目名称:CTFd,代码行数:35,代码来源:auth.py

示例6: get_payouts

def get_payouts():
    """ Used by remote procedure call to retrieve a list of transactions to
    be processed. Transaction information is signed for safety. """
    s = TimedSerializer(current_app.config['rpc_signature'])
    args = s.loads(request.data)
    current_app.logger.info("get_payouts being called, args of {}!".format(args))
    lock = False
    merged = None
    if isinstance(args, dict) and args['lock']:
        lock = True
    if isinstance(args, dict) and args['merged']:
        merged = args['merged']

    payouts = (Payout.query.filter_by(transaction_id=None, locked=False, merged_type=merged).
               join(Payout.block, aliased=True).filter_by(mature=True)).all()
    bonus_payouts = (BonusPayout.query.filter_by(transaction_id=None, locked=False, merged_type=merged).
                     join(BonusPayout.block, aliased=True).filter_by(mature=True)).all()

    pids = [(p.user, p.amount, p.id) for p in payouts]
    bids = [(p.user, p.amount, p.id) for p in bonus_payouts]

    if lock:
        current_app.logger.info("Locking pids and bids at retriever request.")
        for payout in payouts:
            payout.locked = True
        for payout in bonus_payouts:
            payout.locked = True
        db.session.commit()
    return s.dumps([pids, bids, lock])
开发者ID:yinhm,项目名称:simplevert,代码行数:29,代码来源:rpc_views.py

示例7: confirm_transactions

def confirm_transactions():
    """ Used as a response from an rpc payout system. This will either reset
    the sent status of a list of transactions upon failure on the remote side,
    or create a new CoinTransaction object and link it to the transactions to
    signify that the transaction has been processed. Both request and response
    are signed. """
    s = TimedSerializer(current_app.config['rpc_signature'])
    data = s.loads(request.data)

    # basic checking of input
    try:
        assert len(data['coin_txid']) == 64
        assert isinstance(data['pids'], list)
        assert isinstance(data['bids'], list)
        for id in data['pids']:
            assert isinstance(id, int)
        for id in data['bids']:
            assert isinstance(id, int)
    except AssertionError:
        current_app.logger.warn("Invalid data passed to confirm", exc_info=True)
        abort(400)

    coin_trans = Transaction.create(data['coin_txid'])
    db.session.flush()
    Payout.query.filter(Payout.id.in_(data['pids'])).update(
        {Payout.transaction_id: coin_trans.txid}, synchronize_session=False)
    BonusPayout.query.filter(BonusPayout.id.in_(data['bids'])).update(
        {BonusPayout.transaction_id: coin_trans.txid}, synchronize_session=False)
    db.session.commit()
    return s.dumps(True)
开发者ID:raid5,项目名称:simpledoge,代码行数:30,代码来源:views.py

示例8: verify_auth_token

 def verify_auth_token(token, max_age=3600):
     s = TimedSerializer(secret_key)
     try:
         data = s.loads(token, max_age=max_age)
     except SignatureExpired:
         return None
     except BadSignature:
         return None
     return data
开发者ID:navinesh,项目名称:leave-management-system,代码行数:9,代码来源:models.py

示例9: get_payouts

def get_payouts():
    """ Used by remote procedure call to retrieve a list of transactions to
    be processed. Transaction information is signed for safety. """
    s = TimedSerializer(current_app.config['rpc_signature'])
    s.loads(request.data)

    payouts = (Payout.query.filter_by(transaction_id=None).
               join(Payout.block, aliased=True).filter_by(mature=True))
    bonus_payouts = BonusPayout.query.filter_by(transaction_id=None)
    pids = [(p.user, p.amount, p.id) for p in payouts]
    bids = [(p.user, p.amount, p.id) for p in bonus_payouts]
    return s.dumps([pids, bids])
开发者ID:raid5,项目名称:simpledoge,代码行数:12,代码来源:views.py

示例10: confirm_transactions

def confirm_transactions():
    """ Used to confirm that a transaction is now complete on the network. """
    s = TimedSerializer(current_app.config['rpc_signature'])
    data = s.loads(request.data)

    # basic checking of input
    try:
        assert isinstance(data['tids'], list)
    except AssertionError:
        current_app.logger.warn("Invalid data passed to confirm_transactions",
                                exc_info=True)
        abort(400)

    Transaction.query.filter(Transaction.txid.in_(data['tids'])).update(
        {Transaction.confirmed: True}, synchronize_session=False)
    db.session.commit()

    return s.dumps(True)
开发者ID:yinhm,项目名称:simplevert,代码行数:18,代码来源:rpc_views.py

示例11: __init__

    def __init__(self, config_path='/config.yml', root_suffix='/../',
                 max_age=5):
        self.root = os.path.abspath(os.path.dirname(__file__) + root_suffix)
        self.config = current_app.config
        del current_app.logger.handlers[0]
        current_app.logger.addHandler(ch)

        self.serializer = TimedSerializer(self.config['rpc_signature'])
        self.max_age = max_age
开发者ID:raid5,项目名称:simpledoge,代码行数:9,代码来源:rpc.py

示例12: __init__

    def __init__(self, config, CoinRPC, logger=None):

        if not config:
            raise SCRPCException('Invalid configuration file')
        self._set_config(**config)

        # Setup CoinRPC
        self.coin_rpc = CoinRPC

        # Setup the sqlite database mapper
        self.engine = sa.create_engine('sqlite:///{}'.format(self.config['database_path']),
                                       echo=self.config['log_level'] == "DEBUG")

        # Pulled from SQLA docs to implement strict exclusive access to the
        # payout state database.
        # See http://docs.sqlalchemy.org/en/rel_0_9/dialects/sqlite.html#pysqlite-serializable
        @sa.event.listens_for(self.engine, "connect")
        def do_connect(dbapi_connection, connection_record):
            # disable pysqlite's emitting of the BEGIN statement entirely.
            # also stops it from emitting COMMIT before any DDL.
            dbapi_connection.isolation_level = None

        @sa.event.listens_for(self.engine, "begin")
        def do_begin(conn):
            # emit our own BEGIN
            conn.execute("BEGIN EXCLUSIVE")

        self.db = sessionmaker(bind=self.engine)
        self.db.session = self.db()
        # Hack if flask is in the env
        self.db.session._model_changes = {}
        # Create the table if it doesn't exist
        Payout.__table__.create(self.engine, checkfirst=True)

        # Setup logger for the class
        if logger:
            self.logger = logger
        else:
            logging.Formatter.converter = datetime.time.gmtime
            self.logger = logging.getLogger(self.config['logger_name'])
            self.logger.setLevel(getattr(logging, self.config['log_level']))
            log_format = logging.Formatter('%(asctime)s %(levelname)s %(message)s')

            # stdout handler
            handler = logging.StreamHandler(sys.stdout)
            handler.setFormatter(log_format)
            handler.setLevel(getattr(logging, self.config['log_level']))
            self.logger.addHandler(handler)

            # don't attach a file handler if path evals false
            if self.config['log_path']:
                handler = logging.FileHandler(self.config['log_path'])
                handler.setFormatter(log_format)
                handler.setLevel(getattr(logging, self.config['log_level']))
                self.logger.addHandler(handler)

        self.serializer = TimedSerializer(self.config['rpc_signature'])
开发者ID:ahmedbodi,项目名称:simplecoin_rpc_client,代码行数:57,代码来源:sc_rpc.py

示例13: get_response

 def get_response(self, method, signed_data, get_header):
     if method != 'POST':
         return (405, ['POST'])
     public_key = get_header(PUBLIC_KEY_HEADER, None)
     if not public_key:
         return (400, "No public key")
     private_key = self.get_private_key(public_key)
     if not private_key:
         return (400, "Invalid public key")
     signer = TimedSerializer(private_key)
     try:
         data = signer.loads(signed_data, max_age=self.max_age)
     except SignatureExpired:
         return (400, "Signature expired")
     except BadSignature:
         return (400, "Bad Signature")
     try:
         raw_response_data = self.provide(data)
     except:
         self.report_exception()
         return (400, "Failed to process the request")
     response_data = signer.dumps(raw_response_data)
     return (200, response_data)
开发者ID:deanrock,项目名称:webservices,代码行数:23,代码来源:models.py

示例14: __init__

 def __init__(self, base_url, public_key, private_key):
     self.base_url = base_url
     self.public_key = public_key
     self.signer = TimedSerializer(private_key)
开发者ID:deanrock,项目名称:webservices,代码行数:4,代码来源:models.py

示例15: generate_auth_token

 def generate_auth_token(self):
     s = TimedSerializer(secret_key)
     return s.dumps(self.id)
开发者ID:navinesh,项目名称:leave-management-system,代码行数:3,代码来源:models.py


注:本文中的itsdangerous.TimedSerializer类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。