User CRUD

This commit is contained in:
Jörn-Michael Miehe 2022-03-27 13:47:18 +00:00
parent ae3627cbe0
commit 9625336df9
2 changed files with 47 additions and 0 deletions

View file

@ -46,10 +46,54 @@ class User(UserBase, table=True):
@classmethod
def get(cls, name: str) -> User | None:
"""
Load user from database by name.
"""
with Connection.session as db:
return db.get(cls, name)
@classmethod
def authenticate(
cls,
name: str,
password: str,
) -> User | None:
"""
Authenticate with name/password against users in database.
"""
crypt_context = Config.load_sync().crypto.crypt_context_sync
if (user := cls.get(name)) is None:
# nonexistent user, fake doing password verification
crypt_context.dummy_verify()
return None
if not crypt_context.verify(password, user.password):
# password hash mismatch
return None
return user
def update(self) -> None:
"""
Update this user in the database.
"""
with Connection.session as db:
db.add(self)
db.commit()
db.refresh(self)
def delete(self) -> bool:
"""
Delete this user from the database.
"""
with Connection.session as db:
db.delete(self)
db.commit()
class UserCreate(UserBase):
password: str | None = Field(default=None)
password_clear: str | None = Field(default=None)

View file

@ -61,6 +61,9 @@ async def on_startup() -> None:
)
print(user.User.get("Uwe"))
print(user.User.authenticate("Uwe", "uwe"))
uwe = user.User.authenticate("Uwe", "ulf")
def main() -> None: