diff --git a/api/kiwi_vpn_api/db_new/user.py b/api/kiwi_vpn_api/db_new/user.py index 623640d..45235e6 100644 --- a/api/kiwi_vpn_api/db_new/user.py +++ b/api/kiwi_vpn_api/db_new/user.py @@ -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) diff --git a/api/kiwi_vpn_api/main.py b/api/kiwi_vpn_api/main.py index 70d6915..335d058 100755 --- a/api/kiwi_vpn_api/main.py +++ b/api/kiwi_vpn_api/main.py @@ -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: