Verified Commit 66d487fc authored by Jakob Moser's avatar Jakob Moser
Browse files

Add basic User type

A user actually only has a uuid and a name, this is because we look all relevant data up in LDAP.

We only save the User, so that we can re-identify them even if e.g. their login changes
parent 5775a6e6
Loading
Loading
Loading
Loading

portal/model/User.py

0 → 100644
+44 −0
Changes for portal/model/User.py: 44 added lines, 0 removed lines.
Original line number Diff line number Diff line
from typing import Optional, Sequence, Self

from sqlalchemy.orm import Mapped, mapped_column

from portal import db
from portal.model.Base import Base


class User(Base):
    name: Mapped[str] = mapped_column(unique=True, index=True)

    def __init__(self, name: str) -> None:
        self.name = name

    @classmethod
    def get_by_name(cls, name: str) -> Optional[Self]:
        """Return the user with the given name, if they exist."""
        return db.session.execute(
            db.select(cls).where(cls.name == name)
        ).scalar_one_or_none()

    @property
    def keys(self) -> Sequence["Key"]:
        """
        Get all keys created by this user
        """
        return (
            db.session.execute(db.select(Key).where(Key.user_uuid == self.uuid))
            .scalars()
            .all()
        )

    def delete_keys(self) -> None:
        """
        Delete all keys created by this user
        """
        db.session.execute(db.delete(Key).where(Key.user_uuid == self.uuid))
        db.session.commit()

    def to_dict(self) -> dict[str, str]:
        return {"uuid": self.uuid, "name": self.name}


from portal.model.Key import Key