Skip to content

opensampl.db.access_orm

ORM for managing access to openSAMPL database and endpoints

APIAccessKey

Bases: Base

Table for recording and managing API access keys.

Source code in opensampl/db/access_orm.py
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
class APIAccessKey(Base):
    """Table for recording and managing API access keys."""

    __tablename__ = "api_access_keys"

    id = Column(Integer, primary_key=True, index=True)
    key = Column(String(64), unique=True, nullable=False, index=True)
    created_at = Column(DateTime, default=lambda: datetime.now(UTC).replace(tzinfo=None), nullable=False)
    expires_at = Column(DateTime, nullable=True)

    def generate_key(self) -> str:
        """
        Generate the API access key.

        Returns:
            The generated access key string.

        """
        self.key = secrets.token_urlsafe(48)
        return self.key

    def is_expired(self) -> bool:
        """
        Check if API access key is expired.

        Returns:
            True if the key is expired, False otherwise.

        """
        if self.expires_at is None:
            return False
        expiry = self.expires_at
        if expiry.tzinfo is None:
            expiry = expiry.replace(tzinfo=UTC)
        return datetime.now(tz=UTC) > expiry

generate_key()

Generate the API access key.

Returns:

Type Description
str

The generated access key string.

Source code in opensampl/db/access_orm.py
23
24
25
26
27
28
29
30
31
32
def generate_key(self) -> str:
    """
    Generate the API access key.

    Returns:
        The generated access key string.

    """
    self.key = secrets.token_urlsafe(48)
    return self.key

is_expired()

Check if API access key is expired.

Returns:

Type Description
bool

True if the key is expired, False otherwise.

Source code in opensampl/db/access_orm.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def is_expired(self) -> bool:
    """
    Check if API access key is expired.

    Returns:
        True if the key is expired, False otherwise.

    """
    if self.expires_at is None:
        return False
    expiry = self.expires_at
    if expiry.tzinfo is None:
        expiry = expiry.replace(tzinfo=UTC)
    return datetime.now(tz=UTC) > expiry