Initial commit: Role-based data visualisation platform for DMH hospital admissions (Phases 1-3)
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
from typing import Optional
|
||||
from sqlalchemy.orm import Session
|
||||
from app.models.user import User
|
||||
from app.core.security import verify_password, create_access_token
|
||||
from app.core.exceptions import AuthException, ForbiddenException
|
||||
from app.schemas.auth import TokenResponse, UserSummary
|
||||
from app.config import settings
|
||||
|
||||
|
||||
def authenticate_user(db: Session, username_or_email: str, password: str) -> Optional[User]:
|
||||
"""Finds user by username or email and verifies argon2 password hash."""
|
||||
user = db.query(User).filter(
|
||||
(User.username == username_or_email) | (User.email == username_or_email)
|
||||
).first()
|
||||
|
||||
if not user:
|
||||
return None
|
||||
if not verify_password(password, user.hashed_password):
|
||||
return None
|
||||
return user
|
||||
|
||||
|
||||
def login_user(db: Session, username_or_email: str, password: str) -> TokenResponse:
|
||||
"""Authenticates credentials and generates signed JWT token."""
|
||||
user = authenticate_user(db, username_or_email, password)
|
||||
if not user:
|
||||
raise AuthException("Incorrect username or password")
|
||||
|
||||
if not user.is_active:
|
||||
raise ForbiddenException("User account is inactive. Please contact your administrator.")
|
||||
|
||||
token = create_access_token(
|
||||
data={
|
||||
"sub": str(user.id),
|
||||
"username": user.username,
|
||||
"role": user.role,
|
||||
}
|
||||
)
|
||||
|
||||
return TokenResponse(
|
||||
access_token=token,
|
||||
token_type="Bearer",
|
||||
expires_in=settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60,
|
||||
user=UserSummary.model_validate(user)
|
||||
)
|
||||
@@ -0,0 +1,255 @@
|
||||
from datetime import datetime
|
||||
from typing import List, Dict, Any, Optional
|
||||
from sqlalchemy import (
|
||||
Table, MetaData, select, func, and_, or_, text, Column
|
||||
)
|
||||
from sqlalchemy.orm import Session
|
||||
from app.models.user import User
|
||||
from app.models.dataset import Dataset, DatasetColumn
|
||||
from app.schemas.chart import ChartSpec, ChartResult, ChartFilter
|
||||
from app.services.permission_service import get_effective_permissions
|
||||
from app.core.exceptions import NotFoundException, ForbiddenException, ValidationException
|
||||
|
||||
|
||||
def get_column_expression(table: Table, col_name: str, time_bucket: Optional[str] = None, dialect_name: str = "sqlite") -> Any:
|
||||
"""Returns a safe SQLAlchemy Core column expression with optional time bucketing."""
|
||||
if col_name not in table.c:
|
||||
raise ValidationException(f"Column '{col_name}' does not exist on table")
|
||||
|
||||
col = table.c[col_name]
|
||||
if time_bucket:
|
||||
if dialect_name == "postgresql":
|
||||
if time_bucket == "month":
|
||||
return func.to_char(col, "YYYY-MM").label("time_bucket")
|
||||
elif time_bucket == "day":
|
||||
return func.to_char(col, "YYYY-MM-DD").label("time_bucket")
|
||||
elif time_bucket == "year":
|
||||
return func.to_char(col, "YYYY").label("time_bucket")
|
||||
else:
|
||||
# SQLite fallback
|
||||
if time_bucket == "month":
|
||||
return func.strftime("%Y-%m", col).label("time_bucket")
|
||||
elif time_bucket == "day":
|
||||
return func.strftime("%Y-%m-%d", col).label("time_bucket")
|
||||
elif time_bucket == "year":
|
||||
return func.strftime("%Y", col).label("time_bucket")
|
||||
|
||||
return col
|
||||
|
||||
|
||||
def build_filter_clause(table: Table, filt: ChartFilter) -> Any:
|
||||
"""Builds a parameterized filter condition using SQLAlchemy Core whitelisted columns."""
|
||||
if filt.column not in table.c:
|
||||
raise ValidationException(f"Filter column '{filt.column}' is not a valid dataset column")
|
||||
|
||||
col = table.c[filt.column]
|
||||
op = filt.operator.lower()
|
||||
val = filt.value
|
||||
|
||||
if op == "eq":
|
||||
return col == val
|
||||
elif op == "ne":
|
||||
return col != val
|
||||
elif op == "gt":
|
||||
return col > val
|
||||
elif op == "gte":
|
||||
return col >= val
|
||||
elif op == "lt":
|
||||
return col < val
|
||||
elif op == "lte":
|
||||
return col <= val
|
||||
elif op == "in":
|
||||
if isinstance(val, list):
|
||||
return col.in_(val)
|
||||
else:
|
||||
return col.in_([v.strip() for v in str(val).split(",") if v.strip()])
|
||||
elif op == "between" and isinstance(val, list) and len(val) == 2:
|
||||
return and_(col >= val[0], col <= val[1])
|
||||
else:
|
||||
return col == val
|
||||
|
||||
|
||||
def execute_chart_query(
|
||||
db: Session,
|
||||
user: User,
|
||||
spec: ChartSpec,
|
||||
preview_user_id: Optional[int] = None,
|
||||
preview_role: Optional[str] = None
|
||||
) -> ChartResult:
|
||||
"""
|
||||
Validates permissions, whitelists columns, injects row rules,
|
||||
and executes an aggregated query using SQLAlchemy Core with bound parameters.
|
||||
"""
|
||||
# 1. Dataset verification
|
||||
dataset = db.query(Dataset).filter(Dataset.id == spec.dataset_id).first()
|
||||
if not dataset:
|
||||
raise NotFoundException(f"Dataset with ID {spec.dataset_id} not found")
|
||||
|
||||
# 2. Permission Evaluation
|
||||
eff_perms = get_effective_permissions(
|
||||
db=db,
|
||||
user=user,
|
||||
dataset_id=spec.dataset_id,
|
||||
preview_user_id=preview_user_id,
|
||||
preview_role=preview_role
|
||||
)
|
||||
|
||||
if not eff_perms.can_view:
|
||||
raise ForbiddenException("Access denied: You do not have permission to view this dataset")
|
||||
|
||||
# 3. Whitelist column checks
|
||||
allowed_cols = set(eff_perms.allowed_columns)
|
||||
if spec.dimension and spec.dimension not in allowed_cols:
|
||||
raise ForbiddenException(f"Access to dimension column '{spec.dimension}' is restricted")
|
||||
|
||||
if spec.measure and spec.measure != "*" and spec.measure not in allowed_cols:
|
||||
raise ForbiddenException(f"Access to measure column '{spec.measure}' is restricted")
|
||||
|
||||
if spec.secondary_dimension and spec.secondary_dimension not in allowed_cols:
|
||||
raise ForbiddenException(f"Access to secondary dimension '{spec.secondary_dimension}' is restricted")
|
||||
|
||||
for f in spec.filters:
|
||||
if f.column not in allowed_cols:
|
||||
raise ForbiddenException(f"Filtering on restricted column '{f.column}' is forbidden")
|
||||
|
||||
# 4. Reflect dynamic table
|
||||
bind = db.get_bind()
|
||||
dialect_name = bind.dialect.name
|
||||
meta = MetaData()
|
||||
table = Table(dataset.table_name, meta, autoload_with=bind)
|
||||
|
||||
# 5. Build WHERE conditions (Row rules + User filters)
|
||||
where_conditions = []
|
||||
|
||||
# Inject enforced row rules (AND intersection)
|
||||
for rule in eff_perms.row_rules:
|
||||
if rule.column_name in table.c:
|
||||
rule_filt = ChartFilter(
|
||||
column=rule.column_name,
|
||||
operator=rule.operator,
|
||||
value=rule.rule_value
|
||||
)
|
||||
where_conditions.append(build_filter_clause(table, rule_filt))
|
||||
|
||||
# Inject client filters
|
||||
for f in spec.filters:
|
||||
where_conditions.append(build_filter_clause(table, f))
|
||||
|
||||
where_clause = and_(*where_conditions) if where_conditions else None
|
||||
|
||||
# 6. Aggregation function
|
||||
agg_op = spec.aggregation.lower()
|
||||
if agg_op == "sum" and spec.measure and spec.measure != "*":
|
||||
agg_metric = func.sum(table.c[spec.measure]).label("metric_value")
|
||||
elif agg_op == "avg" and spec.measure and spec.measure != "*":
|
||||
agg_metric = func.avg(table.c[spec.measure]).label("metric_value")
|
||||
elif agg_op == "min" and spec.measure and spec.measure != "*":
|
||||
agg_metric = func.min(table.c[spec.measure]).label("metric_value")
|
||||
elif agg_op == "max" and spec.measure and spec.measure != "*":
|
||||
agg_metric = func.max(table.c[spec.measure]).label("metric_value")
|
||||
else:
|
||||
agg_metric = func.count().label("metric_value")
|
||||
|
||||
# 7. Chart-specific query building
|
||||
if spec.chart_type == "kpi":
|
||||
# Total metric query
|
||||
q = select(agg_metric).select_from(table)
|
||||
if where_clause is not None:
|
||||
q = q.where(where_clause)
|
||||
scalar_val = db.execute(q).scalar() or 0
|
||||
formatted_val = round(float(scalar_val), 1) if isinstance(scalar_val, float) else scalar_val
|
||||
return ChartResult(
|
||||
chart_type="kpi",
|
||||
title=spec.dimension or "Total",
|
||||
kpi_value=formatted_val,
|
||||
kpi_subtext=f"Aggregated {agg_op.upper()} on {dataset.name}",
|
||||
total_records=int(scalar_val) if isinstance(scalar_val, (int, float)) else 0,
|
||||
applied_rules_count=len(eff_perms.row_rules)
|
||||
)
|
||||
|
||||
# Dimensional Query
|
||||
dim_expr = get_column_expression(table, spec.dimension, spec.time_bucket, dialect_name)
|
||||
select_items = [dim_expr.label("dim_label"), agg_metric]
|
||||
group_items = [dim_expr]
|
||||
|
||||
if spec.secondary_dimension:
|
||||
sec_dim = table.c[spec.secondary_dimension].label("sec_dim_label")
|
||||
select_items.append(sec_dim)
|
||||
group_items.append(sec_dim)
|
||||
|
||||
query = select(*select_items).group_by(*group_items)
|
||||
if where_clause is not None:
|
||||
query = query.where(where_clause)
|
||||
|
||||
# Ordering
|
||||
if spec.order == "asc":
|
||||
query = query.order_by(agg_metric.asc())
|
||||
else:
|
||||
query = query.order_by(agg_metric.desc())
|
||||
|
||||
if spec.limit:
|
||||
query = query.limit(spec.limit)
|
||||
|
||||
rows = db.execute(query).fetchall()
|
||||
|
||||
# 8. Shape Data for ECharts
|
||||
categories: List[str] = []
|
||||
series_data: List[Dict[str, Any]] = []
|
||||
raw_aggregated: List[Dict[str, Any]] = []
|
||||
total_recs = 0
|
||||
|
||||
if not spec.secondary_dimension:
|
||||
values = []
|
||||
for r in rows:
|
||||
label = str(r[0]) if r[0] is not None else "(Blank)"
|
||||
val = round(float(r[1]), 2) if isinstance(r[1], float) else (r[1] or 0)
|
||||
categories.append(label)
|
||||
values.append(val)
|
||||
raw_aggregated.append({"name": label, "value": val})
|
||||
total_recs += (val if isinstance(val, int) else 1)
|
||||
|
||||
series_data.append({
|
||||
"name": spec.dimension or "Count",
|
||||
"type": "pie" if spec.chart_type in ("pie", "donut") else ("line" if spec.chart_type in ("line", "area") else "bar"),
|
||||
"data": values
|
||||
})
|
||||
else:
|
||||
# Grouped / Stacked query
|
||||
distinct_categories = []
|
||||
distinct_sec = []
|
||||
matrix: Dict[str, Dict[str, Any]] = {}
|
||||
|
||||
for r in rows:
|
||||
dim_lbl = str(r[0]) if r[0] is not None else "(Blank)"
|
||||
sec_lbl = str(r[2]) if r[2] is not None else "(Blank)"
|
||||
val = round(float(r[1]), 2) if isinstance(r[1], float) else (r[1] or 0)
|
||||
|
||||
if dim_lbl not in distinct_categories:
|
||||
distinct_categories.append(dim_lbl)
|
||||
if sec_lbl not in distinct_sec:
|
||||
distinct_sec.append(sec_lbl)
|
||||
|
||||
if sec_lbl not in matrix:
|
||||
matrix[sec_lbl] = {}
|
||||
matrix[sec_lbl][dim_lbl] = val
|
||||
raw_aggregated.append({"dimension": dim_lbl, "secondary": sec_lbl, "value": val})
|
||||
|
||||
categories = distinct_categories
|
||||
for s in distinct_sec:
|
||||
s_data = [matrix.get(s, {}).get(cat, 0) for cat in categories]
|
||||
series_data.append({
|
||||
"name": s,
|
||||
"type": "bar",
|
||||
"stack": "total" if spec.chart_type == "stacked_bar" else None,
|
||||
"data": s_data
|
||||
})
|
||||
|
||||
return ChartResult(
|
||||
chart_type=spec.chart_type,
|
||||
title=f"{dataset.name} by {spec.dimension}",
|
||||
categories=categories,
|
||||
series=series_data,
|
||||
data=raw_aggregated,
|
||||
total_records=total_recs,
|
||||
applied_rules_count=len(eff_perms.row_rules)
|
||||
)
|
||||
@@ -0,0 +1,223 @@
|
||||
import csv
|
||||
import io
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import List, Dict, Any, Tuple
|
||||
from sqlalchemy import (
|
||||
Table, Column, Integer, String, DateTime, MetaData, select, func, inspect, text
|
||||
)
|
||||
from sqlalchemy.orm import Session
|
||||
from app.models.dataset import Dataset, DatasetColumn
|
||||
from app.core.exceptions import ConflictException, NotFoundException, ValidationException
|
||||
|
||||
|
||||
SENSITIVE_FIELD_NAMES = {"mrdnumber", "admittingdoctorname", "doctorname", "patientname"}
|
||||
IDENTIFIER_FIELD_NAMES = {"srno", "mrdnumber", "patientid", "id"}
|
||||
|
||||
|
||||
def clean_table_name(name: str) -> str:
|
||||
"""Generates a safe SQL table name."""
|
||||
clean = re.sub(r"[^a-zA-Z0-9_]", "_", name.lower()).strip("_")
|
||||
return f"ds_{clean}"
|
||||
|
||||
|
||||
def parse_datetime_value(val: str) -> Any:
|
||||
"""Parses DD-MM-YYYY HH:MM into a Python datetime object."""
|
||||
if not val or not val.strip():
|
||||
return None
|
||||
val = val.strip()
|
||||
# Primary format: DD-MM-YYYY HH:MM
|
||||
for fmt in ("%d-%m-%Y %H:%M", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d", "%d/%m/%Y %H:%M"):
|
||||
try:
|
||||
return datetime.strptime(val, fmt)
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def parse_int_value(val: str) -> Any:
|
||||
"""Parses integer or returns None."""
|
||||
if not val or not val.strip():
|
||||
return None
|
||||
try:
|
||||
return int(val.strip())
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def register_dataset_from_csv(
|
||||
db: Session,
|
||||
file_content: bytes,
|
||||
dataset_name: str,
|
||||
description: str = ""
|
||||
) -> Dataset:
|
||||
"""
|
||||
Ingests CSV data (specifically tuned for hospital admission data),
|
||||
creates a dedicated table via SQLAlchemy Core, inserts data in chunks,
|
||||
and registers dataset and column metadata.
|
||||
"""
|
||||
bind = db.get_bind()
|
||||
|
||||
# Decode CSV content
|
||||
text_data = file_content.decode("utf-8-sig", errors="replace")
|
||||
csv_reader = csv.DictReader(io.StringIO(text_data))
|
||||
fieldnames = csv_reader.fieldnames or []
|
||||
|
||||
if not fieldnames:
|
||||
raise ValidationException("CSV file contains no headers or columns")
|
||||
|
||||
table_name = clean_table_name(dataset_name)
|
||||
|
||||
# Check if dataset name already exists
|
||||
existing_ds = db.query(Dataset).filter(
|
||||
(Dataset.name == dataset_name) | (Dataset.table_name == table_name)
|
||||
).first()
|
||||
if existing_ds:
|
||||
db.delete(existing_ds)
|
||||
db.commit()
|
||||
|
||||
# Drop table if exists on this bind
|
||||
try:
|
||||
db.execute(text(f'DROP TABLE IF EXISTS "{table_name}"'))
|
||||
db.commit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Read rows and infer schema
|
||||
rows = list(csv_reader)
|
||||
total_rows = len(rows)
|
||||
|
||||
# Define columns using SQLAlchemy Core with fresh MetaData
|
||||
table_meta = MetaData()
|
||||
cols = []
|
||||
col_metadata = []
|
||||
|
||||
for f in fieldnames:
|
||||
col_lower = f.lower()
|
||||
is_sensitive = col_lower in SENSITIVE_FIELD_NAMES
|
||||
is_identifier = col_lower in IDENTIFIER_FIELD_NAMES
|
||||
|
||||
# Determine column data type
|
||||
if col_lower == "srno":
|
||||
data_type = "integer"
|
||||
sa_col = Column(f, Integer, primary_key=True)
|
||||
elif "date" in col_lower:
|
||||
data_type = "datetime"
|
||||
sa_col = Column(f, DateTime, nullable=True)
|
||||
elif col_lower == "age":
|
||||
data_type = "integer"
|
||||
sa_col = Column(f, Integer, nullable=True)
|
||||
else:
|
||||
data_type = "string"
|
||||
sa_col = Column(f, String(255), nullable=True)
|
||||
|
||||
cols.append(sa_col)
|
||||
col_metadata.append({
|
||||
"column_name": f,
|
||||
"display_name": f.replace("_", " ").title() if "_" in f else f,
|
||||
"data_type": data_type,
|
||||
"is_sensitive": is_sensitive,
|
||||
"is_identifier": is_identifier
|
||||
})
|
||||
|
||||
# Dynamically create table with SQLAlchemy Core
|
||||
dynamic_table = Table(table_name, table_meta, *cols, extend_existing=True)
|
||||
dynamic_table.create(bind=bind, checkfirst=True)
|
||||
|
||||
# Prepare batch records
|
||||
prepared_records = []
|
||||
for r in rows:
|
||||
row_dict = {}
|
||||
for f in fieldnames:
|
||||
col_lower = f.lower()
|
||||
val = r.get(f)
|
||||
if val is not None:
|
||||
val = val.strip()
|
||||
if val == "":
|
||||
val = None
|
||||
|
||||
if col_lower == "srno":
|
||||
row_dict[f] = parse_int_value(val)
|
||||
elif "date" in col_lower:
|
||||
row_dict[f] = parse_datetime_value(val)
|
||||
elif col_lower == "age":
|
||||
row_dict[f] = parse_int_value(val)
|
||||
else:
|
||||
row_dict[f] = val
|
||||
prepared_records.append(row_dict)
|
||||
|
||||
# Bulk insert in batches of 5000 using SQLAlchemy Core
|
||||
batch_size = 5000
|
||||
for i in range(0, len(prepared_records), batch_size):
|
||||
batch = prepared_records[i : i + batch_size]
|
||||
db.execute(dynamic_table.insert(), batch)
|
||||
db.commit()
|
||||
|
||||
# Save Dataset record
|
||||
dataset = Dataset(
|
||||
name=dataset_name,
|
||||
description=description,
|
||||
source_type="file",
|
||||
table_name=table_name,
|
||||
row_count=total_rows,
|
||||
column_count=len(fieldnames)
|
||||
)
|
||||
db.add(dataset)
|
||||
db.flush()
|
||||
|
||||
# Save DatasetColumn records
|
||||
for cm in col_metadata:
|
||||
db_col = DatasetColumn(
|
||||
dataset_id=dataset.id,
|
||||
column_name=cm["column_name"],
|
||||
display_name=cm["display_name"],
|
||||
data_type=cm["data_type"],
|
||||
is_sensitive=cm["is_sensitive"],
|
||||
is_identifier=cm["is_identifier"]
|
||||
)
|
||||
db.add(db_col)
|
||||
|
||||
db.commit()
|
||||
db.refresh(dataset)
|
||||
return dataset
|
||||
|
||||
|
||||
def get_all_datasets(db: Session) -> List[Dataset]:
|
||||
"""Returns all registered datasets with columns."""
|
||||
return db.query(Dataset).order_by(Dataset.created_at.desc()).all()
|
||||
|
||||
|
||||
def get_dataset_by_id(db: Session, dataset_id: int) -> Dataset:
|
||||
"""Gets dataset details or raises 404."""
|
||||
ds = db.query(Dataset).filter(Dataset.id == dataset_id).first()
|
||||
if not ds:
|
||||
raise NotFoundException(f"Dataset with ID {dataset_id} not found")
|
||||
return ds
|
||||
|
||||
|
||||
def update_column_metadata(
|
||||
db: Session,
|
||||
dataset_id: int,
|
||||
column_id: int,
|
||||
display_name: str = None,
|
||||
is_sensitive: bool = None,
|
||||
is_identifier: bool = None
|
||||
) -> DatasetColumn:
|
||||
"""Updates display name, sensitivity, and identifier flags for a column."""
|
||||
col = db.query(DatasetColumn).filter(
|
||||
DatasetColumn.id == column_id,
|
||||
DatasetColumn.dataset_id == dataset_id
|
||||
).first()
|
||||
if not col:
|
||||
raise NotFoundException(f"Column ID {column_id} for Dataset ID {dataset_id} not found")
|
||||
|
||||
if display_name is not None:
|
||||
col.display_name = display_name
|
||||
if is_sensitive is not None:
|
||||
col.is_sensitive = is_sensitive
|
||||
if is_identifier is not None:
|
||||
col.is_identifier = is_identifier
|
||||
|
||||
db.commit()
|
||||
db.refresh(col)
|
||||
return col
|
||||
@@ -0,0 +1,193 @@
|
||||
from typing import List, Optional, Set
|
||||
from sqlalchemy.orm import Session
|
||||
from app.models.user import User, UserRole
|
||||
from app.models.dataset import Dataset, DatasetColumn
|
||||
from app.models.permission import DatasetPermission, ColumnPermission, RowRule
|
||||
from app.schemas.permission import (
|
||||
DatasetPermissionCreate, EffectivePermissions, RowRuleResponse
|
||||
)
|
||||
from app.core.exceptions import NotFoundException, ValidationException
|
||||
|
||||
|
||||
def save_dataset_permission(db: Session, perm_in: DatasetPermissionCreate) -> DatasetPermission:
|
||||
"""Creates or updates permission rules for a user or role on a dataset."""
|
||||
dataset = db.query(Dataset).filter(Dataset.id == perm_in.dataset_id).first()
|
||||
if not dataset:
|
||||
raise NotFoundException(f"Dataset with ID {perm_in.dataset_id} not found")
|
||||
|
||||
if not perm_in.user_id and not perm_in.role:
|
||||
raise ValidationException("Either user_id or role must be specified")
|
||||
|
||||
# Find existing permission
|
||||
query = db.query(DatasetPermission).filter(DatasetPermission.dataset_id == perm_in.dataset_id)
|
||||
if perm_in.user_id:
|
||||
query = query.filter(DatasetPermission.user_id == perm_in.user_id)
|
||||
else:
|
||||
query = query.filter(DatasetPermission.role == perm_in.role)
|
||||
|
||||
existing = query.first()
|
||||
if existing:
|
||||
existing.can_view = perm_in.can_view
|
||||
existing.can_export = perm_in.can_export
|
||||
# Clear previous column permissions & row rules to replace
|
||||
db.query(ColumnPermission).filter(ColumnPermission.dataset_permission_id == existing.id).delete()
|
||||
db.query(RowRule).filter(RowRule.dataset_permission_id == existing.id).delete()
|
||||
perm_record = existing
|
||||
else:
|
||||
perm_record = DatasetPermission(
|
||||
dataset_id=perm_in.dataset_id,
|
||||
user_id=perm_in.user_id,
|
||||
role=perm_in.role,
|
||||
can_view=perm_in.can_view,
|
||||
can_export=perm_in.can_export,
|
||||
)
|
||||
db.add(perm_record)
|
||||
db.flush()
|
||||
|
||||
# Add hidden columns
|
||||
for col_id in perm_in.hidden_column_ids:
|
||||
col = db.query(DatasetColumn).filter(
|
||||
DatasetColumn.id == col_id,
|
||||
DatasetColumn.dataset_id == perm_in.dataset_id
|
||||
).first()
|
||||
if col:
|
||||
col_perm = ColumnPermission(
|
||||
dataset_permission_id=perm_record.id,
|
||||
column_id=col.id,
|
||||
is_hidden=True
|
||||
)
|
||||
db.add(col_perm)
|
||||
|
||||
# Add row rules
|
||||
for r in perm_in.row_rules:
|
||||
# Validate column name exists in dataset
|
||||
col_exists = db.query(DatasetColumn).filter(
|
||||
DatasetColumn.dataset_id == perm_in.dataset_id,
|
||||
DatasetColumn.column_name == r.column_name
|
||||
).first()
|
||||
if not col_exists:
|
||||
raise ValidationException(f"Column '{r.column_name}' does not exist in dataset")
|
||||
|
||||
row_rule = RowRule(
|
||||
dataset_permission_id=perm_record.id,
|
||||
column_name=r.column_name,
|
||||
operator=r.operator,
|
||||
rule_value=r.rule_value
|
||||
)
|
||||
db.add(row_rule)
|
||||
|
||||
db.commit()
|
||||
db.refresh(perm_record)
|
||||
return perm_record
|
||||
|
||||
|
||||
def get_effective_permissions(
|
||||
db: Session,
|
||||
user: User,
|
||||
dataset_id: int,
|
||||
preview_user_id: Optional[int] = None,
|
||||
preview_role: Optional[str] = None
|
||||
) -> EffectivePermissions:
|
||||
"""
|
||||
Computes effective dataset, column and row-level permissions for a user.
|
||||
If the requesting user is a Super Admin and provides preview_user_id or preview_role,
|
||||
permissions are evaluated for that target entity.
|
||||
"""
|
||||
# Resolve target user / role for preview
|
||||
target_role = user.role
|
||||
target_user_id = user.id
|
||||
|
||||
if user.is_super_admin():
|
||||
if preview_user_id:
|
||||
target_user = db.query(User).filter(User.id == preview_user_id).first()
|
||||
if target_user:
|
||||
target_user_id = target_user.id
|
||||
target_role = target_user.role
|
||||
elif preview_role:
|
||||
target_role = preview_role
|
||||
target_user_id = None
|
||||
else:
|
||||
# Unrestricted Super Admin
|
||||
all_cols = db.query(DatasetColumn).filter(DatasetColumn.dataset_id == dataset_id).all()
|
||||
return EffectivePermissions(
|
||||
dataset_id=dataset_id,
|
||||
can_view=True,
|
||||
can_export=True,
|
||||
allowed_columns=[c.column_name for c in all_cols],
|
||||
hidden_columns=[],
|
||||
row_rules=[]
|
||||
)
|
||||
|
||||
# Fetch all columns for this dataset
|
||||
all_columns = db.query(DatasetColumn).filter(DatasetColumn.dataset_id == dataset_id).all()
|
||||
col_dict = {c.id: c.column_name for c in all_columns}
|
||||
sensitive_cols = {c.column_name for c in all_columns if c.is_sensitive}
|
||||
|
||||
# Fetch permissions by user_id and by role
|
||||
perms: List[DatasetPermission] = []
|
||||
if target_user_id:
|
||||
user_perm = db.query(DatasetPermission).filter(
|
||||
DatasetPermission.dataset_id == dataset_id,
|
||||
DatasetPermission.user_id == target_user_id
|
||||
).first()
|
||||
if user_perm:
|
||||
perms.append(user_perm)
|
||||
|
||||
if target_role:
|
||||
role_perm = db.query(DatasetPermission).filter(
|
||||
DatasetPermission.dataset_id == dataset_id,
|
||||
DatasetPermission.role == target_role
|
||||
).first()
|
||||
if role_perm:
|
||||
perms.append(role_perm)
|
||||
|
||||
# If no permissions found, default to view=False
|
||||
if not perms:
|
||||
return EffectivePermissions(
|
||||
dataset_id=dataset_id,
|
||||
can_view=False,
|
||||
can_export=False,
|
||||
allowed_columns=[],
|
||||
hidden_columns=[c.column_name for c in all_columns],
|
||||
row_rules=[]
|
||||
)
|
||||
|
||||
# Intersection logic:
|
||||
# can_view is True if any granted permission allows view
|
||||
can_view = any(p.can_view for p in perms)
|
||||
can_export = any(p.can_export for p in perms)
|
||||
|
||||
# Hidden columns: combine all explicitly hidden column permissions + sensitive columns by default
|
||||
hidden_col_names: Set[str] = set()
|
||||
for p in perms:
|
||||
for cp in p.column_permissions:
|
||||
if cp.is_hidden and cp.column_id in col_dict:
|
||||
hidden_col_names.add(col_dict[cp.column_id])
|
||||
|
||||
# Add sensitive columns unless role is super_admin
|
||||
if target_role != UserRole.SUPER_ADMIN.value:
|
||||
hidden_col_names.update(sensitive_cols)
|
||||
|
||||
allowed_columns = [c.column_name for c in all_columns if c.column_name not in hidden_col_names]
|
||||
|
||||
# Combine row rules across all applicable permissions (AND intersection)
|
||||
combined_row_rules = []
|
||||
for p in perms:
|
||||
for r in p.row_rules:
|
||||
combined_row_rules.append(
|
||||
RowRuleResponse(
|
||||
id=r.id,
|
||||
column_name=r.column_name,
|
||||
operator=r.operator,
|
||||
rule_value=r.rule_value
|
||||
)
|
||||
)
|
||||
|
||||
return EffectivePermissions(
|
||||
dataset_id=dataset_id,
|
||||
can_view=can_view,
|
||||
can_export=can_export,
|
||||
allowed_columns=allowed_columns,
|
||||
hidden_columns=list(hidden_col_names),
|
||||
row_rules=combined_row_rules
|
||||
)
|
||||
@@ -0,0 +1,85 @@
|
||||
from typing import List, Optional
|
||||
from sqlalchemy.orm import Session
|
||||
from app.models.user import User, UserRole
|
||||
from app.schemas.user import UserCreate, UserUpdate
|
||||
from app.core.security import hash_password
|
||||
from app.core.exceptions import ConflictException, NotFoundException, ValidationException
|
||||
|
||||
|
||||
def get_users(db: Session, skip: int = 0, limit: int = 100) -> List[User]:
|
||||
"""Retrieves paginated list of users."""
|
||||
return db.query(User).offset(skip).limit(limit).all()
|
||||
|
||||
|
||||
def get_user_by_id(db: Session, user_id: int) -> User:
|
||||
"""Retrieves single user by primary key or raises 404."""
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise NotFoundException(f"User with ID {user_id} not found")
|
||||
return user
|
||||
|
||||
|
||||
def create_user(db: Session, user_in: UserCreate) -> User:
|
||||
"""Validates uniqueness and creates a new user."""
|
||||
# Check if username exists
|
||||
if db.query(User).filter(User.username == user_in.username).first():
|
||||
raise ConflictException(f"Username '{user_in.username}' already registered")
|
||||
|
||||
# Check if email exists
|
||||
if db.query(User).filter(User.email == user_in.email).first():
|
||||
raise ConflictException(f"Email '{user_in.email}' already registered")
|
||||
|
||||
# Validate role
|
||||
valid_roles = [r.value for r in UserRole]
|
||||
if user_in.role not in valid_roles:
|
||||
raise ValidationException(f"Invalid role '{user_in.role}'. Allowed: {', '.join(valid_roles)}")
|
||||
|
||||
db_user = User(
|
||||
username=user_in.username,
|
||||
email=user_in.email,
|
||||
hashed_password=hash_password(user_in.password),
|
||||
full_name=user_in.full_name,
|
||||
role=user_in.role,
|
||||
is_active=user_in.is_active
|
||||
)
|
||||
db.add(db_user)
|
||||
db.commit()
|
||||
db.refresh(db_user)
|
||||
return db_user
|
||||
|
||||
|
||||
def update_user(db: Session, user_id: int, user_in: UserUpdate) -> User:
|
||||
"""Updates user fields with validation."""
|
||||
user = get_user_by_id(db, user_id)
|
||||
|
||||
if user_in.email and user_in.email != user.email:
|
||||
if db.query(User).filter(User.email == user_in.email, User.id != user_id).first():
|
||||
raise ConflictException(f"Email '{user_in.email}' already in use by another user")
|
||||
user.email = user_in.email
|
||||
|
||||
if user_in.password:
|
||||
user.hashed_password = hash_password(user_in.password)
|
||||
|
||||
if user_in.full_name is not None:
|
||||
user.full_name = user_in.full_name
|
||||
|
||||
if user_in.role is not None:
|
||||
valid_roles = [r.value for r in UserRole]
|
||||
if user_in.role not in valid_roles:
|
||||
raise ValidationException(f"Invalid role '{user_in.role}'. Allowed: {', '.join(valid_roles)}")
|
||||
user.role = user_in.role
|
||||
|
||||
if user_in.is_active is not None:
|
||||
user.is_active = user_in.is_active
|
||||
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
return user
|
||||
|
||||
|
||||
def delete_user(db: Session, user_id: int) -> bool:
|
||||
"""Deletes a user record."""
|
||||
user = get_user_by_id(db, user_id)
|
||||
db.delete(user)
|
||||
db.commit()
|
||||
return True
|
||||
Reference in New Issue
Block a user