Esempio n. 1
0
    def create_token(self,
                     client_id,
                     roles=[],
                     requesting_client=None,
                     expiration=None):
        """Create a JWT token for use in Lowball applications.

        :param client_id: client id for the token
        :type client_id: str
        :param roles: list of roles to give the client
        :type roles: list(str)
        :param requesting_client: The user requesting the token
        :type requesting_client: str
        :param expiration: time of expiration for this token
        :type expiration: datetime
        :return: Token and token data
        :rtype: str, Token
        """

        if not client_id or not isinstance(client_id, str):
            raise BadRequestException("Invalid client id")

        if not roles:
            roles = []
        if not isinstance(roles, list) or not all(
                isinstance(r, str) for r in roles):
            raise BadRequestException("Roles must be a list of strings")

        if requesting_client is not None and not isinstance(
                requesting_client, str):
            raise BadRequestException("Invalid requesting client id")

        now = datetime.datetime.utcnow()

        if not requesting_client:
            requesting_client = client_id

        if expiration is None:
            expiration = now + datetime.timedelta(
                seconds=self.config.default_token_life)

        token_id = generate_token_id()
        token_data = Token(cid=client_id,
                           r=roles,
                           cts=now,
                           ets=expiration,
                           rcid=requesting_client,
                           tid=token_id)

        if token_data.expiration - now > datetime.timedelta(
                seconds=self.config.max_token_life):
            raise InvalidTokenLifeException

        token = jwt.encode(token_data.to_dict(),
                           self.config.token_secret,
                           algorithm="HS256")

        return token, token_data
Esempio n. 2
0
 def test_to_dict_method_returns_proper_data(self, username, roles, created,
                                             expiration, issued_by,
                                             token_id, token_dict):
     token = Token(cid=username,
                   r=roles,
                   cts=created,
                   ets=expiration,
                   rcid=issued_by,
                   tid=token_id)
     assert token.to_dict() == token_dict