sio-2425/delivery1/server/services/users.py

53 lines
1.6 KiB
Python

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,
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_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