Ejemplo n.º 1
0
def encode_jwt(payload: dict, token_type: TokenType) -> str:

    exp = (settings.JWT_EXPIRATION_DELTA if token_type is TokenType.ACCESS else
           settings.JWT_REFRESH_EXPIRATION_DELTA)

    jti_size = (settings.JWT_JTI_SIZE if settings.JWT_BLACKLIST_ENABLED
                and token_type.value in settings.JWT_BLACKLIST_TOKEN_CHECKS
                else 0)

    payload["type"] = token_type.value
    token = generate_jwt(
        payload,
        _secret_key,
        algorithm=settings.JWT_ALGORITHM,
        lifetime=exp,
        jti_size=jti_size,
    )

    if settings.JWT_ENCRYPT:
        token = JWE(
            plaintext=token.encode("utf-8"),
            protected={
                "alg": settings.JWE_ALGORITHM,
                "enc": settings.JWE_ENCRYPTION,
                "typ": "JWE",
            },
        )
        token.add_recipient(_encryption_key)
        token = token.serialize()
    return token
Ejemplo n.º 2
0
 def set(self, key, value, replace=False):
     self.protected_header = {'alg': 'dir', 'enc': self.master_enctype}
     if self.secret_protection != 'encrypt':
         self.protected_header['custodia.key'] = key
     protected = json_encode(self.protected_header)
     jwe = JWE(value, protected)
     jwe.add_recipient(self.mkey)
     cvalue = jwe.serialize(compact=True)
     return self.store.set(key, cvalue, replace)
Ejemplo n.º 3
0
 def encrypt(self, plaintext,
             _protected='{"alg":"RSA-OAEP","enc":"A256GCM"}',
             _public_jwk=None):
     try:
         jwe = JWE(plaintext=plaintext,
                   protected=_protected)
         _public_jwk = _public_jwk if _public_jwk else self._public_jwk
         jwe.add_recipient(_public_jwk)
         ciphertext = jwe.serialize(compact=True)
     except Exception:
         raise ValueError("Couldn't encrypt message.")
     return ciphertext
Ejemplo n.º 4
0
 def encrypt(self,
             plaintext,
             _protected='{"alg":"RSA-OAEP","enc":"A256GCM"}',
             _public_jwk=None):
     try:
         jwe = JWE(plaintext=plaintext, protected=_protected)
         _public_jwk = _public_jwk if _public_jwk else self._public_jwk
         jwe.add_recipient(_public_jwk)
         ciphertext = jwe.serialize(compact=True)
     except Exception:
         raise ValueError("Couldn't encrypt message.")
     return ciphertext
Ejemplo n.º 5
0
    def make_encrypted_token(self, key):
        """Encrypts the payload.

        Creates a JWE token with the header as the JWE protected header and
        the claims as the plaintext. See (:class:`jwcrypto.jwe.JWE`) for
        details on the exceptions that may be reaised.

        :param key: A (:class:`jwcrypto.jwk.JWK`) key.
        """

        t = JWE(self.claims, self.header)
        t.add_recipient(key)
        self.token = t
Ejemplo n.º 6
0
    def make_encrypted_token(self, key):
        """Encrypts the payload.

        Creates a JWE token with the header as the JWE protected header and
        the claims as the plaintext. See (:class:`jwcrypto.jwe.JWE`) for
        details on the exceptions that may be reaised.

        :param key: A (:class:`jwcrypto.jwk.JWK`) key.
        """

        t = JWE(self.claims, self.header)
        t.add_recipient(key)
        self.token = t
Ejemplo n.º 7
0
def forgotpass(request):
    if request.user:
        # already logged in, redirect to home
        return HTTPFound(location=request.route_url('home'))
    next_url = request.params.get('next', None)
    if not next_url:
        next_url = request.route_url('home')
    login = ''
    if 'form.submitted' in request.params:
        login = request.params.get('email')
        item = request.dbsession.query(User).filter_by(email=login).first()
        if item is not None:
            # Generate link:
            key = JWK(**loads(request.registry.settings["jwt.secret"]))
            mins = request.registry.settings["jwt.expire"]
            payload = dumps({
                "id": item.id,
                "dt": timegm(gmtime()),
                "hash": hexlify(item.password_hash).decode("utf-8")
            })
            token = JWE(payload.encode('utf-8'),
                        json_encode({
                            "alg": "A256KW",
                            "enc": "A256CBC-HS512"
                        }))
            token.add_recipient(key)
            link = request.route_url("resetpass", jwe=token.serialize(True))
            message = Message(
                subject="VS Leaderboard - Reset Password",
                recipients=[item.email],
                body="To reset your password, please click: \n{0}\n".format(
                    link) +
                "This link will expire in {0} minutes.".format(mins))
            request.mailer.send(message)
        request.session.flash(
            "s|If that e-mail address is used it will receive a password reset link."
        )

    return dict(
        url=request.route_url('forgotpass'),
        next_url=next_url,
        login=login,
    )
Ejemplo n.º 8
0
def make_enc_kem(name, value, sig_key, alg, enc_key, enc):
    plaintext = make_sig_kem(name, value, sig_key, alg)
    eprot = {'kid': enc_key.key_id, 'alg': enc[0], 'enc': enc[1]}
    jwe = JWE(plaintext, json_encode(eprot))
    jwe.add_recipient(enc_key)
    return jwe.serialize(compact=True)
Ejemplo n.º 9
0
 def set(self, key, value, replace=False):
     jwe = JWE(value, json_encode({'alg': 'dir', 'enc': self.enc}))
     jwe.add_recipient(self.mkey)
     cvalue = jwe.serialize(compact=True)
     return self.store.set(key, cvalue, replace)
Ejemplo n.º 10
0
def make_enc_kem(name, value, sig_key, alg, enc_key, enc):
    plaintext = make_sig_kem(name, value, sig_key, alg)
    eprot = {'kid': enc_key.key_id, 'alg': enc[0], 'enc': enc[1]}
    jwe = JWE(plaintext, json_encode(eprot))
    jwe.add_recipient(enc_key)
    return jwe.serialize(compact=True)
Ejemplo n.º 11
0
 def set(self, key, value, replace=False):
     jwe = JWE(value, json_encode({'alg': 'dir', 'enc': self.enc}))
     jwe.add_recipient(self.mkey)
     cvalue = jwe.serialize(compact=True)
     return super(EncryptedStore, self).set(key, cvalue, replace)
Ejemplo n.º 12
0
 def set(self, key, value, replace=False):
     protected = json_encode({'alg': 'dir', 'enc': self.master_enctype})
     jwe = JWE(value, protected)
     jwe.add_recipient(self.mkey)
     cvalue = jwe.serialize(compact=True)
     return self.store.set(key, cvalue, replace)
Ejemplo n.º 13
0
def make_enc_kem(name, value, sig_key, alg, enc_key, enc):
    plaintext = make_sig_kem(name, value, sig_key, alg)
    eprot = {"kid": enc_key.key_id, "alg": enc[0], "enc": enc[1]}
    E = JWE(plaintext, json_encode(eprot))
    E.add_recipient(enc_key)
    return E.serialize(compact=True)
Ejemplo n.º 14
0
 def set(self, key, value, replace=False):
     protected = json_encode({'alg': 'dir', 'enc': self.master_enctype})
     jwe = JWE(value, protected)
     jwe.add_recipient(self.mkey)
     cvalue = jwe.serialize(compact=True)
     return super(EncryptedStore, self).set(key, cvalue, replace)