from sqlalchemy.orm.attributes import flag_modified from database import db from models import User, Organization class UserService: @staticmethod def create_user(username: str, full_name: str, email: str, public_key: str, org: Organization = None) -> User: from services import OrganizationService user = User( username=username, full_name=full_name, email=email, roles={}, public_keys={org.id: public_key} if org else {}, orgs={org.id: { "name": org.name, "status": "active" }} if org else {} ) db.add(user) db.commit() db.refresh(user) if org: OrganizationService.add_user_to_organization(org, user) return user @staticmethod def get_user(user_id: int) -> User | None: return db.query(User).filter(User.id == user_id).first() @staticmethod def get_user_by_username(username: str) -> User | None: return db.query(User).filter(User.username == username).first() @staticmethod def add_org_to_user(user: User, org: Organization) -> User: orgs = user.orgs.copy() orgs[org.id] = { "name": org.name, "status": "active" } user.orgs = orgs db.commit() db.refresh(user) return user @staticmethod def add_role_to_user(user: User, org: Organization, role: str) -> User: roles = user.roles.copy() roles[org.id] = role user.roles = roles flag_modified(user, "roles") db.commit() db.refresh(user) roles = org.roles.copy() roles[role]["users"].append(user.id) org.roles = roles flag_modified(org, "roles") db.commit() db.refresh(org) return user @staticmethod def remove_role_from_user(user: User, org: Organization, role: str) -> User: roles = user.roles.copy() roles.pop(org.id) user.roles = roles flag_modified(user, "roles") db.commit() db.refresh(user) roles = org.roles.copy() roles[role]["users"].remove(user.id) org.roles = roles flag_modified(org, "roles") db.commit() db.refresh(org) return user @staticmethod def add_public_key_to_user(user: User, org: Organization, public_key: str) -> User: public_keys = user.public_keys.copy() public_keys[org.id] = public_key user.public_keys = public_keys db.commit() db.refresh(user) return user