Python itsdangerous.URLSafeSerializer() Examples

The following are 25 code examples of itsdangerous.URLSafeSerializer(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module itsdangerous , or try the search function .
Example #1
Source File: asm.py    From assembly with MIT License 7 votes vote down vote up
def sign_data(data, expires_in=None, **kw):
    """
    To sign url safe data.
    If expires_in is provided it will Time the signature
    :param data: (mixed) the data to sign
    :param expires_in: (int) in minutes. Time to expire
    :param kw: kwargs for itsdangerous.URLSafeSerializer
    :return:
    """
    if expires_in:
        expires_in *= 60
        s = URLSafeTimedSerializer2(secret_key=__CRYPT.get("secret_key"),
                                    expires_in=expires_in,
                                    salt=__CRYPT.get("salt"),
                                    **kw)
    else:
        s = itsdangerous.URLSafeSerializer(secret_key=__CRYPT.get("secret_key"),
                                           salt=__CRYPT.get("salt"),
                                           **kw)
    return s.dumps(data) 
Example #2
Source File: email_links.py    From amivapi with GNU Affero General Public License v3.0 6 votes vote down vote up
def on_delete_signup(token):
    """Endpoint to delete signups via email"""
    try:
        s = URLSafeSerializer(get_token_secret())
        signup_id = ObjectId(s.loads(token))
    except BadSignature:
        return "Unknown token"

    deleteitem_internal('eventsignups', concurrency_check=False,
                        **{current_app.config['ID_FIELD']: signup_id})

    redirect_url = current_app.config.get('SIGNUP_DELETED_REDIRECT')
    if redirect_url:
        return redirect(redirect_url)
    else:
        return current_app.config['SIGNUP_DELETED_TEXT'] 
Example #3
Source File: asm.py    From assembly with MIT License 6 votes vote down vote up
def unsign_data(token,  **kw):
    """
    To unsign url safe data.
    If expires_in is provided it will Time the signature
    :param token:
    :param secret_key:
    :param salt: (string) a namespace key
    :param kw:
    :return:
    """
    if len(token.split(".")) == 3:
        s = URLSafeTimedSerializer2(secret_key=__CRYPT.get("secret_key"), salt=__CRYPT.get("salt"), **kw)
        value, timestamp = s.loads(token, max_age=None, return_timestamp=True)
        now = datetime.datetime.utcnow()
        if timestamp > now:
            return value
        else:
            raise itsdangerous.SignatureExpired(
                'Signature age %s < %s ' % (timestamp, now),
                payload=value,
                date_signed=timestamp)
    else:
        s = itsdangerous.URLSafeSerializer(secret_key=__CRYPT.get("secret_key"), salt=__CRYPT.get("salt"), **kw)
        return s.loads(token) 
Example #4
Source File: models.py    From realms-wiki with GNU General Public License v2.0 6 votes vote down vote up
def load_token(token):
    # Load unsafe because payload is needed for sig
    sig_okay, payload = URLSafeSerializer(current_app.config['SECRET_KEY']).loads_unsafe(token)

    if not payload:
        return None

    # User key *could* be stored in payload to avoid user lookup in db
    user = User.get_by_id(payload.get('id'))

    if not user:
        return None

    try:
        if BaseUser.signer(sha256(user.password).hexdigest()).loads(token):
            return user
        else:
            return None
    except BadSignature:
        return None 
Example #5
Source File: util.py    From LoginServer with MIT License 5 votes vote down vote up
def get_serializer(secret_key=None):
    if secret_key is None:
        secret_key = app.secret_key
    return URLSafeSerializer(secret_key) 
Example #6
Source File: app.py    From datasette with Apache License 2.0 5 votes vote down vote up
def sign(self, value, namespace="default"):
        return URLSafeSerializer(self._secret, namespace).dumps(value) 
Example #7
Source File: email_links.py    From amivapi with GNU Affero General Public License v3.0 5 votes vote down vote up
def on_confirm_email(token):
    """Email confirmation endpoint.

    We try to confirm the specified signup and redirect to a webpage.
    """
    try:
        s = URLSafeSerializer(get_token_secret())
        signup_id = ObjectId(s.loads(token))
    except BadSignature:
        return "Unknown token"

    patch_internal('eventsignups', {'confirmed': True},
                   skip_validation=True, concurrency_check=False,
                   **{current_app.config['ID_FIELD']: signup_id})

    # Now the user may be able to get accepted, so update the events waiting
    # list
    lookup = {current_app.config['ID_FIELD']: signup_id}
    signup = current_app.data.find_one('eventsignups', None, **lookup)

    update_waiting_list(signup['event'])

    redirect_url = current_app.config.get('EMAIL_CONFIRMED_REDIRECT')
    if redirect_url:
        return redirect(redirect_url)
    else:
        return current_app.config['CONFIRM_TEXT'] 
Example #8
Source File: emails.py    From amivapi with GNU Affero General Public License v3.0 5 votes vote down vote up
def send_confirmmail_to_unregistered_users(items):
    """Send a confirmation email for external signups(email only)

    Args:
        item: The item, which was just inserted into the database
    """
    for item in items:
        if item.get('user') is None:
            event = current_app.data.find_one(
                'events', None,
                **{current_app.config['ID_FIELD']: item['event']})

            title = event.get('title_en') or event.get('title_de')

            s = URLSafeSerializer(get_token_secret())
            token = s.dumps(str(item['_id']))

            if current_app.config.get('SERVER_NAME') is None:
                current_app.logger.warning("SERVER_NAME is not set. E-Mail "
                                           "links will not work!")

            confirm_link = url_for('emails.on_confirm_email', token=token,
                                   _external=True)

            mail([item['email']],
                 'Registration for %s' % title,
                 current_app.config['CONFIRM_EMAIL_TEXT'].format(
                     title=title,
                     link=confirm_link)) 
Example #9
Source File: emails.py    From amivapi with GNU Affero General Public License v3.0 5 votes vote down vote up
def notify_signup_accepted(event, signup):
    """Send an email to a user that his signup was accepted"""
    id_field = current_app.config['ID_FIELD']

    if signup.get('user'):
        lookup = {id_field: signup['user']}
        user = current_app.data.find_one('users', None, **lookup)
        name = user['firstname']
        email = user['email']
    else:
        name = 'Guest of AMIV'
        email = signup['email']

    s = URLSafeSerializer(get_token_secret())
    token = s.dumps(str(signup[id_field]))

    if current_app.config.get('SERVER_NAME') is None:
        current_app.logger.warning("SERVER_NAME is not set. E-Mail links "
                                   "will not work!")

    deletion_link = url_for('emails.on_delete_signup', token=token,
                            _external=True)

    mail([email],
         'Eventsignup accepted',
         current_app.config['ACCEPT_EMAIL_TEXT'].format(
             name=name,
             title=event.get('title_en') or event.get('title_de'),
             link=deletion_link,
             deadline=event['time_register_end'].strftime('%H.%M %d.%m.%Y'))) 
Example #10
Source File: monitors.py    From runbook with Apache License 2.0 5 votes vote down vote up
def genURL(self, cid, rdb):
        ''' This creates a safe url for monitors to send failures or success '''
        s = URLSafeSerializer(self.ctype)
        self.url = s.dumps([cid])
        urldata = {
            'url': self.url
        }
        results = r.table('monitors').get(cid).update(urldata).run(rdb)
        if results['replaced'] == 1:
            return True
        else:
            return False 
Example #11
Source File: users.py    From nyaa with GNU General Public License v3.0 5 votes vote down vote up
def get_serializer(secret_key=None):
    if secret_key is None:
        secret_key = app.secret_key
    return URLSafeSerializer(secret_key) 
Example #12
Source File: utilities.py    From CAQE with MIT License 5 votes vote down vote up
def unsign_data(signed_data):
    """
    Unsign and unserialize signed data
    Parameters
    ----------
    signed_data : str
        The signed and serialized data
    Returns
    -------
    object
        Decrypted data
    """
    s = URLSafeSerializer(app.secret_key)
    return s.loads(signed_data) 
Example #13
Source File: utilities.py    From CAQE with MIT License 5 votes vote down vote up
def sign_data(data):
    """
    Serialize and sign data (likely to be put in a session cookie).
    Parameters
    ----------
    data : object
        Data to be serialized and signed.
    Returns
    -------
    str
        Encrypted data
    """
    s = URLSafeSerializer(app.secret_key)
    return s.dumps(data) 
Example #14
Source File: models.py    From DemonHunter with MIT License 5 votes vote down vote up
def generate_token(self):
        s = URLSafeSerializer('secret-key')        
        self.token = s.dumps(self.address)
        return self.token 
Example #15
Source File: models.py    From realms-wiki with GNU General Public License v2.0 5 votes vote down vote up
def signer(salt):
        return URLSafeSerializer(current_app.config['SECRET_KEY'] + salt) 
Example #16
Source File: models.py    From realms-wiki with GNU General Public License v2.0 5 votes vote down vote up
def signer(salt):
        return URLSafeSerializer(current_app.config['SECRET_KEY'] + salt) 
Example #17
Source File: flask_gopher.py    From flask-gopher with GNU General Public License v3.0 5 votes vote down vote up
def get_gopher_signing_serializer(self, app):
        """
        This is almost the same serializer that the cookie session uses,
        except that it doesn't set an `expiration` time for the session.
        """
        if not app.secret_key:
            return None
        signer_kwargs = dict(
            key_derivation=self.key_derivation,
            digest_method=self.digest_method)
        return URLSafeSerializer(
            app.secret_key,
            salt=self.salt,
            serializer=self.serializer,
            signer_kwargs=signer_kwargs) 
Example #18
Source File: web.py    From mailur with GNU General Public License v3.0 5 votes vote down vote up
def session(callback):
    cookie_name = 'session'
    serializer = URLSafeSerializer(conf['SECRET'])

    def inner(*args, **kwargs):
        data_raw = data = request.get_cookie(cookie_name)
        if data_raw:
            try:
                data = serializer.loads(data_raw)
            except (BadSignature, BadData):
                data = None

        if data:
            conf['USER'] = data['username']

        request.session = data or {}

        try:
            return callback(*args, **kwargs)
        finally:
            if request.session:
                save(request.session)
            elif not data_raw:
                pass
            else:
                response.delete_cookie(cookie_name)

    def save(session):
        cookie_opts = {
            # keep session for 3 days
            'max_age': 3600 * 24 * 3,

            # for security
            'httponly': True,
            'secure': request.headers.get('X-Forwarded-Proto') == 'https',
        }
        data = serializer.dumps(session)
        response.set_cookie(cookie_name, data, **cookie_opts)
    return inner 
Example #19
Source File: security.py    From Flask-Boost with MIT License 5 votes vote down vote up
def decode(something):
    """Decode something with SECRET_KEY."""
    secret_key = current_app.config.get('SECRET_KEY')
    s = URLSafeSerializer(secret_key)
    try:
        return s.loads(something)
    except BadSignature:
        return None 
Example #20
Source File: security.py    From Flask-Boost with MIT License 5 votes vote down vote up
def encode(something):
    """Encode something with SECRET_KEY."""
    secret_key = current_app.config.get('SECRET_KEY')
    s = URLSafeSerializer(secret_key)
    return s.dumps(something) 
Example #21
Source File: views.py    From online-ratings with MIT License 5 votes vote down vote up
def get_serializer(secret_key=None):
    if secret_key is None:
        secret_key = current_app.config['SECRET_KEY']
    return URLSafeSerializer(secret_key) 
Example #22
Source File: security.py    From learning-python with MIT License 5 votes vote down vote up
def decode(something):
    """Decode something with SECRET_KEY."""
    secret_key = current_app.config.get('SECRET_KEY')
    s = URLSafeSerializer(secret_key)
    try:
        return s.loads(something)
    except BadSignature:
        return None 
Example #23
Source File: security.py    From learning-python with MIT License 5 votes vote down vote up
def encode(something):
    """Encode something with SECRET_KEY."""
    secret_key = current_app.config.get('SECRET_KEY')
    s = URLSafeSerializer(secret_key)
    return s.dumps(something) 
Example #24
Source File: database.py    From cascade-server with Apache License 2.0 5 votes vote down vote up
def connect():
    global serializer, fernet
    crypto_info = settings.load()['database']['crypto']
    mongo_host = settings.load()['database']['mongo'].get('host', '127.0.0.1')
    mongo_port = settings.load()['database']['mongo'].get('port', '27017')
    serializer = URLSafeSerializer(crypto_info['key'])
    fernet = Fernet(crypto_info['fernet'])
    mongoengine.connect(name, host=mongo_host, port=mongo_port, tz_aware=True) 
Example #25
Source File: app.py    From datasette with Apache License 2.0 5 votes vote down vote up
def unsign(self, signed, namespace="default"):
        return URLSafeSerializer(self._secret, namespace).loads(signed)