"""Service to handle user_token operations.""" import uuid from datetime import datetime from typing import Optional from atheneum.db import db from atheneum.model import User, UserToken def generate_token() -> uuid.UUID: """ Generate a unique token. :return: """ return uuid.uuid4() def create( user: User, note: Optional[str] = None, enabled: bool = True, expiration_time: Optional[datetime] = None) -> UserToken: """ Create and save a UserToken. :param user: The User object to bind the token to :param note: An optional field to store additional information about a token :param enabled: A boolean to indicate whether a token can be considered eligible for authentication :param expiration_time: An optional argument to determine when the token becomes invalid as a means of authentication. Defaults to None, which means no expiration :return: """ token = generate_token() user_token = UserToken( user_id=user.id, token=token.__str__(), note=note, enabled=enabled, creation_time=datetime.now(), expiration_time=expiration_time, version=0) db.session.add(user_token) db.session.commit() return user_token def delete(user_token: UserToken) -> bool: """ Delete a user_token. :param user_token: :return: """ existing_user_token = db.session.delete(user_token) if existing_user_token is None: db.session.commit() return True return False def find_by_user_and_token(user: User, token: str) -> Optional[UserToken]: """ Lookup a user_token by user and token string. :param user: :param token: :return: """ return UserToken.query.filter_by(user_id=user.id, token=token).first()