57 lines
1.7 KiB
Python
57 lines
1.7 KiB
Python
from sqlalchemy.orm.attributes import flag_modified
|
|
|
|
from database import db
|
|
from models import User, Organization
|
|
from utils import encode_public_key
|
|
|
|
|
|
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: encode_public_key(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 |