3v324v23 commited on
Commit
df90dd5
·
1 Parent(s): 01be209

Users added

Browse files
api_server.py CHANGED
@@ -1392,7 +1392,8 @@ def _extract_resource(path: str):
1392
 
1393
  async def _write_audit_log(
1394
  user_id, username, action, resource_type, resource_id,
1395
- http_method, endpoint, response_status, ip_address, user_agent, duration_ms
 
1396
  ):
1397
  """Write an audit log row asynchronously. Never raises — DB failures are silently swallowed."""
1398
  try:
@@ -1410,6 +1411,7 @@ async def _write_audit_log(
1410
  user_agent=user_agent,
1411
  duration_ms=duration_ms,
1412
  occurred_at=datetime.utcnow(),
 
1413
  )
1414
  db.add(log)
1415
  db.commit()
@@ -1601,6 +1603,29 @@ async def upload_statement(
1601
  statements[statement_id] = stmt
1602
 
1603
  logger.info(f"Uploaded statement {statement_id}: {merged_filename} ({len(pdf_paths)} files, {total_size} bytes)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1604
  return UploadInitResponse(statementId=statement_id)
1605
 
1606
 
@@ -2303,6 +2328,29 @@ async def classify_statement(statement_id: str, current_user: User = Depends(get
2303
  res = await run_statement_classification_task(statement_id)
2304
  if isinstance(res, dict) and "error" in res:
2305
  raise HTTPException(status_code=500, detail=res["error"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2306
  return res
2307
 
2308
 
@@ -3121,16 +3169,40 @@ async def export_statement(statement_id: str, payload: ExportRequest, request: R
3121
  raise HTTPException(status_code=404, detail="Statement not found")
3122
 
3123
  stmt = statements[statement_id]
3124
-
 
3125
  download_url = f"{request.base_url}api/v1/statements/{statement_id}/download?format={payload.format}"
3126
  auth_header = request.headers.get("authorization")
3127
  if auth_header and auth_header.lower().startswith("bearer "):
3128
  token = auth_header[7:]
3129
  download_url += f"&token={token}"
3130
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3131
  return ExportResponse(
3132
  downloadUrl=download_url,
3133
- fileName=f"{stmt.file_name.replace('.pdf', '')}.{payload.format}",
3134
  )
3135
 
3136
 
@@ -3898,11 +3970,12 @@ async def login(payload: LoginRequest, request: Request):
3898
  from sqlalchemy.orm import Session as SASession
3899
  from auth.database import SessionLocal as _SessionLocal
3900
  _db: SASession = _SessionLocal()
 
3901
  try:
3902
  user = _db.query(User).filter(User.username == payload.username).first()
3903
 
3904
  if user is None or not verify_password(payload.password, user.hashed_password):
3905
- # Log failed login
3906
  try:
3907
  log = AuditLog(
3908
  user_id=user.id if user else None,
@@ -3914,8 +3987,12 @@ async def login(payload: LoginRequest, request: Request):
3914
  response_status=401,
3915
  ip_address=request.client.host if request.client else None,
3916
  user_agent=request.headers.get("user-agent"),
3917
- occurred_at=datetime.utcnow(),
3918
  duration_ms=0,
 
 
 
 
3919
  )
3920
  _db.add(log)
3921
  _db.commit()
@@ -3924,7 +4001,7 @@ async def login(payload: LoginRequest, request: Request):
3924
  raise HTTPException(status_code=401, detail="Invalid username or password")
3925
 
3926
  # Update last login
3927
- user.last_login_at = datetime.utcnow()
3928
 
3929
  # Create JWT
3930
  token = create_access_token({"sub": user.username})
@@ -3937,17 +4014,18 @@ async def login(payload: LoginRequest, request: Request):
3937
  jti = payload_data.get("jti")
3938
  exp = datetime.utcfromtimestamp(payload_data["exp"])
3939
 
3940
- # Persist session
3941
  session = UserSession(
3942
  user_id=user.id,
3943
  token_jti=jti,
3944
  expires_at=exp,
 
3945
  ip_address=request.client.host if request.client else None,
3946
  user_agent=request.headers.get("user-agent"),
3947
  )
3948
  _db.add(session)
3949
 
3950
- # Audit log
3951
  log = AuditLog(
3952
  user_id=user.id,
3953
  username=user.username,
@@ -3958,8 +4036,15 @@ async def login(payload: LoginRequest, request: Request):
3958
  response_status=200,
3959
  ip_address=request.client.host if request.client else None,
3960
  user_agent=request.headers.get("user-agent"),
3961
- occurred_at=datetime.utcnow(),
3962
  duration_ms=0,
 
 
 
 
 
 
 
3963
  )
3964
  _db.add(log)
3965
  _db.commit()
@@ -3985,15 +4070,23 @@ async def logout(
3985
  from auth.database import SessionLocal as _SL
3986
  from auth.service import decode_token as _dt
3987
  _db = _SL()
 
3988
  try:
3989
  auth_header = request.headers.get("Authorization", "")
3990
  token = auth_header.split(" ", 1)[1] if auth_header.startswith("Bearer ") else ""
3991
  payload_data = _dt(token)
3992
  jti = payload_data.get("jti")
 
 
 
3993
  if jti:
3994
  sess = _db.query(UserSession).filter(UserSession.token_jti == jti).first()
3995
  if sess:
3996
  sess.is_revoked = True
 
 
 
 
3997
  log = AuditLog(
3998
  user_id=current_user.id,
3999
  username=current_user.username,
@@ -4004,8 +4097,15 @@ async def logout(
4004
  response_status=200,
4005
  ip_address=request.client.host if request.client else None,
4006
  user_agent=request.headers.get("user-agent"),
4007
- occurred_at=datetime.utcnow(),
4008
  duration_ms=0,
 
 
 
 
 
 
 
4009
  )
4010
  _db.add(log)
4011
  _db.commit()
@@ -4070,6 +4170,7 @@ async def seed_users(
4070
  @app.get("/api/v1/admin/audit-logs")
4071
  async def get_audit_logs(
4072
  user_id: Optional[str] = None,
 
4073
  action: Optional[str] = None,
4074
  from_date: Optional[str] = None,
4075
  to_date: Optional[str] = None,
@@ -4087,6 +4188,8 @@ async def get_audit_logs(
4087
  q = _db.query(AuditLog)
4088
  if user_id:
4089
  q = q.filter(AuditLog.user_id == user_id)
 
 
4090
  if action:
4091
  q = q.filter(AuditLog.action == action)
4092
  if from_date:
@@ -4110,6 +4213,8 @@ async def get_audit_logs(
4110
  "response_status": log.response_status,
4111
  "ip_address": log.ip_address,
4112
  "duration_ms": log.duration_ms,
 
 
4113
  "occurred_at": log.occurred_at.isoformat() if log.occurred_at else None,
4114
  }
4115
  for log in logs
@@ -4118,6 +4223,421 @@ async def get_audit_logs(
4118
  finally:
4119
  _db.close()
4120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4121
  # ═══════════════════════════════════════════════════════════════════════════════
4122
  # PASTE THIS BLOCK into api_server.py ─ after the existing admin audit-log
4123
  # endpoint (around line 2700).
 
1392
 
1393
  async def _write_audit_log(
1394
  user_id, username, action, resource_type, resource_id,
1395
+ http_method, endpoint, response_status, ip_address, user_agent, duration_ms,
1396
+ extra_data: Optional[str] = None,
1397
  ):
1398
  """Write an audit log row asynchronously. Never raises — DB failures are silently swallowed."""
1399
  try:
 
1411
  user_agent=user_agent,
1412
  duration_ms=duration_ms,
1413
  occurred_at=datetime.utcnow(),
1414
+ extra_data=extra_data,
1415
  )
1416
  db.add(log)
1417
  db.commit()
 
1603
  statements[statement_id] = stmt
1604
 
1605
  logger.info(f"Uploaded statement {statement_id}: {merged_filename} ({len(pdf_paths)} files, {total_size} bytes)")
1606
+
1607
+ # UAT audit — write enriched upload log
1608
+ asyncio.create_task(_write_audit_log(
1609
+ user_id=current_user.id,
1610
+ username=current_user.username,
1611
+ action="upload_statement",
1612
+ resource_type="statement",
1613
+ resource_id=statement_id,
1614
+ http_method="POST",
1615
+ endpoint="/api/v1/statements/upload",
1616
+ response_status=200,
1617
+ ip_address=None,
1618
+ user_agent=None,
1619
+ duration_ms=0,
1620
+ extra_data=json.dumps({
1621
+ "statement_id": statement_id,
1622
+ "file_names": file_names,
1623
+ "file_count": len(pdf_paths),
1624
+ "total_bytes": total_size,
1625
+ "total_kb": round(total_size / 1024, 1),
1626
+ }),
1627
+ ))
1628
+
1629
  return UploadInitResponse(statementId=statement_id)
1630
 
1631
 
 
2328
  res = await run_statement_classification_task(statement_id)
2329
  if isinstance(res, dict) and "error" in res:
2330
  raise HTTPException(status_code=500, detail=res["error"])
2331
+
2332
+ # UAT audit — log classify action with transaction count
2333
+ stmt = statements.get(statement_id)
2334
+ tx_count = len(stmt.transactions) if stmt else 0
2335
+ file_name = stmt.file_name if stmt else None
2336
+ asyncio.create_task(_write_audit_log(
2337
+ user_id=current_user.id,
2338
+ username=current_user.username,
2339
+ action="classify_statement",
2340
+ resource_type="statement",
2341
+ resource_id=statement_id,
2342
+ http_method="POST",
2343
+ endpoint=f"/api/v1/statements/{statement_id}/classify",
2344
+ response_status=200,
2345
+ ip_address=None,
2346
+ user_agent=None,
2347
+ duration_ms=0,
2348
+ extra_data=json.dumps({
2349
+ "statement_id": statement_id,
2350
+ "file_name": file_name,
2351
+ "transaction_count": tx_count,
2352
+ }),
2353
+ ))
2354
  return res
2355
 
2356
 
 
3169
  raise HTTPException(status_code=404, detail="Statement not found")
3170
 
3171
  stmt = statements[statement_id]
3172
+ export_file_name = f"{stmt.file_name.replace('.pdf', '')}.{payload.format}"
3173
+
3174
  download_url = f"{request.base_url}api/v1/statements/{statement_id}/download?format={payload.format}"
3175
  auth_header = request.headers.get("authorization")
3176
  if auth_header and auth_header.lower().startswith("bearer "):
3177
  token = auth_header[7:]
3178
  download_url += f"&token={token}"
3179
+
3180
+ # UAT audit — log export action
3181
+ tx_count = len([t for t in (stmt.transactions or []) if t.get("status") != "deleted"])
3182
+ asyncio.create_task(_write_audit_log(
3183
+ user_id=current_user.id,
3184
+ username=current_user.username,
3185
+ action="export_statement",
3186
+ resource_type="statement",
3187
+ resource_id=statement_id,
3188
+ http_method="POST",
3189
+ endpoint=f"/api/v1/statements/{statement_id}/export",
3190
+ response_status=200,
3191
+ ip_address=request.client.host if request.client else None,
3192
+ user_agent=request.headers.get("user-agent"),
3193
+ duration_ms=0,
3194
+ extra_data=json.dumps({
3195
+ "statement_id": statement_id,
3196
+ "file_name": stmt.file_name,
3197
+ "export_file_name": export_file_name,
3198
+ "export_format": payload.format,
3199
+ "transaction_count": tx_count,
3200
+ }),
3201
+ ))
3202
+
3203
  return ExportResponse(
3204
  downloadUrl=download_url,
3205
+ fileName=export_file_name,
3206
  )
3207
 
3208
 
 
3970
  from sqlalchemy.orm import Session as SASession
3971
  from auth.database import SessionLocal as _SessionLocal
3972
  _db: SASession = _SessionLocal()
3973
+ login_time = datetime.utcnow()
3974
  try:
3975
  user = _db.query(User).filter(User.username == payload.username).first()
3976
 
3977
  if user is None or not verify_password(payload.password, user.hashed_password):
3978
+ # Log failed login attempt with contextual data
3979
  try:
3980
  log = AuditLog(
3981
  user_id=user.id if user else None,
 
3987
  response_status=401,
3988
  ip_address=request.client.host if request.client else None,
3989
  user_agent=request.headers.get("user-agent"),
3990
+ occurred_at=login_time,
3991
  duration_ms=0,
3992
+ extra_data=json.dumps({
3993
+ "reason": "invalid_credentials",
3994
+ "attempted_username": payload.username,
3995
+ }),
3996
  )
3997
  _db.add(log)
3998
  _db.commit()
 
4001
  raise HTTPException(status_code=401, detail="Invalid username or password")
4002
 
4003
  # Update last login
4004
+ user.last_login_at = login_time
4005
 
4006
  # Create JWT
4007
  token = create_access_token({"sub": user.username})
 
4014
  jti = payload_data.get("jti")
4015
  exp = datetime.utcfromtimestamp(payload_data["exp"])
4016
 
4017
+ # Persist session (store created_at explicitly for duration calc on logout)
4018
  session = UserSession(
4019
  user_id=user.id,
4020
  token_jti=jti,
4021
  expires_at=exp,
4022
+ created_at=login_time,
4023
  ip_address=request.client.host if request.client else None,
4024
  user_agent=request.headers.get("user-agent"),
4025
  )
4026
  _db.add(session)
4027
 
4028
+ # Audit log — store user profile info in extra_data for UAT tracking
4029
  log = AuditLog(
4030
  user_id=user.id,
4031
  username=user.username,
 
4036
  response_status=200,
4037
  ip_address=request.client.host if request.client else None,
4038
  user_agent=request.headers.get("user-agent"),
4039
+ occurred_at=login_time,
4040
  duration_ms=0,
4041
+ extra_data=json.dumps({
4042
+ "full_name": user.full_name,
4043
+ "role": user.role,
4044
+ "email": user.email,
4045
+ "token_jti": jti,
4046
+ "token_expires_at": exp.isoformat(),
4047
+ }),
4048
  )
4049
  _db.add(log)
4050
  _db.commit()
 
4070
  from auth.database import SessionLocal as _SL
4071
  from auth.service import decode_token as _dt
4072
  _db = _SL()
4073
+ logout_time = datetime.utcnow()
4074
  try:
4075
  auth_header = request.headers.get("Authorization", "")
4076
  token = auth_header.split(" ", 1)[1] if auth_header.startswith("Bearer ") else ""
4077
  payload_data = _dt(token)
4078
  jti = payload_data.get("jti")
4079
+
4080
+ # Compute session duration from session.created_at → now
4081
+ session_duration_seconds = None
4082
  if jti:
4083
  sess = _db.query(UserSession).filter(UserSession.token_jti == jti).first()
4084
  if sess:
4085
  sess.is_revoked = True
4086
+ if sess.created_at:
4087
+ delta = logout_time - sess.created_at
4088
+ session_duration_seconds = int(delta.total_seconds())
4089
+
4090
  log = AuditLog(
4091
  user_id=current_user.id,
4092
  username=current_user.username,
 
4097
  response_status=200,
4098
  ip_address=request.client.host if request.client else None,
4099
  user_agent=request.headers.get("user-agent"),
4100
+ occurred_at=logout_time,
4101
  duration_ms=0,
4102
+ session_duration_seconds=session_duration_seconds,
4103
+ extra_data=json.dumps({
4104
+ "session_duration_seconds": session_duration_seconds,
4105
+ "session_duration_minutes": round(session_duration_seconds / 60, 1) if session_duration_seconds else None,
4106
+ "full_name": current_user.full_name,
4107
+ "role": current_user.role,
4108
+ }),
4109
  )
4110
  _db.add(log)
4111
  _db.commit()
 
4170
  @app.get("/api/v1/admin/audit-logs")
4171
  async def get_audit_logs(
4172
  user_id: Optional[str] = None,
4173
+ username: Optional[str] = None,
4174
  action: Optional[str] = None,
4175
  from_date: Optional[str] = None,
4176
  to_date: Optional[str] = None,
 
4188
  q = _db.query(AuditLog)
4189
  if user_id:
4190
  q = q.filter(AuditLog.user_id == user_id)
4191
+ if username:
4192
+ q = q.filter(AuditLog.username == username)
4193
  if action:
4194
  q = q.filter(AuditLog.action == action)
4195
  if from_date:
 
4213
  "response_status": log.response_status,
4214
  "ip_address": log.ip_address,
4215
  "duration_ms": log.duration_ms,
4216
+ "session_duration_seconds": log.session_duration_seconds,
4217
+ "extra_data": log.extra_data,
4218
  "occurred_at": log.occurred_at.isoformat() if log.occurred_at else None,
4219
  }
4220
  for log in logs
 
4223
  finally:
4224
  _db.close()
4225
 
4226
+
4227
+ # ── UAT audit summary endpoint ────────────────────────────────────────────────
4228
+
4229
+ @app.get("/api/v1/admin/audit-logs/summary")
4230
+ async def get_audit_logs_summary(
4231
+ from_date: Optional[str] = None,
4232
+ to_date: Optional[str] = None,
4233
+ current_user: User = Depends(get_current_user),
4234
+ ):
4235
+ """
4236
+ Per-user UAT activity summary — admin only.
4237
+
4238
+ Returns a list of users with aggregated stats:
4239
+ - Total logins / login failures
4240
+ - Last login / last logout timestamps
4241
+ - Total session time (minutes)
4242
+ - Statements uploaded / classified / exported
4243
+ - Export format breakdown
4244
+ """
4245
+ if current_user.role != "admin":
4246
+ raise HTTPException(status_code=403, detail="Admin access required")
4247
+
4248
+ from auth.database import SessionLocal as _SL
4249
+ from sqlalchemy import func
4250
+ _db = _SL()
4251
+ try:
4252
+ q = _db.query(AuditLog)
4253
+ if from_date:
4254
+ q = q.filter(AuditLog.occurred_at >= datetime.fromisoformat(from_date))
4255
+ if to_date:
4256
+ q = q.filter(AuditLog.occurred_at <= datetime.fromisoformat(to_date))
4257
+
4258
+ logs = q.order_by(AuditLog.occurred_at.asc()).all()
4259
+
4260
+ # Aggregate per user
4261
+ from collections import defaultdict
4262
+ user_stats: Dict[str, Any] = defaultdict(lambda: {
4263
+ "user_id": None,
4264
+ "username": None,
4265
+ "full_name": None,
4266
+ "role": None,
4267
+ "total_logins": 0,
4268
+ "total_login_failures": 0,
4269
+ "last_login_at": None,
4270
+ "last_logout_at": None,
4271
+ "total_session_seconds": 0,
4272
+ "statements_uploaded": 0,
4273
+ "statements_classified": 0,
4274
+ "statements_exported": 0,
4275
+ "export_format_counts": {},
4276
+ "export_file_names": [],
4277
+ "upload_file_names": [],
4278
+ })
4279
+
4280
+ # Also fetch user profiles for display names
4281
+ all_users = {u.username: u for u in _db.query(User).all()}
4282
+
4283
+ for log in logs:
4284
+ uname = log.username or "anonymous"
4285
+ s = user_stats[uname]
4286
+ s["user_id"] = log.user_id
4287
+ s["username"] = uname
4288
+
4289
+ # Populate full_name and role from User table
4290
+ if uname in all_users:
4291
+ s["full_name"] = all_users[uname].full_name
4292
+ s["role"] = all_users[uname].role
4293
+
4294
+ # Try to pull from extra_data if user table lookup missed
4295
+ if log.extra_data:
4296
+ try:
4297
+ ed = json.loads(log.extra_data)
4298
+ if not s["full_name"]:
4299
+ s["full_name"] = ed.get("full_name")
4300
+ if not s["role"]:
4301
+ s["role"] = ed.get("role")
4302
+ except Exception:
4303
+ pass
4304
+
4305
+ if log.action == "login_success":
4306
+ s["total_logins"] += 1
4307
+ if log.occurred_at:
4308
+ ts = log.occurred_at.isoformat()
4309
+ if s["last_login_at"] is None or ts > s["last_login_at"]:
4310
+ s["last_login_at"] = ts
4311
+
4312
+ elif log.action == "login_failed":
4313
+ s["total_login_failures"] += 1
4314
+
4315
+ elif log.action == "logout":
4316
+ if log.occurred_at:
4317
+ ts = log.occurred_at.isoformat()
4318
+ if s["last_logout_at"] is None or ts > s["last_logout_at"]:
4319
+ s["last_logout_at"] = ts
4320
+ if log.session_duration_seconds:
4321
+ s["total_session_seconds"] += log.session_duration_seconds
4322
+
4323
+ elif log.action == "upload_statement":
4324
+ s["statements_uploaded"] += 1
4325
+ if log.extra_data:
4326
+ try:
4327
+ ed = json.loads(log.extra_data)
4328
+ names = ed.get("file_names", [])
4329
+ s["upload_file_names"].extend(names)
4330
+ except Exception:
4331
+ pass
4332
+
4333
+ elif log.action == "classify_statement":
4334
+ s["statements_classified"] += 1
4335
+
4336
+ elif log.action == "export_statement":
4337
+ s["statements_exported"] += 1
4338
+ if log.extra_data:
4339
+ try:
4340
+ ed = json.loads(log.extra_data)
4341
+ fmt = ed.get("export_format", "unknown")
4342
+ s["export_format_counts"][fmt] = s["export_format_counts"].get(fmt, 0) + 1
4343
+ fname = ed.get("export_file_name")
4344
+ if fname:
4345
+ s["export_file_names"].append(fname)
4346
+ except Exception:
4347
+ pass
4348
+
4349
+ result = []
4350
+ for uname, s in user_stats.items():
4351
+ result.append({
4352
+ "user_id": s["user_id"],
4353
+ "username": s["username"],
4354
+ "full_name": s["full_name"],
4355
+ "role": s["role"],
4356
+ "total_logins": s["total_logins"],
4357
+ "total_login_failures": s["total_login_failures"],
4358
+ "last_login_at": s["last_login_at"],
4359
+ "last_logout_at": s["last_logout_at"],
4360
+ "total_session_minutes": round(s["total_session_seconds"] / 60, 1),
4361
+ "statements_uploaded": s["statements_uploaded"],
4362
+ "statements_classified": s["statements_classified"],
4363
+ "statements_exported": s["statements_exported"],
4364
+ "export_format_counts": s["export_format_counts"],
4365
+ "upload_file_names": s["upload_file_names"],
4366
+ "export_file_names": s["export_file_names"],
4367
+ })
4368
+
4369
+ # Sort by total_logins desc
4370
+ result.sort(key=lambda x: x["total_logins"], reverse=True)
4371
+ return {"summary": result, "from_date": from_date, "to_date": to_date}
4372
+ finally:
4373
+ _db.close()
4374
+
4375
+
4376
+ # ── UAT audit XLSX export endpoint ───────────────────────────────────────────
4377
+
4378
+ @app.get("/api/v1/admin/audit-logs/export")
4379
+ async def export_audit_logs_xlsx(
4380
+ from_date: Optional[str] = None,
4381
+ to_date: Optional[str] = None,
4382
+ username: Optional[str] = None,
4383
+ action: Optional[str] = None,
4384
+ current_user: User = Depends(get_current_user),
4385
+ ):
4386
+ """
4387
+ Download full audit log as XLSX — admin only.
4388
+
4389
+ Sheet 1 — Detailed Logs: all matching rows with extra_data decoded inline.
4390
+ Sheet 2 — User Summary: aggregated per-user stats.
4391
+
4392
+ Supports query params: from_date, to_date, username, action.
4393
+ """
4394
+ if current_user.role != "admin":
4395
+ raise HTTPException(status_code=403, detail="Admin access required")
4396
+
4397
+ from auth.database import SessionLocal as _SL
4398
+ _db = _SL()
4399
+ try:
4400
+ q = _db.query(AuditLog)
4401
+ if from_date:
4402
+ q = q.filter(AuditLog.occurred_at >= datetime.fromisoformat(from_date))
4403
+ if to_date:
4404
+ q = q.filter(AuditLog.occurred_at <= datetime.fromisoformat(to_date))
4405
+ if username:
4406
+ q = q.filter(AuditLog.username == username)
4407
+ if action:
4408
+ q = q.filter(AuditLog.action == action)
4409
+
4410
+ logs = q.order_by(AuditLog.occurred_at.desc()).all()
4411
+
4412
+ # ── Build XLSX workbook ────────────────────────────────────────────────
4413
+ wb = openpyxl.Workbook()
4414
+
4415
+ # ── Styles ────────────────────────────────────────────────────────────
4416
+ from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
4417
+ header_font = Font(bold=True, color="FFFFFF", size=11)
4418
+ header_fill = PatternFill(start_color="1F4E79", end_color="1F4E79", fill_type="solid")
4419
+ sub_header_fill = PatternFill(start_color="2E75B6", end_color="2E75B6", fill_type="solid")
4420
+ alt_fill = PatternFill(start_color="EBF3FB", end_color="EBF3FB", fill_type="solid")
4421
+ center_align = Alignment(horizontal="center", vertical="top", wrap_text=True)
4422
+ left_align = Alignment(horizontal="left", vertical="top", wrap_text=True)
4423
+ thin_border = Border(
4424
+ left=Side(style="thin", color="BFBFBF"),
4425
+ right=Side(style="thin", color="BFBFBF"),
4426
+ top=Side(style="thin", color="BFBFBF"),
4427
+ bottom=Side(style="thin", color="BFBFBF"),
4428
+ )
4429
+
4430
+ def style_header_row(ws, row_num, num_cols):
4431
+ for c in range(1, num_cols + 1):
4432
+ cell = ws.cell(row=row_num, column=c)
4433
+ cell.font = header_font
4434
+ cell.fill = header_fill
4435
+ cell.alignment = center_align
4436
+ cell.border = thin_border
4437
+
4438
+ def style_data_row(ws, row_num, num_cols, alternate=False):
4439
+ for c in range(1, num_cols + 1):
4440
+ cell = ws.cell(row=row_num, column=c)
4441
+ if alternate:
4442
+ cell.fill = alt_fill
4443
+ cell.alignment = left_align
4444
+ cell.border = thin_border
4445
+
4446
+ # ═════════════════════════════════════════════════════════════════════
4447
+ # SHEET 1 — Detailed Logs
4448
+ # ═════════════════════��═══════════════════════════════════════════════
4449
+ ws1 = wb.active
4450
+ ws1.title = "Detailed Logs"
4451
+
4452
+ detail_headers = [
4453
+ "#", "Timestamp (UTC)", "Username", "Action", "Resource Type",
4454
+ "Resource ID", "HTTP", "Endpoint", "Status", "IP Address",
4455
+ "Duration (ms)", "Session Duration (min)",
4456
+ # Decoded extra_data fields
4457
+ "File Name(s)", "File Count", "File Size (KB)",
4458
+ "Export Format", "Transaction Count",
4459
+ "Role", "Full Name", "Extra Data (raw)",
4460
+ ]
4461
+ ws1.append(detail_headers)
4462
+ style_header_row(ws1, 1, len(detail_headers))
4463
+ ws1.freeze_panes = "A2"
4464
+
4465
+ ACTION_LABELS = {
4466
+ "login_success": "Login Success",
4467
+ "login_failed": "Login Failed",
4468
+ "logout": "Logout",
4469
+ "upload_statement": "Upload Statement",
4470
+ "classify_statement": "Classify Statement",
4471
+ "export_statement": "Export Statement",
4472
+ "download_statement": "Download Statement",
4473
+ }
4474
+
4475
+ for i, log in enumerate(logs, start=1):
4476
+ ed: Dict[str, Any] = {}
4477
+ if log.extra_data:
4478
+ try:
4479
+ ed = json.loads(log.extra_data)
4480
+ except Exception:
4481
+ pass
4482
+
4483
+ file_names = ", ".join(ed.get("file_names", []) or []) or ed.get("file_name", "") or ""
4484
+ file_count = ed.get("file_count", "")
4485
+ file_kb = ed.get("total_kb", "")
4486
+ export_fmt = ed.get("export_format", "")
4487
+ tx_count = ed.get("transaction_count", "")
4488
+ role = ed.get("role", "")
4489
+ full_name = ed.get("full_name", "")
4490
+ sess_min = ""
4491
+ if log.session_duration_seconds is not None:
4492
+ sess_min = round(log.session_duration_seconds / 60, 1)
4493
+
4494
+ row = [
4495
+ i,
4496
+ log.occurred_at.strftime("%Y-%m-%d %H:%M:%S") if log.occurred_at else "",
4497
+ log.username or "",
4498
+ ACTION_LABELS.get(log.action, log.action or ""),
4499
+ log.resource_type or "",
4500
+ log.resource_id or "",
4501
+ log.http_method or "",
4502
+ log.endpoint or "",
4503
+ log.response_status or "",
4504
+ log.ip_address or "",
4505
+ log.duration_ms if log.duration_ms is not None else "",
4506
+ sess_min,
4507
+ file_names,
4508
+ file_count,
4509
+ file_kb,
4510
+ export_fmt,
4511
+ tx_count,
4512
+ role,
4513
+ full_name,
4514
+ log.extra_data or "",
4515
+ ]
4516
+ ws1.append(row)
4517
+ style_data_row(ws1, i + 1, len(detail_headers), alternate=(i % 2 == 0))
4518
+
4519
+ # Column widths for Sheet 1
4520
+ col_widths_1 = [5, 20, 16, 22, 16, 20, 7, 45, 8, 16, 14, 20, 35, 11, 13, 14, 18, 12, 22, 40]
4521
+ for col_i, w in enumerate(col_widths_1, start=1):
4522
+ ws1.column_dimensions[openpyxl.utils.get_column_letter(col_i)].width = w
4523
+
4524
+ # Auto-filter
4525
+ ws1.auto_filter.ref = ws1.dimensions
4526
+
4527
+ # ═════════════════════════════════════════════════════════════════════
4528
+ # SHEET 2 — User Summary
4529
+ # ═════════════════════════════════════════════════════════════════════
4530
+ ws2 = wb.create_sheet(title="User Summary")
4531
+
4532
+ summary_headers = [
4533
+ "Username", "Full Name", "Role",
4534
+ "Total Logins", "Failed Logins",
4535
+ "Last Login (UTC)", "Last Logout (UTC)",
4536
+ "Total Session Time (min)",
4537
+ "Statements Uploaded", "Statements Classified", "Statements Exported",
4538
+ "Export Formats", "Uploaded File Names", "Exported File Names",
4539
+ ]
4540
+ ws2.append(summary_headers)
4541
+ style_header_row(ws2, 1, len(summary_headers))
4542
+ ws2.freeze_panes = "A2"
4543
+
4544
+ # Re-aggregate from the already-fetched logs
4545
+ from collections import defaultdict
4546
+ sum_stats: Dict[str, Any] = defaultdict(lambda: {
4547
+ "full_name": None, "role": None,
4548
+ "logins": 0, "failures": 0,
4549
+ "last_login": None, "last_logout": None,
4550
+ "session_secs": 0,
4551
+ "uploads": 0, "classifies": 0, "exports": 0,
4552
+ "fmt_counts": {}, "upload_names": [], "export_names": [],
4553
+ })
4554
+ all_users_map = {u.username: u for u in _db.query(User).all()}
4555
+
4556
+ for log in logs:
4557
+ uname = log.username or "anonymous"
4558
+ s = sum_stats[uname]
4559
+ if uname in all_users_map:
4560
+ s["full_name"] = all_users_map[uname].full_name
4561
+ s["role"] = all_users_map[uname].role
4562
+ ed: Dict[str, Any] = {}
4563
+ if log.extra_data:
4564
+ try:
4565
+ ed = json.loads(log.extra_data)
4566
+ except Exception:
4567
+ pass
4568
+ if not s["full_name"] and ed.get("full_name"):
4569
+ s["full_name"] = ed["full_name"]
4570
+ if not s["role"] and ed.get("role"):
4571
+ s["role"] = ed["role"]
4572
+
4573
+ if log.action == "login_success":
4574
+ s["logins"] += 1
4575
+ ts = log.occurred_at.isoformat() if log.occurred_at else None
4576
+ if ts and (not s["last_login"] or ts > s["last_login"]):
4577
+ s["last_login"] = ts
4578
+ elif log.action == "login_failed":
4579
+ s["failures"] += 1
4580
+ elif log.action == "logout":
4581
+ ts = log.occurred_at.isoformat() if log.occurred_at else None
4582
+ if ts and (not s["last_logout"] or ts > s["last_logout"]):
4583
+ s["last_logout"] = ts
4584
+ if log.session_duration_seconds:
4585
+ s["session_secs"] += log.session_duration_seconds
4586
+ elif log.action == "upload_statement":
4587
+ s["uploads"] += 1
4588
+ s["upload_names"].extend(ed.get("file_names", []))
4589
+ elif log.action == "classify_statement":
4590
+ s["classifies"] += 1
4591
+ elif log.action == "export_statement":
4592
+ s["exports"] += 1
4593
+ fmt = ed.get("export_format", "unknown")
4594
+ s["fmt_counts"][fmt] = s["fmt_counts"].get(fmt, 0) + 1
4595
+ fname = ed.get("export_file_name")
4596
+ if fname:
4597
+ s["export_names"].append(fname)
4598
+
4599
+ for row_i, (uname, s) in enumerate(sum_stats.items(), start=1):
4600
+ fmt_str = ", ".join(f"{k}:{v}" for k, v in s["fmt_counts"].items()) if s["fmt_counts"] else ""
4601
+ row = [
4602
+ uname,
4603
+ s["full_name"] or "",
4604
+ s["role"] or "",
4605
+ s["logins"],
4606
+ s["failures"],
4607
+ s["last_login"] or "",
4608
+ s["last_logout"] or "",
4609
+ round(s["session_secs"] / 60, 1),
4610
+ s["uploads"],
4611
+ s["classifies"],
4612
+ s["exports"],
4613
+ fmt_str,
4614
+ "\n".join(s["upload_names"]),
4615
+ "\n".join(s["export_names"]),
4616
+ ]
4617
+ ws2.append(row)
4618
+ style_data_row(ws2, row_i + 1, len(summary_headers), alternate=(row_i % 2 == 0))
4619
+
4620
+ col_widths_2 = [18, 22, 12, 14, 14, 22, 22, 22, 20, 22, 20, 20, 50, 50]
4621
+ for col_i, w in enumerate(col_widths_2, start=1):
4622
+ ws2.column_dimensions[openpyxl.utils.get_column_letter(col_i)].width = w
4623
+ ws2.auto_filter.ref = ws2.dimensions
4624
+
4625
+ # ── Stream response ───────────────────────────────────────────────────
4626
+ buf = io.BytesIO()
4627
+ wb.save(buf)
4628
+ buf.seek(0)
4629
+
4630
+ date_tag = datetime.utcnow().strftime("%Y%m%d_%H%M")
4631
+ filename = f"UAT_AuditLog_{date_tag}.xlsx"
4632
+ headers = {"Content-Disposition": f'attachment; filename="{filename}"'}
4633
+ return StreamingResponse(
4634
+ buf,
4635
+ media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
4636
+ headers=headers,
4637
+ )
4638
+ finally:
4639
+ _db.close()
4640
+
4641
  # ═══════════════════════════════════════════════════════════════════════════════
4642
  # PASTE THIS BLOCK into api_server.py ─ after the existing admin audit-log
4643
  # endpoint (around line 2700).
auth/migrations.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ auth/migrations.py — One-time migration to add UAT audit enrichment columns.
3
+
4
+ Run once after deploying this change:
5
+ python auth/migrations.py
6
+
7
+ Safe to re-run — uses IF NOT EXISTS for PostgreSQL.
8
+ For SQLite (local dev), falls back to a try/except approach.
9
+ """
10
+
11
+ import os
12
+ import sys
13
+ from pathlib import Path
14
+
15
+ # Ensure project root is on path so dotenv and auth package resolve correctly
16
+ project_root = Path(__file__).resolve().parent.parent
17
+ sys.path.insert(0, str(project_root))
18
+
19
+ from dotenv import load_dotenv
20
+ load_dotenv()
21
+
22
+ from auth.database import engine
23
+
24
+
25
+ def run_migrations():
26
+ """Add extra_data and session_duration_seconds columns to audit_logs if not present."""
27
+ with engine.connect() as conn:
28
+ dialect = engine.dialect.name
29
+ print(f"[Migration] Connected to database (dialect: {dialect})")
30
+
31
+ if dialect == "postgresql":
32
+ # PostgreSQL supports IF NOT EXISTS
33
+ statements = [
34
+ "ALTER TABLE audit_logs ADD COLUMN IF NOT EXISTS extra_data TEXT;",
35
+ "ALTER TABLE audit_logs ADD COLUMN IF NOT EXISTS session_duration_seconds INTEGER;",
36
+ ]
37
+ for sql in statements:
38
+ try:
39
+ conn.execute(__import__("sqlalchemy").text(sql))
40
+ conn.commit()
41
+ print(f"[Migration] OK: {sql.strip()}")
42
+ except Exception as e:
43
+ print(f"[Migration] WARN (may already exist): {e}")
44
+
45
+ elif dialect == "sqlite":
46
+ # SQLite does not support IF NOT EXISTS on ALTER TABLE
47
+ for col_name, col_def in [
48
+ ("extra_data", "TEXT"),
49
+ ("session_duration_seconds", "INTEGER"),
50
+ ]:
51
+ try:
52
+ from sqlalchemy import text, inspect
53
+ inspector = inspect(engine)
54
+ existing = [c["name"] for c in inspector.get_columns("audit_logs")]
55
+ if col_name not in existing:
56
+ conn.execute(text(f"ALTER TABLE audit_logs ADD COLUMN {col_name} {col_def}"))
57
+ conn.commit()
58
+ print(f"[Migration] Added column: {col_name} ({col_def})")
59
+ else:
60
+ print(f"[Migration] Column already exists, skipping: {col_name}")
61
+ except Exception as e:
62
+ print(f"[Migration] WARN: {e}")
63
+
64
+ else:
65
+ print(f"[Migration] Unsupported dialect '{dialect}'. Please add columns manually:")
66
+ print(" ALTER TABLE audit_logs ADD COLUMN extra_data TEXT;")
67
+ print(" ALTER TABLE audit_logs ADD COLUMN session_duration_seconds INTEGER;")
68
+ return
69
+
70
+ print("[Migration] Done. All UAT audit columns are in place.")
71
+
72
+
73
+ if __name__ == "__main__":
74
+ run_migrations()
auth/models.py CHANGED
@@ -76,6 +76,9 @@ class AuditLog(Base):
76
  user_agent = Column(Text, nullable=True)
77
  occurred_at = Column(DateTime, nullable=False, default=datetime.utcnow, index=True)
78
  duration_ms = Column(Integer, nullable=True)
 
 
 
79
 
80
  user = relationship("User", back_populates="audit_logs")
81
 
 
76
  user_agent = Column(Text, nullable=True)
77
  occurred_at = Column(DateTime, nullable=False, default=datetime.utcnow, index=True)
78
  duration_ms = Column(Integer, nullable=True)
79
+ # ── UAT audit enrichments ─────────────────────────────────────────────────
80
+ extra_data = Column(Text, nullable=True) # JSON blob: file names, tx counts, export format …
81
+ session_duration_seconds = Column(Integer, nullable=True) # login→logout delta (set on logout)
82
 
83
  user = relationship("User", back_populates="audit_logs")
84
 
auth/seed_users.py CHANGED
@@ -1,11 +1,12 @@
1
  """
2
- One-time script to seed initial employee accounts.
3
 
4
  Usage:
5
  python auth/seed_users.py
6
 
7
- Run ONCE after filling in DATABASE_URL in .env.
8
- Tables will be auto-created if they don't exist yet.
 
9
  """
10
 
11
  import sys
@@ -19,55 +20,59 @@ load_dotenv()
19
 
20
  from auth.database import engine, Base, SessionLocal
21
  import auth.models # register models with Base so create_all sees them
22
- from auth.service import create_user
 
23
 
24
  Base.metadata.create_all(bind=engine)
25
 
26
  INITIAL_USERS = [
27
  {
28
- "username": "employee1",
29
- "password": "TempPass@123",
30
  "full_name": "Employee One",
31
  "email": "emp1@befree.com",
32
  "role": "tester",
33
  },
34
  {
35
- "username": "employee2",
36
- "password": "TempPass@123",
37
  "full_name": "Employee Two",
38
  "email": "emp2@befree.com",
39
  "role": "tester",
40
  },
41
  {
42
- "username": "employee3",
43
- "password": "TempPass@123",
44
  "full_name": "Employee Three",
45
  "email": "emp3@befree.com",
46
  "role": "tester",
47
- },
48
- {
49
- "username": "admin",
50
- "password": "AdminPass@456",
51
- "full_name": "BeFree Admin",
52
- "email": "admin@befree.com",
53
- "role": "admin",
54
- },
55
- {
56
- "username": "manager",
57
- "password": "ManagerPass@123",
58
- "full_name": "BeFree Manager",
59
- "email": "manager@befree.com",
60
- "role": "manager",
61
- },
62
  ]
63
 
64
- with SessionLocal() as db:
65
- for u in INITIAL_USERS:
 
66
  try:
67
- user = create_user(db, **u)
68
- print(f"OK Created: {user.username} ({user.role})")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  except Exception as e:
70
- print(f"SKIP Skipped: {u['username']} - {e}")
 
71
 
72
  print(
73
  "\nDone. Share credentials with employees and ask them to change passwords after first login."
 
1
  """
2
+ One-time script to seed/update initial employee accounts.
3
 
4
  Usage:
5
  python auth/seed_users.py
6
 
7
+ - Creates the user if the username AND email are new.
8
+ - Updates username + password if the email already exists (handles renames).
9
+ - Safe to re-run at any time.
10
  """
11
 
12
  import sys
 
20
 
21
  from auth.database import engine, Base, SessionLocal
22
  import auth.models # register models with Base so create_all sees them
23
+ from auth.models import User
24
+ from auth.service import create_user, hash_password
25
 
26
  Base.metadata.create_all(bind=engine)
27
 
28
  INITIAL_USERS = [
29
  {
30
+ "username": "Befree_employee1",
31
+ "password": "Emp1_Test@2026!",
32
  "full_name": "Employee One",
33
  "email": "emp1@befree.com",
34
  "role": "tester",
35
  },
36
  {
37
+ "username": "Befree_employee2",
38
+ "password": "Emp2_Secure#849",
39
  "full_name": "Employee Two",
40
  "email": "emp2@befree.com",
41
  "role": "tester",
42
  },
43
  {
44
+ "username": "Befree_employee3",
45
+ "password": "Emp3_Login$572",
46
  "full_name": "Employee Three",
47
  "email": "emp3@befree.com",
48
  "role": "tester",
49
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  ]
51
 
52
+ for u in INITIAL_USERS:
53
+ # Each user gets its own session so a failure on one doesn't cascade
54
+ with SessionLocal() as db:
55
  try:
56
+ # Check if a user with this email already exists
57
+ existing_by_email = db.query(User).filter(User.email == u["email"]).first()
58
+
59
+ if existing_by_email:
60
+ # Update username and password (handles the employee1 -> Befree_employee1 rename)
61
+ old_username = existing_by_email.username
62
+ existing_by_email.username = u["username"]
63
+ existing_by_email.hashed_password = hash_password(u["password"])
64
+ existing_by_email.full_name = u["full_name"]
65
+ existing_by_email.role = u["role"]
66
+ db.commit()
67
+ print(f"UPDATE Renamed: {old_username!r} -> {u['username']!r} ({u['role']})")
68
+ else:
69
+ # Brand new user
70
+ user = create_user(db, **u)
71
+ print(f"OK Created: {user.username} ({user.role})")
72
+
73
  except Exception as e:
74
+ db.rollback()
75
+ print(f"SKIP Failed: {u['username']} - {e}")
76
 
77
  print(
78
  "\nDone. Share credentials with employees and ask them to change passwords after first login."
bank-classifier/bank_classifier/engines/llm_engine.py CHANGED
@@ -176,7 +176,7 @@ def _build_system_prompt(valid_categories: list[str]) -> str:
176
  cats_str = "\n".join(f" - {c}" for c in valid_categories)
177
 
178
  debit_fallback = next(
179
- (c for c in valid_categories if "retail" in c.lower()), "General Retail"
180
  )
181
  credit_fallback = next(
182
  (c for c in valid_categories if "income" in c.lower()), "Other Income"
 
176
  cats_str = "\n".join(f" - {c}" for c in valid_categories)
177
 
178
  debit_fallback = next(
179
+ (c for c in valid_categories if "additional" in c.lower()), "Additional Expenses"
180
  )
181
  credit_fallback = next(
182
  (c for c in valid_categories if "income" in c.lower()), "Other Income"