bbe7f49c86
Aegis CI / lint-and-test (push) Has been cancelled
Snyk Security Scan / Python vulnerabilities (backend) (push) Has been cancelled
Snyk Security Scan / npm vulnerabilities (frontend) (push) Has been cancelled
Snyk Security Scan / Docker image vulnerabilities (backend) (push) Has been cancelled
- A lead opening a test with a pending procedure suggestion awaiting
their review now gets a blocking popup (approve/reject only) instead
of discovering it later in a separate queue.
- Users can be granted more than one role via extra_roles; only one is
ever active at a time (no permission mixing) and a top-bar switcher
lets the user swap which one, taking effect immediately since role
is read fresh from the DB on every request.
- The password-setup/reset webhook now posts the agreed Power Automate
contract ({to, subject, body} with the platform's standard greeting
and signature template) and supports an admin-configured API key
sent as an x-api-key header.
203 lines
6.6 KiB
Python
203 lines
6.6 KiB
Python
"""User management service — framework-agnostic CRUD for users.
|
|
|
|
Uses domain exceptions from app.domain.errors. The router handles
|
|
HTTP concerns, auth, audit logging, and commit.
|
|
"""
|
|
|
|
# Enable future language features for compatibility
|
|
from __future__ import annotations
|
|
|
|
# Import uuid
|
|
import uuid
|
|
|
|
# Import secrets
|
|
import secrets
|
|
|
|
# Import Session from sqlalchemy.orm
|
|
from sqlalchemy.orm import Session
|
|
|
|
# Import hash_password from app.auth
|
|
from app.auth import hash_password
|
|
|
|
# Import from app.domain.errors
|
|
from app.domain.errors import (
|
|
BusinessRuleViolation,
|
|
DuplicateEntityError,
|
|
EntityNotFoundError,
|
|
)
|
|
|
|
# Import User from app.models.user
|
|
from app.models.user import User
|
|
|
|
# Assign VALID_ROLES = {"admin", "red_tech", "blue_tech", "red_lead", "blue_lead", "manager", "viewer"}
|
|
VALID_ROLES = {"admin", "red_tech", "blue_tech", "red_lead", "blue_lead", "manager", "viewer"}
|
|
|
|
|
|
# Define function list_users
|
|
def list_users(db: Session) -> list[User]:
|
|
"""Return a list of all users ordered by username."""
|
|
# Return db.query(User).order_by(User.username).all()
|
|
return db.query(User).order_by(User.username).all()
|
|
|
|
|
|
# Define function create_user
|
|
def create_user(
|
|
# Entry: db
|
|
db: Session,
|
|
*,
|
|
# Entry: username
|
|
username: str,
|
|
# Entry: email
|
|
email: str | None,
|
|
# Entry: password
|
|
password: str,
|
|
# Entry: role
|
|
role: str,
|
|
) -> User:
|
|
"""Create a new user.
|
|
|
|
Raises DuplicateEntityError if username already exists.
|
|
Raises BusinessRuleViolation if role is invalid.
|
|
Does not commit; the router handles that.
|
|
"""
|
|
# Assign existing = db.query(User).filter(User.username == username).first()
|
|
existing = db.query(User).filter(User.username == username).first()
|
|
# Check: existing
|
|
if existing:
|
|
# Raise DuplicateEntityError
|
|
raise DuplicateEntityError("User", "username", username)
|
|
|
|
# Check: role not in VALID_ROLES
|
|
if role not in VALID_ROLES:
|
|
# Raise BusinessRuleViolation
|
|
raise BusinessRuleViolation(
|
|
f"Invalid role '{role}'. Must be one of: {', '.join(sorted(VALID_ROLES))}"
|
|
)
|
|
|
|
# Assign user = User(
|
|
user = User(
|
|
# Keyword argument: username
|
|
username=username,
|
|
# Keyword argument: email
|
|
email=email,
|
|
# Keyword argument: hashed_password
|
|
hashed_password=hash_password(password),
|
|
# Keyword argument: role
|
|
role=role,
|
|
)
|
|
# Stage new record(s) for database insertion
|
|
db.add(user)
|
|
# Return user
|
|
return user
|
|
|
|
|
|
def create_user_without_password(db: Session, *, full_name: str, email: str, role: str) -> User:
|
|
"""Create a new user without a password — they set their own via an
|
|
admin-triggered, emailed one-time link (see password_setup_service).
|
|
|
|
``username`` is derived from ``email`` since it's still needed
|
|
internally as the login identifier, but it's never surfaced in the UI.
|
|
|
|
Raises DuplicateEntityError if a user with this email/username already
|
|
exists. Raises BusinessRuleViolation if role is invalid. Does not
|
|
commit; the router handles that.
|
|
"""
|
|
existing = db.query(User).filter(User.username == email).first()
|
|
if existing:
|
|
raise DuplicateEntityError("User", "email", email)
|
|
|
|
if role not in VALID_ROLES:
|
|
raise BusinessRuleViolation(
|
|
f"Invalid role '{role}'. Must be one of: {', '.join(sorted(VALID_ROLES))}"
|
|
)
|
|
|
|
user = User(
|
|
username=email,
|
|
email=email,
|
|
full_name=full_name,
|
|
# Unusable random password — the user can only ever get in via the
|
|
# emailed set-password link, never by guessing/being told a value.
|
|
hashed_password=hash_password(secrets.token_urlsafe(32)),
|
|
role=role,
|
|
must_change_password=True,
|
|
)
|
|
db.add(user)
|
|
return user
|
|
|
|
|
|
# Define function get_user_or_raise
|
|
def get_user_or_raise(db: Session, user_id: uuid.UUID) -> User:
|
|
"""Return a user by ID or raise EntityNotFoundError."""
|
|
# Assign user = db.query(User).filter(User.id == user_id).first()
|
|
user = db.query(User).filter(User.id == user_id).first()
|
|
# Check: user is None
|
|
if user is None:
|
|
# Raise EntityNotFoundError
|
|
raise EntityNotFoundError("User", str(user_id))
|
|
# Return user
|
|
return user
|
|
|
|
|
|
# Define function update_user
|
|
def update_user(db: Session, user_id: uuid.UUID, **fields: object) -> User:
|
|
"""Update one or more fields of an existing user.
|
|
|
|
Raises EntityNotFoundError if user does not exist.
|
|
Raises BusinessRuleViolation if role is invalid.
|
|
Handles 'password' by hashing and storing as 'hashed_password'.
|
|
Does not commit; the router handles that.
|
|
"""
|
|
# Assign user = get_user_or_raise(db, user_id)
|
|
user = get_user_or_raise(db, user_id)
|
|
# Assign update_data = dict(fields)
|
|
update_data = dict(fields)
|
|
|
|
# Check: "role" in update_data and update_data["role"] not in VALID_ROLES
|
|
if "role" in update_data and update_data["role"] not in VALID_ROLES:
|
|
# Raise BusinessRuleViolation
|
|
raise BusinessRuleViolation(
|
|
f"Invalid role '{update_data['role']}'. Must be one of: {', '.join(sorted(VALID_ROLES))}"
|
|
)
|
|
|
|
if update_data.get("extra_roles") is not None:
|
|
invalid = [r for r in update_data["extra_roles"] if r not in VALID_ROLES]
|
|
if invalid:
|
|
raise BusinessRuleViolation(
|
|
f"Invalid role(s) {', '.join(invalid)}. Must be one of: {', '.join(sorted(VALID_ROLES))}"
|
|
)
|
|
|
|
# Check: "password" in update_data
|
|
if "password" in update_data:
|
|
# Assign update_data["hashed_password"] = hash_password(str(update_data.pop("password")))
|
|
update_data["hashed_password"] = hash_password(str(update_data.pop("password")))
|
|
|
|
# Iterate over update_data.items()
|
|
for field, value in update_data.items():
|
|
# Call setattr()
|
|
setattr(user, field, value)
|
|
|
|
# Return user
|
|
return user
|
|
|
|
|
|
def switch_active_role(db: Session, user: User, new_role: str) -> User:
|
|
"""Swap *user*'s currently-active role with one from their extra_roles.
|
|
|
|
Roles never mix — the user acts under exactly one role at a time, this
|
|
just changes which one. Raises BusinessRuleViolation if new_role isn't
|
|
one this user has been granted. Does not commit; caller commits.
|
|
"""
|
|
available = {user.role, *(user.extra_roles or [])}
|
|
if new_role not in available:
|
|
raise BusinessRuleViolation(f"Role '{new_role}' is not available to this user")
|
|
|
|
if new_role == user.role:
|
|
return user
|
|
|
|
old_role = user.role
|
|
remaining = [r for r in (user.extra_roles or []) if r != new_role]
|
|
remaining.append(old_role)
|
|
user.role = new_role
|
|
user.extra_roles = remaining
|
|
return user
|