How to use the itsdangerous.TimestampSigner function in itsdangerous

To help you get started, we’ve selected a few itsdangerous examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github encode / hostedapi / tests / client.py View on Github external
def __init__(self, app, raise_server_exceptions=True):
        from source.settings import SECRET

        dispatch = ASGIDispatch(app=app, raise_app_exceptions=raise_server_exceptions)
        self.signer = itsdangerous.TimestampSigner(SECRET)
        super().__init__(
            base_url="https://testserver",
            dispatch=dispatch,
            headers={"accept": "text/html; */*"},
        )
github AppEnlight / appenlight / backend / src / appenlight / lib / utils / __init__.py View on Github external
def channelstream_request(
    secret, endpoint, payload, throw_exceptions=False, servers=None
):
    responses = []
    if not servers:
        servers = []

    signer = TimestampSigner(secret)
    sig_for_server = signer.sign(endpoint)
    for secret, server in [(s["secret"], s["server"]) for s in servers]:
        response = {}
        secret_headers = {
            "x-channelstream-secret": sig_for_server,
            "x-channelstream-endpoint": endpoint,
            "Content-Type": "application/json",
        }
        url = "%s%s" % (server, endpoint)
        try:
            response = requests.post(
                url,
                data=json.dumps(payload, cls=DateTimeEncoder),
                headers=secret_headers,
                verify=False,
                timeout=2,
github roddyofchina / SimpletourDevops / webapp / views.py View on Github external
registerobj=forms.Register()       #实例化forms
    restdata['data'] = registerobj     #将对象传到模板中

    if request.method == 'POST':
        form = forms.Register(request.POST)
        if form.is_valid():
            username = request.POST['username']
            email = request.POST['email']
            password1 = request.POST['password1']
            password2 = request.POST['password2']
            if not Suser.objects.all().filter(email=email):    #先判断是否存在该用户
                if form.pwd_validate(password1,password2):     #判断密码是否一致
                    user = Suser.objects.create_user(email,username,password1)
                    user.save()
                    #生成验证连接并发送邮件
                    s=TimestampSigner(django_settings.SECRET_KEY)
                    registerstring = s.sign(email)
                    sendmail.delay(dict(to=email,string=registerstring))   #发送邮件
                    return HttpResponseRedirect('/web/login/')
                else:
                    error=u'密码输入不一致!!'
                    restdata['regerror'] = error
            else:
                error=u'用户已存在,请重新输入!!!!!'
                restdata['regerror'] = error
        else:
            restdata['data'] = form
    return render(request,'webapp/register.html',restdata)
github pypa / warehouse / warehouse / utils / crypto.py View on Github external
"random_token",
]


def random_token():
    token = base64.urlsafe_b64encode(os.urandom(32)).rstrip(b"=")
    return token.decode("utf8")


class Signer(_Signer):

    default_digest_method = hashlib.sha512
    default_key_derivation = "hmac"


class TimestampSigner(_TimestampSigner):

    default_digest_method = hashlib.sha512
    default_key_derivation = "hmac"


class URLSafeTimedSerializer(_URLSafeTimedSerializer):

    default_signer = TimestampSigner
github feisuzhu / thbattle / backend / player / models.py View on Github external
help_text='勋章',
    )
    friends = models.ManyToManyField(
        'self',
        related_name='friended_by', verbose_name='好友',
        symmetrical=False, blank=True,
        help_text='好友',
    )
    blocks = models.ManyToManyField(
        'self',
        related_name='blocked_by', verbose_name='黑名单',
        symmetrical=False, blank=True,
        help_text='黑名单',
    )

    token_signer = itsdangerous.TimestampSigner(backend.settings.SECRET_KEY)

    def token(self):
        data = base64.b64encode(msgpack.dumps({'player': True, 'id': self.id}))
        return self.token_signer.sign(data).decode('utf-8')

    @classmethod
    def from_token(cls, token, max_age=30):
        data = cls.token_signer.unsign(token.encode('utf-8'), max_age=max_age)
        data = msgpack.loads(base64.b64decode(data), encoding='utf-8')
        if data.get('player') is not True:
            return None

        return cls.objects.get(id=data['id'])

    def __str__(self):
        return self.name
github CMGS / titan / views / account / alias.py View on Github external
def decode(self, stub):
        try:
            s = URLSafeSerializer(config.SECRET_KEY)
            e = s.loads(stub)
            s = TimestampSigner(config.SECRET_KEY)
            e = s.unsign(e, max_age=config.VERIFY_STUB_EXPIRE)
            return e
        except Exception:
            return None
github marrow / contentment / web / ext / contentment.py View on Github external
dom = context.request.host.partition(':')[0]
		parts = MAP.get(dom, (dom, 'en', ''))
		context.domain = parts[0]
		context.lang = parts[1]
		context.otherlang = parts[2]
		context.site = context.croot = Asset.objects.nearest('/' + context.domain)
		context.D = partial(D_, lang=parts[1])
		context.replacements = dict(context=context)
		
		if context.croot:
			context.theme = load(context.croot.properties.theme + ':page')
		else:
			context.theme = load('web.theme.bootstrap.base:page')
		
		if 'SECRET' in os.environ and 'uid' in context.request.cookies:
			s = TimestampSigner(os.environ['SECRET'])
			try:
				uc = user_cookie.bind(context.request)
				token = uc.get_value()
				token = s.unsign(token, max_age=60*60*24).decode('ascii')
			except:
				context.uid = None
				if __debug__: raise
			else:
				context.uid = token.partition('-')[2]
		else:
			context.uid = None
		
		log.info("Prepared context.", extra=dict(domain=[dom, context.domain], lang=context.lang, root=repr(context.croot), theme=repr(context.theme)))
github infobyte / faraday / server / websocket_factories.py View on Github external
"""
            We only support JOIN and LEAVE workspace messages.
            When authentication is implemented we need to verify
            that the user can join the selected workspace.
            When authentication is implemented we need to reply
            the client if the join failed.
        """
        if not is_binary:
            message = json.loads(payload)
            if message['action'] == 'JOIN_WORKSPACE':
                if 'workspace' not in message or 'token' not in message:
                    logger.warning('Invalid join workspace message: '
                                   '{}'.format(message))
                    self.sendClose()
                    return
                signer = itsdangerous.TimestampSigner(app.config['SECRET_KEY'],
                                                      salt="websocket")
                try:
                    workspace_id = signer.unsign(message['token'], max_age=60)
                except itsdangerous.BadData as e:
                    self.sendClose()
                    logger.warning('Invalid websocket token for workspace '
                                   '{}'.format(message['workspace']))
                    logger.exception(e)
                else:
                    with app.app_context():
                        workspace = Workspace.query.get(int(workspace_id))
                    if workspace.name != message['workspace']:
                        logger.warning(
                            'Trying to join workspace {} with token of '
                            'workspace {}. Rejecting.'.format(
                                message['workspace'], workspace.name
github ironman5366 / W.I.L.L / will / API / __init__.py View on Github external
def _load_configuration(self):
        """
        Go through relevant configuration keys and load it into the class, checking for correct types as it goes.
        Throw an error if any of the keys are missing or of the wrong type
        Required keys:
            - secret-key: str: the key that the HMAC signer will use
            - banned-ips: (list, set): an iterable of permanently banned ips that the API should always refuse requests
            from
        """
        try:
            error_cause = "secret-key"
            secret_key = self.configuration_data["secret-key"]
            assert type(secret_key) == str
            self.signer = Signer(secret_key)
            self.timestampsigner = TimestampSigner(secret_key)
            hooks.signer = self.signer

            v1.signer = self.signer
            v1.timestampsigner = self.timestampsigner
            error_cause = "banned-ips"
            assert type(self.configuration_data["banned-ips"]) in (list, set)
        except (KeyError, AssertionError):
            error_string = "Please ensure that {0} is properly defined in your configuration_file.".format(error_cause)
            log.error(error_string)
            raise ConfigurationError(error_string)
        self._conf_loaded = True
github encode / starlette / starlette / middleware / sessions.py View on Github external
def __init__(
        self,
        app: ASGIApp,
        secret_key: typing.Union[str, Secret],
        session_cookie: str = "session",
        max_age: int = 14 * 24 * 60 * 60,  # 14 days, in seconds
        same_site: str = "lax",
        https_only: bool = False,
    ) -> None:
        self.app = app
        self.signer = itsdangerous.TimestampSigner(str(secret_key))
        self.session_cookie = session_cookie
        self.max_age = max_age
        self.security_flags = "httponly; samesite=" + same_site
        if https_only:  # Secure flag can be used with HTTPS only
            self.security_flags += "; secure"