Ejemplo n.º 1
0
    async def auth_client_registration(self,
                                       request: sanic.request.Request) -> bool:
        if "authorization" not in request.headers:
            logger.warning(
                "Client attempted registration without authorization header")
            return False

        hdr = request.headers["authorization"]
        if "Bearer" not in hdr:
            logger.warning(
                "Client attempted registration without Bearer token")
            return False

        token = hdr.split("Bearer")[-1].strip()
        if self._provider.client_registration_key is None:
            return True
        elif (isinstance(self._provider.client_registration_key, str)
              and self._provider.client_registration_key != token):
            logger.warning(
                "Client attempted registration without incorrect Bearer token {0}"
                .format(masked(token)))
            return False
        elif (inspect.iscoroutinefunction(
                self._provider.client_registration_key)
              and token != await self._provider.client_registration_key):
            logger.warning(
                "Client attempted registration without incorrect Bearer token {0}"
                .format(masked(token)))
            return False

        return True
Ejemplo n.º 2
0
 async def delete_token_by_access_token(self, access_token: str):
     try:
         await self._table.put_item(Key={"access_token": access_token})
         logger.info("Deleted token {0}".format(masked(access_token)))
     except Exception as err:
         logger.exception("Failed to delete token {0}".format(
             masked(access_token)),
                          exc_info=err)
Ejemplo n.º 3
0
 async def _save_code(self, code: Dict[str, Any]):
     try:
         await self._table.put_item(Item=code)
         logger.info("Saved code {0}".format(masked(code["code"])))
     except Exception as err:
         logger.exception("Failed to save code {0}".format(
             masked(code["code"])),
                          exc_info=err)
Ejemplo n.º 4
0
 async def delete_token_by_access_token(self, access_token: str):
     try:
         key = "token_" + access_token
         await self._redis.delete(key)
         logger.info("Deleted token {0}".format(masked(access_token)))
     except Exception as err:
         logger.exception("Failed to delete token {0}".format(
             masked(access_token)),
                          exc_info=err)
Ejemplo n.º 5
0
 async def save_token(self, token: Dict[str, Any]):
     try:
         await self._table.put_item(Item=token)
         logger.info("Saved token {0}".format(masked(
             token["access_token"])))
     except Exception as err:
         logger.exception("Failed to save token {0}".format(
             masked(token["access_token"])),
                          exc_info=err)
Ejemplo n.º 6
0
 async def mark_used_by_id(self, id_: str):
     try:
         code = await self.get_by_id(id_)
         code["used"] = True
         await self._save_code(code)
         logger.info("Marked code {0} as used".format(masked(id_)))
     except Exception as err:
         logger.exception("Failed to mark code {0} as used".format(
             masked(id_)),
                          exc_info=err)
Ejemplo n.º 7
0
 async def mark_used_by_id(self, id_: str):
     try:
         await self._table.update_item(
             Key={"code": id_},
             UpdateExpression="SET used = :u",
             ExpressionAttributeValues={":u": True})
         logger.info("Marked code {0} as used".format(masked(id_)))
     except Exception as err:
         logger.exception("Failed to mark code {0} as used".format(
             masked(id_)),
                          exc_info=err)
Ejemplo n.º 8
0
 async def _save_code(self, code: Dict[str, Any]):
     try:
         ttl = int(code["expires_at"] - datetime.datetime.now().timestamp())
         key = "code_" + code["code"]
         value = pickle.dumps(code)
         await self._redis.set(key=key, value=value, expire=ttl)
         logger.info("Saved code {0}".format(masked(code["code"])))
     except Exception as err:
         logger.exception("Failed to save code {0}".format(
             masked(code["code"])),
                          exc_info=err)
Ejemplo n.º 9
0
 async def save_token(self, token: Dict[str, Any]):
     try:
         ttl = int(token["expires_at"] -
                   datetime.datetime.now().timestamp())
         key = "token_" + token["access_token"]
         value = pickle.dumps(token)
         await self._redis.set(key=key, value=value, expire=ttl)
         logger.info("Saved token {0}".format(masked(
             token["access_token"])))
     except Exception as err:
         logger.exception("Failed to save token {0}".format(
             masked(token["access_token"])),
                          exc_info=err)
Ejemplo n.º 10
0
    async def mark_used_by_id(self, id_: str):
        try:
            code = self._store[id_]

            code["used"] = True
            logger.info("Marked code {0} as used".format(masked(code["code"])))
        except KeyError:
            pass
Ejemplo n.º 11
0
 async def get_by_id(self, id_: str) -> Union[Dict[str, Any], None]:
     try:
         resp = await self._table.get_item(Key={"code": id_})
         if "Item" in resp:
             return resp["Item"]
     except Exception as err:
         logger.exception("Failed to get code {0}".format(masked(id_)),
                          exc_info=err)
     return None
Ejemplo n.º 12
0
    async def delete_token_by_code(self, code: str):
        to_delete = []

        for access_token, token in self._store.items():
            if token.get("code") == code:
                to_delete.append(access_token)

        for access_token in to_delete:
            del self._store[access_token]
            logger.info("Deleted token {0}".format(masked(access_token)))
Ejemplo n.º 13
0
 async def get_token_by_access_token(
         self, access_token: str) -> Union[Dict[str, Any], None]:
     try:
         resp = await self._table.get_item(
             Key={"access_token": access_token})
         if "Item" in resp:
             return resp["Item"]
     except Exception as err:
         logger.exception("Failed to get token {0}".format(
             masked(access_token)),
                          exc_info=err)
     return None
Ejemplo n.º 14
0
    async def get_by_id(self, id_: str) -> Union[Dict[str, Any], None]:
        result = None

        try:
            key = "code_" + id_
            pickled_value = await self._redis.get(key=key)
            if pickled_value:
                result = pickle.loads(pickled_value)
        except Exception as err:
            logger.exception("Failed to get code {0}".format(masked(id_)),
                             exc_info=err)
        return result
Ejemplo n.º 15
0
 async def get_token_by_access_token(
         self, access_token: str) -> Union[Dict[str, Any], None]:
     try:
         key = "token_" + access_token
         token_data = await self._redis.get(key)
         if token_data:
             return pickle.loads(token_data)
     except Exception as err:
         logger.exception("Failed to get token {0}".format(
             masked(access_token)),
                          exc_info=err)
     return None
Ejemplo n.º 16
0
    async def delete_token_by_code(self, code: str):
        try:
            all_token_keys = await self._redis.keys("token_*")
            if all_token_keys:
                to_delete = []

                # Iterate through all tokens, unpickle them
                # if they stem from this code, invalidate
                all_tokens = await self._redis.mget(*all_token_keys)
                for token_pickle in all_tokens:
                    token = pickle.loads(token_pickle)
                    if token["code"] == code:
                        to_delete.append("token_" + token["access_token"])

                if to_delete:
                    await self._redis.delete(*to_delete)
                    logger.info("Deleted tokens {0}".format(" ".join(
                        [masked(item) for item in to_delete])))

        except Exception as err:
            logger.exception("Failed to delete tokens by code {0}".format(
                masked(code)),
                             exc_info=err)
Ejemplo n.º 17
0
    async def get_token_by_refresh_token(
            self, refresh_token: str) -> Union[Dict[str, Any], None]:
        try:
            all_token_keys = await self._redis.keys("token_*")
            if all_token_keys:
                # Iterate through all tokens, unpickle them
                all_tokens = await self._redis.mget(*all_token_keys)
                for token_pickle in all_tokens:
                    token = pickle.loads(token_pickle)
                    if token["refresh_token"] == refresh_token:
                        return token

        except Exception as err:
            logger.exception("Failed to get token by refresh token {0}".format(
                masked(refresh_token)),
                             exc_info=err)
Ejemplo n.º 18
0
 async def _save_code(self, code: Dict[str, Any]):
     self._store[code["code"]] = code
     logger.info("Saved code {0}".format(masked(code["code"])))
Ejemplo n.º 19
0
 async def delete_token_by_access_token(self, access_token: str):
     try:
         del self._store[access_token]
         logger.info("Deleted token {0}".format(masked(access_token)))
     except KeyError:
         pass
Ejemplo n.º 20
0
 async def save_token(self, token: Dict[str, Any]):
     self._store[token["access_token"]] = token
     logger.info("Saved token {0}".format(masked(token["access_token"])))