|
1 | 1 | import re |
| 2 | +from datetime import datetime, timedelta |
2 | 3 |
|
3 | | -from fastapi import HTTPException, status |
| 4 | +from fastapi import Depends, HTTPException, status |
| 5 | +from fastapi.security import HTTPAuthorizationCredentials |
| 6 | +from lims_utils.auth import GenericUser |
4 | 7 | from lims_utils.logging import app_logger |
5 | 8 | from psycopg.errors import ForeignKeyViolation, UniqueViolation |
6 | | -from sqlalchemy import update |
| 9 | +from sqlalchemy import func, select, update |
7 | 10 | from sqlalchemy.exc import IntegrityError |
8 | 11 |
|
| 12 | +from ..auth import Permissions, User, auth_scheme |
9 | 13 | from ..models.inner_db import tables as db_tables |
| 14 | +from ..models.inner_db.tables import Shipment |
10 | 15 | from .database import inner_db |
| 16 | +from .external import ExternalRequest |
11 | 17 |
|
12 | 18 | UNIQUE_VIOLATION_REGEX = r"\((.*)\)=\((.*)\)" |
13 | 19 |
|
@@ -70,9 +76,60 @@ def wrap(*args, **kwargs): |
70 | 76 | case ForeignKeyViolation(): |
71 | 77 | columns = _get_columns_and_values(e.__cause__.diag.message_detail) |
72 | 78 | raise HTTPException( |
73 | | - status_code=status.HTTP_404_NOT_FOUND, detail=f"Invalid {', '.join(columns.keys())} provided" |
| 79 | + status_code=status.HTTP_404_NOT_FOUND, |
| 80 | + detail=f"Invalid {', '.join(columns.keys())} provided", |
74 | 81 | ) |
75 | 82 | case _: |
76 | 83 | app_logger.warning("Integrity error whilst performing request", exc_info=e) |
77 | 84 |
|
78 | 85 | return wrap |
| 86 | + |
| 87 | + |
| 88 | +def check_session_locked(shipment_id: int, user: GenericUser, token: HTTPAuthorizationCredentials): |
| 89 | + # Staff are exempt from this limitation |
| 90 | + if bool({"em_admin", "super_admin"} & set(user.permissions)): |
| 91 | + return False |
| 92 | + |
| 93 | + session = inner_db.session.execute( |
| 94 | + select( |
| 95 | + func.concat(Shipment.proposalCode, Shipment.proposalNumber).label("proposal"), |
| 96 | + Shipment.visitNumber, |
| 97 | + ).filter(Shipment.id == shipment_id) |
| 98 | + ).one() |
| 99 | + |
| 100 | + response = ExternalRequest.request( |
| 101 | + token=token.credentials, |
| 102 | + method="GET", |
| 103 | + url=f"/proposals/{session.proposal}/sessions/{session.visitNumber}", |
| 104 | + ) |
| 105 | + |
| 106 | + if response.status_code != 200: |
| 107 | + app_logger.warning("Failed to retrieve session from ISPyB at %s: %s", response.url, response.text) |
| 108 | + |
| 109 | + raise HTTPException( |
| 110 | + status_code=status.HTTP_424_FAILED_DEPENDENCY, |
| 111 | + detail="Resource can't be verified upstream", |
| 112 | + ) |
| 113 | + |
| 114 | + session_start = datetime.strptime(response.json()["startDate"], "%Y-%m-%dT%H:%M:%S") |
| 115 | + |
| 116 | + if session_start - datetime.now() < timedelta(hours=24): |
| 117 | + return True |
| 118 | + |
| 119 | + return False |
| 120 | + |
| 121 | + |
| 122 | +def session_unlocked( |
| 123 | + shipment_id: int = Depends(Permissions.shipment), |
| 124 | + user: GenericUser = Depends(User), |
| 125 | + token: HTTPAuthorizationCredentials = Depends(auth_scheme), |
| 126 | +): |
| 127 | + """Check if a session is locked, and its resources can't be modified any further""" |
| 128 | + |
| 129 | + if check_session_locked(shipment_id, user, token): |
| 130 | + raise HTTPException( |
| 131 | + status_code=status.HTTP_400_BAD_REQUEST, |
| 132 | + detail="Resource can't be modified 24 hours before session", |
| 133 | + ) |
| 134 | + |
| 135 | + return shipment_id |
0 commit comments