Skip to content

Key

Key

Bases: BaseModel

Utility class for creating keys.

Source code in src/api_key_factory/factory/key.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Key(BaseModel):
    """Utility class for creating keys."""

    prefix: str
    rand_uuid: str

    def __init__(self, prefix: str = ""):
        """Constructor.

        Args:
            prefix (str): Prefix of the token. Default empty.
        """
        rand_uuid = uuid.uuid4()

        super().__init__(prefix=prefix, rand_uuid=str(rand_uuid))

    def get_value(self) -> str:
        """Get the token as a string.

        Returns:
            str: The token string.
        """
        if len(self.prefix) > 0:
            value = self.prefix + "-" + self.rand_uuid
        else:
            value = self.rand_uuid

        return value

    def get_hash(self) -> str:
        """Get the token as a hashed SHA-256 string.

        Returns:
            str: The hashed token string.
        """
        value = self.get_value()

        hash_object = hashlib.sha256()
        value_encoded = value.encode("utf-8")
        hash_object.update(value_encoded)

        return hash_object.hexdigest()

__init__(prefix='')

Constructor.

Parameters:

Name Type Description Default
prefix str

Prefix of the token. Default empty.

''
Source code in src/api_key_factory/factory/key.py
15
16
17
18
19
20
21
22
23
def __init__(self, prefix: str = ""):
    """Constructor.

    Args:
        prefix (str): Prefix of the token. Default empty.
    """
    rand_uuid = uuid.uuid4()

    super().__init__(prefix=prefix, rand_uuid=str(rand_uuid))

get_hash()

Get the token as a hashed SHA-256 string.

Returns:

Name Type Description
str str

The hashed token string.

Source code in src/api_key_factory/factory/key.py
38
39
40
41
42
43
44
45
46
47
48
49
50
def get_hash(self) -> str:
    """Get the token as a hashed SHA-256 string.

    Returns:
        str: The hashed token string.
    """
    value = self.get_value()

    hash_object = hashlib.sha256()
    value_encoded = value.encode("utf-8")
    hash_object.update(value_encoded)

    return hash_object.hexdigest()

get_value()

Get the token as a string.

Returns:

Name Type Description
str str

The token string.

Source code in src/api_key_factory/factory/key.py
25
26
27
28
29
30
31
32
33
34
35
36
def get_value(self) -> str:
    """Get the token as a string.

    Returns:
        str: The token string.
    """
    if len(self.prefix) > 0:
        value = self.prefix + "-" + self.rand_uuid
    else:
        value = self.rand_uuid

    return value