Skip to content

Security

materia.security

password

hash_password

hash_password(password, algo='bcrypt')
PARAMETER DESCRIPTION
password

TYPE: str

algo

TYPE: Literal['bcrypt'] DEFAULT: 'bcrypt'

Source code in src/materia/security/password.py
 6
 7
 8
 9
10
def hash_password(password: str, algo: Literal["bcrypt"] = "bcrypt") -> str:
    if algo == "bcrypt":
        return bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
    else:
        raise NotImplementedError(algo)

validate_password

validate_password(password, hash, algo='bcrypt')
PARAMETER DESCRIPTION
password

TYPE: str

hash

TYPE: str

algo

TYPE: Literal['bcrypt'] DEFAULT: 'bcrypt'

Source code in src/materia/security/password.py
13
14
15
16
17
18
19
def validate_password(
    password: str, hash: str, algo: Literal["bcrypt"] = "bcrypt"
) -> bool:
    if algo == "bcrypt":
        return bcrypt.checkpw(password.encode(), hash.encode())
    else:
        raise NotImplementedError(algo)

secret_key

generate_key

generate_key()
Source code in src/materia/security/secret_key.py
6
7
def generate_key() -> bytes:
    return Fernet.generate_key()

encrypt_payload

encrypt_payload(payload, key, valid_base64=True)
PARAMETER DESCRIPTION
payload

TYPE: bytes

key

TYPE: bytes

valid_base64

TYPE: bool DEFAULT: True

Source code in src/materia/security/secret_key.py
 9
10
11
12
13
14
15
16
def encrypt_payload(payload: bytes, key: bytes, valid_base64: bool = True) -> bytes:
    func = Fernet(key)
    data = func.encrypt(payload)

    if valid_base64:
        data = base64.b64encode(data, b"-_").decode().replace("=", "").encode() 

    return data

token

TokenClaims

Bases: BaseModel

sub instance-attribute
sub
exp instance-attribute
exp
iat instance-attribute
iat
iss class-attribute instance-attribute
iss = None

generate_token

generate_token(sub, secret, duration, iss=None)
PARAMETER DESCRIPTION
sub

TYPE: str

secret

TYPE: str

duration

TYPE: int

iss

TYPE: Optional[str] DEFAULT: None

Source code in src/materia/security/token.py
15
16
17
18
19
20
21
22
23
def generate_token(
    sub: str, secret: str, duration: int, iss: Optional[str] = None
) -> str:
    now = datetime.datetime.now()
    iat = now.timestamp()
    exp = (now + datetime.timedelta(seconds=duration)).timestamp()
    claims = TokenClaims(sub=sub, exp=int(exp), iat=int(iat), iss=iss)

    return jwt.encode(claims.model_dump(), secret)

validate_token

validate_token(token, secret)
PARAMETER DESCRIPTION
token

TYPE: str

secret

TYPE: str

Source code in src/materia/security/token.py
26
27
28
29
def validate_token(token: str, secret: str) -> TokenClaims:
    payload = jwt.decode(token, secret, algorithms=["HS256"])

    return TokenClaims(**payload)