Squashed commit of the following:
commitd2ec8c0f07Author: mario <dev.mario@sismedika@gmail.com> Date: Thu May 15 15:42:33 2025 +0700 add: db tx commit and rollback implementation commit264435f67eAuthor: mario <dev.mario@sismedika@gmail.com> Date: Thu May 15 14:34:20 2025 +0700 fix: shortlink generation logic update/create commit047ab1937aAuthor: mario <dev.mario@sismedika@gmail.com> Date: Thu May 15 11:06:04 2025 +0700 fix: if multiple studies patient, show first study by default commitc13f834b92Author: mario <dev.mario@sismedika@gmail.com> Date: Thu May 15 09:46:32 2025 +0700 add: register and login with DB query AND some struct type correction commitdd4451c2a8Author: mario <dev.mario@sismedika@gmail.com> Date: Wed May 14 10:23:33 2025 +0700 new file structure & koneksi ke DB commit8289881df3Author: mario <dev.mario@sismedika@gmail.com> Date: Tue May 13 16:49:07 2025 +0700 edit: rm debug route commitdd784da232Author: mario <dev.mario@sismedika@gmail.com> Date: Tue May 13 15:44:11 2025 +0700 add: implement shortlink commit2687a761ccAuthor: mario <dev.mario@sismedika@gmail.com> Date: Tue May 13 11:47:19 2025 +0700 add new dummy doctor user commiteb67eaca46Author: mario <dev.mario@sismedika@gmail.com> Date: Tue May 13 11:46:28 2025 +0700 add: ref_doctor studylist filter commit0d4825d152Author: mario <dev.mario@sismedika@gmail.com> Date: Tue May 13 10:07:16 2025 +0700 edit study_iuids & accNum in patient jwt to array commit2d1f135fdaAuthor: mario <dev.mario@sismedika@gmail.com> Date: Tue May 13 09:52:45 2025 +0700 patient see their multiple studies commit13bb380f51Author: mario <dev.mario@sismedika@gmail.com> Date: Fri May 9 10:13:16 2025 +0700 add: cors handler route and readme commit6c9ab574ceAuthor: mario <dev.mario@sismedika@gmail.com> Date: Mon May 5 11:50:36 2025 +0700 add: login & token validation tapi belum connect ke DB commit297c9a6a01Author: mario <dev.mario@sismedika@gmail.com> Date: Mon Apr 28 15:37:02 2025 +0700 add readme.md commit9b8e0260f3Author: mario <dev.mario@sismedika@gmail.com> Date: Mon Apr 7 15:46:07 2025 +0700 connected-to-google commitf340bc5916Author: mario <dev.mario@sismedika.com> Date: Mon Apr 7 11:14:18 2025 +0700 init
This commit is contained in:
93
internal/api/handlers/auth.go
Normal file
93
internal/api/handlers/auth.go
Normal file
@@ -0,0 +1,93 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/models"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/service"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// AuthHandler handles authentication requests
|
||||
type AuthHandler struct {
|
||||
logger *zap.Logger
|
||||
authService *service.AuthService
|
||||
}
|
||||
|
||||
// NewAuthHandler creates a new auth handler
|
||||
func NewAuthHandler(logger *zap.Logger, authService *service.AuthService) *AuthHandler {
|
||||
return &AuthHandler{
|
||||
logger: logger,
|
||||
authService: authService,
|
||||
}
|
||||
}
|
||||
|
||||
// Login handles user login
|
||||
func (h *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
|
||||
// Parse login request
|
||||
var req models.LoginRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
h.logger.Error("Failed to parse login request", zap.Error(err))
|
||||
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Authenticate user using mock database
|
||||
response, err := h.authService.Login(req.Email, req.Password)
|
||||
if err != nil {
|
||||
h.logger.Warn("Login failed", zap.Error(err), zap.String("email", req.Email))
|
||||
http.Error(w, "Invalid credentials", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// Log successful login with role information
|
||||
h.logger.Info("User logged in successfully",
|
||||
zap.String("email", req.Email),
|
||||
zap.String("userID", response.User.ID),
|
||||
zap.String("role", response.User.Role))
|
||||
|
||||
// Return tokens and user info
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}
|
||||
|
||||
// RefreshToken handles token refresh
|
||||
func (h *AuthHandler) RefreshToken(w http.ResponseWriter, r *http.Request) {
|
||||
// Parse refresh token request
|
||||
var req models.RefreshRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
h.logger.Error("Failed to parse refresh token request", zap.Error(err))
|
||||
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Refresh token
|
||||
accessToken, err := h.authService.RefreshToken(req.RefreshToken)
|
||||
if err != nil {
|
||||
h.logger.Warn("Token refresh failed", zap.Error(err))
|
||||
http.Error(w, "Invalid refresh token", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// Return new access token
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(models.RefreshResponse{
|
||||
AccessToken: accessToken,
|
||||
})
|
||||
}
|
||||
|
||||
// Logout handles user logout
|
||||
func (h *AuthHandler) Logout(w http.ResponseWriter, r *http.Request) {
|
||||
// In a real implementation, you would invalidate the refresh token
|
||||
// For now, just return a success message
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"message": "Successfully logged out",
|
||||
})
|
||||
}
|
||||
247
internal/api/handlers/dicom.go
Normal file
247
internal/api/handlers/dicom.go
Normal file
@@ -0,0 +1,247 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/middleware"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/auth"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/proxy"
|
||||
"github.com/go-chi/chi/v5"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// DicomHandler handles DICOM Web requests
|
||||
type DicomHandler struct {
|
||||
client *proxy.Client
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// NewDicomHandler creates a new DICOM handler
|
||||
func NewDicomHandler(client *proxy.Client, logger *zap.Logger) *DicomHandler {
|
||||
return &DicomHandler{
|
||||
client: client,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// buildRefDoctorFilter constructs a properly encoded query string for referring doctor filtering
|
||||
func (h *DicomHandler) buildRefDoctorFilter(doctorName string, queryParams url.Values) string {
|
||||
// Extract basic parameters with fallbacks
|
||||
limit := queryParams.Get("limit")
|
||||
if limit == "" {
|
||||
limit = "101" // Default limit used by OHIF
|
||||
}
|
||||
|
||||
offset := queryParams.Get("offset")
|
||||
if offset == "" {
|
||||
offset = "0" // Default offset
|
||||
}
|
||||
|
||||
includeField := queryParams.Get("includefield")
|
||||
|
||||
// Make sure includefield includes 00080090 (ReferringPhysician)
|
||||
if includeField != "" && !strings.Contains(includeField, "00080090") {
|
||||
includeField = includeField + ",00080090"
|
||||
} else if includeField == "" {
|
||||
includeField = "00081030,00080060,00080090"
|
||||
}
|
||||
|
||||
// Properly encode the doctor's name
|
||||
encodedName := strings.ReplaceAll(doctorName, " ", "%20")
|
||||
encodedName = strings.ReplaceAll(encodedName, ",", "%2C")
|
||||
encodedName = strings.ReplaceAll(encodedName, ".", "%2E")
|
||||
|
||||
// Construct query string manually to avoid double-encoding
|
||||
return fmt.Sprintf("limit=%s&offset=%s&fuzzymatching=false&includefield=%s&00080090=%s",
|
||||
limit, offset, includeField, encodedName)
|
||||
}
|
||||
|
||||
// isStudyListRequest checks if a path refers to the top-level studies endpoint
|
||||
func isStudyListRequest(path string) bool {
|
||||
// Normalize the path first
|
||||
if !strings.HasPrefix(path, "/") {
|
||||
path = "/" + path
|
||||
}
|
||||
|
||||
// Check for exact match with "/studies"
|
||||
return path == "/studies"
|
||||
}
|
||||
|
||||
// ForwardRequest forwards the request to Google Healthcare API
|
||||
func (h *DicomHandler) ForwardRequest(w http.ResponseWriter, r *http.Request) {
|
||||
// Get claims from context if they exist
|
||||
var claims *auth.CustomClaims
|
||||
claimsValue := r.Context().Value(middleware.ClaimsKey)
|
||||
|
||||
// Add detailed debug logging about claims
|
||||
if claimsValue == nil {
|
||||
h.logger.Warn("Claims not found in context",
|
||||
zap.String("path", r.URL.Path),
|
||||
zap.String("method", r.Method))
|
||||
} else {
|
||||
claims = claimsValue.(*auth.CustomClaims)
|
||||
h.logger.Debug("Claims retrieved from context",
|
||||
zap.String("userID", claims.UserID),
|
||||
zap.String("role", claims.Role),
|
||||
zap.String("userName", claims.UserName))
|
||||
}
|
||||
|
||||
// Get the path after /dicomWeb
|
||||
urlPath := chi.URLParam(r, "*")
|
||||
|
||||
// If the URL parameter is empty, try to extract it from the URL path
|
||||
if urlPath == "" {
|
||||
// Remove /dicomWeb prefix from the URL
|
||||
prefix := "/dicomWeb"
|
||||
if strings.HasPrefix(r.URL.Path, prefix) {
|
||||
urlPath = r.URL.Path[len(prefix):]
|
||||
}
|
||||
}
|
||||
|
||||
// Normalize the path
|
||||
if !strings.HasPrefix(urlPath, "/") {
|
||||
urlPath = "/" + urlPath
|
||||
}
|
||||
|
||||
h.logger.Debug("Forwarding request",
|
||||
zap.String("path", urlPath),
|
||||
zap.String("method", r.Method),
|
||||
zap.String("url", r.URL.String()))
|
||||
|
||||
// Copy query parameters
|
||||
queryParams := r.URL.Query()
|
||||
queryString := ""
|
||||
|
||||
// Apply role-specific query modifications
|
||||
if claims != nil {
|
||||
switch claims.Role {
|
||||
case "patient":
|
||||
// For patients requesting study list, filter to only show their studies
|
||||
if isStudyListRequest(urlPath) {
|
||||
// Check if studies are available in the claim
|
||||
if len(claims.StudyIUIDs) > 0 {
|
||||
// Remove existing StudyInstanceUID param if it exists
|
||||
queryParams.Del("StudyInstanceUID")
|
||||
|
||||
// For DICOMweb, we can use comma-separated UIDs
|
||||
queryParams.Set("StudyInstanceUID", claims.StudyIUIDs[0])
|
||||
|
||||
h.logger.Debug("Filtering by studies",
|
||||
zap.Strings("studies", claims.StudyIUIDs))
|
||||
}
|
||||
} else if strings.HasPrefix(urlPath, "/studies/") {
|
||||
// This is a request for a specific study - check if the patient is authorized
|
||||
|
||||
// Extract the study ID from the path
|
||||
// Format: /studies/{studyID}/...
|
||||
pathParts := strings.Split(strings.TrimPrefix(urlPath, "/"), "/")
|
||||
if len(pathParts) >= 2 {
|
||||
studyID := pathParts[1]
|
||||
|
||||
// Check if this study is in the patient's authorized studies
|
||||
authorized := false
|
||||
|
||||
// Check StudyIUIDs array
|
||||
for _, id := range claims.StudyIUIDs {
|
||||
if id == studyID {
|
||||
authorized = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// If not authorized, return 403 Forbidden
|
||||
if !authorized {
|
||||
h.logger.Warn("Unauthorized study access attempt",
|
||||
zap.String("studyID", studyID),
|
||||
zap.String("patientID", claims.PatientID),
|
||||
zap.Strings("authorizedStudies", claims.StudyIUIDs),
|
||||
)
|
||||
http.Error(w, "Forbidden: You are not authorized to access this study", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
h.logger.Debug("Authorized access to specific study",
|
||||
zap.String("studyID", studyID),
|
||||
zap.String("patientID", claims.PatientID),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Use standard query parameter encoding
|
||||
queryString = queryParams.Encode()
|
||||
|
||||
case "ref_doctor":
|
||||
// For ref_doctor requesting study list, apply filter
|
||||
if isStudyListRequest(urlPath) {
|
||||
// Use our helper function to build the properly encoded query
|
||||
queryString = h.buildRefDoctorFilter(claims.UserName, queryParams)
|
||||
|
||||
h.logger.Debug("Applied referring physician filter",
|
||||
zap.String("doctorName", claims.UserName),
|
||||
zap.String("queryString", queryString))
|
||||
} else {
|
||||
// For other paths, use standard query parameter encoding
|
||||
queryString = queryParams.Encode()
|
||||
}
|
||||
|
||||
case "expertise_doctor":
|
||||
// No restrictions for expertise_doctor
|
||||
queryString = queryParams.Encode()
|
||||
}
|
||||
} else {
|
||||
// No claims, use standard query parameter encoding
|
||||
queryString = queryParams.Encode()
|
||||
}
|
||||
|
||||
// Add the query string to the path
|
||||
if queryString != "" {
|
||||
urlPath = urlPath + "?" + queryString
|
||||
}
|
||||
|
||||
// Read request body if present
|
||||
var bodyBytes []byte
|
||||
if r.Body != nil && r.ContentLength > 0 {
|
||||
var err error
|
||||
bodyBytes, err = io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
h.logger.Error("Failed to read request body", zap.Error(err))
|
||||
http.Error(w, "Failed to read request body", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Get request headers
|
||||
headers := make(map[string]string)
|
||||
for k, v := range r.Header {
|
||||
if len(v) > 0 {
|
||||
headers[k] = v[0]
|
||||
}
|
||||
}
|
||||
|
||||
// Forward the request to Healthcare API
|
||||
response, err := h.client.ForwardRequest(
|
||||
r.Context(),
|
||||
r.Method,
|
||||
urlPath,
|
||||
headers,
|
||||
bodyBytes)
|
||||
|
||||
if err != nil {
|
||||
h.logger.Error("Request forwarding failed", zap.Error(err))
|
||||
http.Error(w, fmt.Sprintf("Request failed: %v", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Set response headers
|
||||
for k, v := range response.Headers {
|
||||
w.Header().Set(k, v)
|
||||
}
|
||||
|
||||
// Set status and write response body
|
||||
w.WriteHeader(response.StatusCode)
|
||||
w.Write(response.Body)
|
||||
}
|
||||
19
internal/api/handlers/healthcheck.go
Normal file
19
internal/api/handlers/healthcheck.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// HealthCheck provides a simple health check endpoint
|
||||
func HealthCheck(w http.ResponseWriter, r *http.Request) {
|
||||
response := map[string]interface{}{
|
||||
"status": "ok",
|
||||
"timestamp": time.Now().Format(time.RFC3339),
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}
|
||||
68
internal/api/handlers/register.go
Normal file
68
internal/api/handlers/register.go
Normal file
@@ -0,0 +1,68 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/service"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// RegisterHandler handles user registration requests
|
||||
type RegisterHandler struct {
|
||||
logger *zap.Logger
|
||||
registerService *service.RegisterService
|
||||
}
|
||||
|
||||
// NewRegisterHandler creates a new registration handler
|
||||
func NewRegisterHandler(logger *zap.Logger, registerService *service.RegisterService) *RegisterHandler {
|
||||
return &RegisterHandler{
|
||||
logger: logger,
|
||||
registerService: registerService,
|
||||
}
|
||||
}
|
||||
|
||||
// Register handles the creation of new users, patients, and doctors
|
||||
func (h *RegisterHandler) Register(w http.ResponseWriter, r *http.Request) {
|
||||
// Parse registration request
|
||||
var req service.RegisterRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
h.logger.Error("Failed to parse registration request", zap.Error(err))
|
||||
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Validate required fields
|
||||
if req.Email == "" || req.Password == "" || req.Name == "" || req.Role == "" {
|
||||
http.Error(w, "Missing required fields", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Perform registration
|
||||
user, err := h.registerService.Register(&req)
|
||||
if err != nil {
|
||||
switch err {
|
||||
case service.ErrEmailExists:
|
||||
http.Error(w, "Email already exists", http.StatusConflict)
|
||||
case service.ErrInvalidRole:
|
||||
http.Error(w, "Invalid user role", http.StatusBadRequest)
|
||||
case service.ErrInvalidPatient:
|
||||
http.Error(w, "Invalid patient data", http.StatusBadRequest)
|
||||
case service.ErrInvalidDoctor:
|
||||
http.Error(w, "Invalid doctor data", http.StatusBadRequest)
|
||||
default:
|
||||
h.logger.Error("Registration failed", zap.Error(err))
|
||||
http.Error(w, "Registration failed", http.StatusInternalServerError)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Return created user
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
|
||||
// Don't include password in response
|
||||
user.Password = ""
|
||||
|
||||
json.NewEncoder(w).Encode(user)
|
||||
}
|
||||
129
internal/api/handlers/shortlink.go
Normal file
129
internal/api/handlers/shortlink.go
Normal file
@@ -0,0 +1,129 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/middleware"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/models"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/service"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// ShortLinkHandler handles shortlink operations
|
||||
type ShortLinkHandler struct {
|
||||
logger *zap.Logger
|
||||
shortLinkService *service.ShortLinkService
|
||||
}
|
||||
|
||||
// NewShortLinkHandler creates a new shortlink handler
|
||||
func NewShortLinkHandler(logger *zap.Logger, shortLinkService *service.ShortLinkService) *ShortLinkHandler {
|
||||
return &ShortLinkHandler{
|
||||
logger: logger,
|
||||
shortLinkService: shortLinkService,
|
||||
}
|
||||
}
|
||||
|
||||
// GenerateShortLink handles shortlink generation requests
|
||||
func (h *ShortLinkHandler) GenerateShortLink(w http.ResponseWriter, r *http.Request) {
|
||||
// Only allow admin or expertise_doctor roles to generate shortlinks
|
||||
userRole, ok := r.Context().Value(middleware.UserRoleKey).(string)
|
||||
if !ok || (userRole != "admin" && userRole != "expertise_doctor") {
|
||||
h.logger.Warn("Unauthorized attempt to generate shortlink",
|
||||
zap.String("role", userRole))
|
||||
http.Error(w, "Only admin or expertise doctor can generate short links", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
// Parse request body
|
||||
var req models.GenerateShortLinkRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
h.logger.Error("Failed to parse shortlink generation request", zap.Error(err))
|
||||
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Get user ID from context
|
||||
userID, ok := r.Context().Value(middleware.UserIDKey).(string)
|
||||
if !ok {
|
||||
h.logger.Error("User ID not found in context")
|
||||
http.Error(w, "User context not found", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Generate shortlink using configured baseURL from service
|
||||
response, err := h.shortLinkService.GenerateShortLink(&req, userID)
|
||||
if err != nil {
|
||||
h.logger.Error("Failed to generate shortlink",
|
||||
zap.Error(err),
|
||||
zap.String("patientID", req.PatientID),
|
||||
zap.String("studyUID", req.StudyUID))
|
||||
|
||||
statusCode := http.StatusInternalServerError
|
||||
message := "Failed to generate shortlink"
|
||||
|
||||
if err == service.ErrInvalidStudyUID {
|
||||
statusCode = http.StatusBadRequest
|
||||
message = "Invalid StudyInstanceUID"
|
||||
}
|
||||
|
||||
http.Error(w, message, statusCode)
|
||||
return
|
||||
}
|
||||
|
||||
// Log successful shortlink generation
|
||||
h.logger.Info("Shortlink generated successfully",
|
||||
zap.String("token", response.ShortToken),
|
||||
zap.String("patientID", req.PatientID),
|
||||
zap.String("studyUID", req.StudyUID),
|
||||
zap.String("createdBy", userID))
|
||||
|
||||
// Return response
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}
|
||||
|
||||
// ShortLinkAuth handles authentication requests using shortlinks
|
||||
func (h *ShortLinkHandler) ShortLinkAuth(w http.ResponseWriter, r *http.Request) {
|
||||
// Parse request body
|
||||
var req models.ShortLinkAuthRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
h.logger.Error("Failed to parse shortlink auth request", zap.Error(err))
|
||||
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Validate and authenticate
|
||||
response, err := h.shortLinkService.AuthenticateWithShortLink(&req)
|
||||
if err != nil {
|
||||
h.logger.Warn("Shortlink authentication failed",
|
||||
zap.Error(err),
|
||||
zap.String("token", req.ShortToken))
|
||||
|
||||
statusCode := http.StatusUnauthorized
|
||||
message := "Authentication failed"
|
||||
|
||||
switch err {
|
||||
case service.ErrShortLinkNotFound, service.ErrShortLinkExpired:
|
||||
message = "Short link not found or expired"
|
||||
case service.ErrInvalidDOB:
|
||||
message = "Invalid date of birth"
|
||||
case service.ErrTooManyAttempts:
|
||||
message = "Too many failed attempts"
|
||||
}
|
||||
|
||||
http.Error(w, message, statusCode)
|
||||
return
|
||||
}
|
||||
|
||||
// Log successful authentication
|
||||
h.logger.Info("Shortlink authentication successful",
|
||||
zap.String("token", req.ShortToken))
|
||||
|
||||
// Return response
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}
|
||||
234
internal/api/middleware/auth.go
Normal file
234
internal/api/middleware/auth.go
Normal file
@@ -0,0 +1,234 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/service"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/auth"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
|
||||
const (
|
||||
UserIDKey contextKey = "user_id"
|
||||
UserRoleKey contextKey = "user_role"
|
||||
UserEmailKey contextKey = "user_email"
|
||||
ClaimsKey contextKey = "auth_claims" // Use this same key everywhere
|
||||
)
|
||||
|
||||
// WhitelistedEndpoints contains paths that can be accessed without authentication
|
||||
var WhitelistedEndpoints = []*regexp.Regexp{
|
||||
// Study by UID
|
||||
regexp.MustCompile(`^/dicomWeb/studies\?.*StudyInstanceUID=.+`),
|
||||
|
||||
// Frame endpoint
|
||||
regexp.MustCompile(`^/dicomWeb/studies/[^/]+/series/[^/]+/instances/[^/]+/frames/\d+$`),
|
||||
}
|
||||
|
||||
// Auth middleware authenticates requests using JWT tokens
|
||||
func Auth(authService *service.AuthService, logger *zap.Logger) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Get authorization header
|
||||
authHeader := r.Header.Get("Authorization")
|
||||
if authHeader == "" {
|
||||
logger.Warn("Missing Authorization header", zap.String("path", r.URL.Path))
|
||||
respondWithError(w, http.StatusUnauthorized, "missing authorization header")
|
||||
return
|
||||
}
|
||||
|
||||
// Extract token from Bearer token
|
||||
bearerToken := strings.Split(authHeader, " ")
|
||||
if len(bearerToken) != 2 || strings.ToLower(bearerToken[0]) != "bearer" {
|
||||
logger.Warn("Invalid Authorization header format", zap.String("header", authHeader))
|
||||
respondWithError(w, http.StatusUnauthorized, "invalid authorization format")
|
||||
return
|
||||
}
|
||||
|
||||
token := bearerToken[1]
|
||||
|
||||
// Validate token
|
||||
claims, err := authService.ValidateToken(token)
|
||||
if err != nil {
|
||||
logger.Warn("Invalid or expired token", zap.Error(err))
|
||||
respondWithError(w, http.StatusUnauthorized, "invalid or expired token")
|
||||
return
|
||||
}
|
||||
|
||||
// Check token type
|
||||
if claims.TokenType != "access" {
|
||||
logger.Warn("Invalid token type", zap.String("tokenType", claims.TokenType))
|
||||
respondWithError(w, http.StatusUnauthorized, "invalid token type")
|
||||
return
|
||||
}
|
||||
|
||||
// Add user info to request context
|
||||
ctx := context.WithValue(r.Context(), UserIDKey, claims.UserID)
|
||||
ctx = context.WithValue(ctx, UserRoleKey, claims.Role)
|
||||
ctx = context.WithValue(ctx, UserEmailKey, claims.Email) // TODO: Apakah kita perlu param email untuk generate access token?
|
||||
|
||||
// Store the claims with the defined context key
|
||||
ctx = context.WithValue(ctx, ClaimsKey, claims)
|
||||
|
||||
// Log successful authentication
|
||||
logger.Debug("Auth middleware: Token validated",
|
||||
zap.String("userID", claims.UserID),
|
||||
zap.String("role", claims.Role))
|
||||
|
||||
// Continue with the request
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// RoleRequired middleware checks if user has the required role
|
||||
func RoleRequired(roles ...string) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Check if the request path is whitelisted first
|
||||
path := r.URL.Path
|
||||
if r.URL.RawQuery != "" {
|
||||
path = path + "?" + r.URL.RawQuery
|
||||
}
|
||||
|
||||
for _, pattern := range WhitelistedEndpoints {
|
||||
if pattern.MatchString(path) {
|
||||
// Path is whitelisted, skip role check
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Get user role from context
|
||||
userRole, ok := r.Context().Value(UserRoleKey).(string)
|
||||
if !ok {
|
||||
respondWithError(w, http.StatusUnauthorized, "user context not found")
|
||||
return
|
||||
}
|
||||
|
||||
// Check if user has one of the required roles
|
||||
hasRole := false
|
||||
for _, role := range roles {
|
||||
if userRole == role {
|
||||
hasRole = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !hasRole {
|
||||
respondWithError(w, http.StatusForbidden, "insufficient permissions")
|
||||
return
|
||||
}
|
||||
|
||||
// Continue with the request
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// PatientViewRestriction ensures patients can only access their own studies
|
||||
func PatientViewRestriction(logger *zap.Logger) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Get claims from context using the defined key
|
||||
claimsValue := r.Context().Value(ClaimsKey)
|
||||
if claimsValue == nil {
|
||||
logger.Error("Missing claims in context - PatientViewRestriction middleware",
|
||||
zap.String("path", r.URL.Path),
|
||||
zap.String("method", r.Method))
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
claims, ok := claimsValue.(*auth.CustomClaims)
|
||||
if !ok {
|
||||
logger.Error("Invalid claims type in context",
|
||||
zap.String("type", fmt.Sprintf("%T", claimsValue)))
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
logger.Debug("PatientViewRestriction: Got claims from context",
|
||||
zap.String("userID", claims.UserID),
|
||||
zap.String("role", claims.Role))
|
||||
|
||||
// Only apply restrictions to patient role
|
||||
if claims.Role != "patient" {
|
||||
// For non-patient roles, continue with the request
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
// Parse the path to extract StudyInstanceUID if present
|
||||
path := r.URL.Path
|
||||
parts := strings.Split(path, "/")
|
||||
|
||||
// Check if this is a study-specific request
|
||||
var requestedStudyUID string
|
||||
for i, part := range parts {
|
||||
if part == "studies" && i+1 < len(parts) {
|
||||
requestedStudyUID = parts[i+1]
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// If there's no study UID in the path, check query parameters
|
||||
if requestedStudyUID == "" {
|
||||
queryStudyUID := r.URL.Query().Get("StudyInstanceUID")
|
||||
if queryStudyUID != "" {
|
||||
requestedStudyUID = queryStudyUID
|
||||
}
|
||||
}
|
||||
|
||||
// If a study is being requested, verify patient has access
|
||||
if requestedStudyUID != "" && len(claims.StudyIUIDs) > 0 {
|
||||
// Check if the requested study is authorized
|
||||
isAuthorized := false
|
||||
|
||||
for _, studyUID := range claims.StudyIUIDs {
|
||||
if studyUID == requestedStudyUID {
|
||||
isAuthorized = true
|
||||
logger.Debug("Patient authorized to access study",
|
||||
zap.String("userID", claims.UserID),
|
||||
zap.String("requestedStudy", requestedStudyUID))
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// If not authorized, return 403 Forbidden
|
||||
if !isAuthorized {
|
||||
logger.Warn("Patient attempted to access unauthorized study",
|
||||
zap.String("userID", claims.UserID),
|
||||
zap.String("role", claims.Role),
|
||||
zap.String("requestedStudy", requestedStudyUID),
|
||||
zap.Strings("authorizedStudies", claims.StudyIUIDs))
|
||||
|
||||
// Return 403 Forbidden with a clear message
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"error": "Access denied: You do not have permission to view this study",
|
||||
"code": "forbidden_study_access",
|
||||
})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Patient has access or is requesting a list (which will be filtered)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to respond with an error
|
||||
func respondWithError(w http.ResponseWriter, statusCode int, message string) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(statusCode)
|
||||
json.NewEncoder(w).Encode(map[string]string{"error": message})
|
||||
}
|
||||
61
internal/api/middleware/logging.go
Normal file
61
internal/api/middleware/logging.go
Normal file
@@ -0,0 +1,61 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// Logger middleware adds request logging
|
||||
func Logger(logger *zap.Logger) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
|
||||
// Create a wrapped response writer to capture the status code
|
||||
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
||||
|
||||
// Process request
|
||||
next.ServeHTTP(ww, r)
|
||||
|
||||
// Calculate request time
|
||||
latency := time.Since(start)
|
||||
|
||||
// Log request details
|
||||
logger.Info("API Request",
|
||||
zap.String("method", r.Method),
|
||||
zap.String("path", r.URL.Path),
|
||||
zap.String("query", r.URL.RawQuery),
|
||||
zap.Int("status", ww.Status()),
|
||||
zap.Duration("latency", latency),
|
||||
zap.String("ip", r.RemoteAddr),
|
||||
zap.String("user-agent", r.UserAgent()),
|
||||
zap.Int("bytes", ww.BytesWritten()),
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// AuditLog middleware records detailed information about DICOM requests
|
||||
func AuditLog(logger *zap.Logger) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Extract user info (placeholder for now)
|
||||
userID := "TODO: userID"
|
||||
|
||||
// Process request
|
||||
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
||||
next.ServeHTTP(ww, r)
|
||||
|
||||
// Audit log after request completes
|
||||
logger.Info("DICOM Access",
|
||||
zap.String("userID", userID),
|
||||
zap.String("action", r.Method),
|
||||
zap.String("resource", r.URL.Path),
|
||||
zap.Int("status", ww.Status()),
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
8
internal/api/models/doctor.go
Normal file
8
internal/api/models/doctor.go
Normal file
@@ -0,0 +1,8 @@
|
||||
package models
|
||||
|
||||
// DoctorDetails contains doctor-specific data
|
||||
type DoctorDetails struct {
|
||||
DoctorID string `json:"doctor_id"`
|
||||
DoctorName string `json:"doctor_name"`
|
||||
Type string `json:"type"` // "ref_doctor" or "expertise_doctor"
|
||||
}
|
||||
112
internal/api/models/mock_data.go
Normal file
112
internal/api/models/mock_data.go
Normal file
@@ -0,0 +1,112 @@
|
||||
package models
|
||||
|
||||
// MockUsers represents a mock database of users
|
||||
var MockUsers = []User{
|
||||
{
|
||||
ID: "1",
|
||||
Email: "admin",
|
||||
Role: "expertise_doctor",
|
||||
Name: "Admin User",
|
||||
CreatedAt: "2025-01-01T00:00:00Z",
|
||||
UpdatedAt: "2025-01-01T00:00:00Z",
|
||||
},
|
||||
{
|
||||
ID: "2",
|
||||
Email: "patient",
|
||||
Role: "patient",
|
||||
Name: "Patient User",
|
||||
CreatedAt: "2025-01-01T00:00:00Z",
|
||||
UpdatedAt: "2025-01-01T00:00:00Z",
|
||||
},
|
||||
{
|
||||
ID: "3",
|
||||
Email: "doctor",
|
||||
Role: "ref_doctor",
|
||||
Name: "DR. HERWINDO RIDWAN, SP.OT",
|
||||
CreatedAt: "2025-01-01T00:00:00Z",
|
||||
UpdatedAt: "2025-01-01T00:00:00Z",
|
||||
},
|
||||
{
|
||||
ID: "4",
|
||||
Email: "patient2",
|
||||
Role: "patient",
|
||||
Name: "Patient Two",
|
||||
CreatedAt: "2025-01-01T00:00:00Z",
|
||||
UpdatedAt: "2025-01-01T00:00:00Z",
|
||||
},
|
||||
{
|
||||
ID: "5",
|
||||
Email: "doctor2",
|
||||
Role: "ref_doctor",
|
||||
Name: "Referring^Physician",
|
||||
CreatedAt: "2025-01-01T00:00:00Z",
|
||||
UpdatedAt: "2025-01-01T00:00:00Z",
|
||||
},
|
||||
}
|
||||
|
||||
// PatientData represents additional data for patients
|
||||
type PatientData struct {
|
||||
PatientID string `json:"patient_id"`
|
||||
UserID string `json:"user_id"`
|
||||
StudyIUIDs []string `json:"study_iuids"`
|
||||
AccessionNumbers []string `json:"accession_numbers"`
|
||||
PatientName string `json:"patient_name"`
|
||||
ReferringPhysician string `json:"referring_physician"`
|
||||
}
|
||||
|
||||
// MockPatients represents a mock database of patient data
|
||||
var MockPatients = []PatientData{
|
||||
{
|
||||
PatientID: "00211622",
|
||||
UserID: "2",
|
||||
StudyIUIDs: []string{"1.2.826.0.1.3680043.9.7307.1.20180530066", "1.2.826.0.1.3680043.9.7307.1.20180713036"},
|
||||
AccessionNumbers: []string{"CR.180530.066", "CR.180713.036"},
|
||||
PatientName: "DIDIT SUYATNA^R.10049.18",
|
||||
ReferringPhysician: "DR. HERWINDO RIDWAN, SP.OT",
|
||||
},
|
||||
{
|
||||
PatientID: "MR00000359",
|
||||
UserID: "4",
|
||||
StudyIUIDs: []string{"1.2.826.0.1.3680043.9.7307.1.202503196393.01"},
|
||||
AccessionNumbers: []string{"CR.250319.6393.01"},
|
||||
PatientName: "Bobon Santoso",
|
||||
ReferringPhysician: "DR. HERWINDO RIDWAN, SP.OT",
|
||||
},
|
||||
}
|
||||
|
||||
// FindUserByCredentials finds a user by email and password (mock authentication)
|
||||
func FindUserByCredentials(email, password string) *User {
|
||||
// In a real implementation, you would hash passwords
|
||||
// For the mock, we'll just match email and assume password is the same as email
|
||||
if password != email {
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, user := range MockUsers {
|
||||
if user.Email == email {
|
||||
return &user
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// FindPatientDataByUserID finds patient data by user ID
|
||||
func FindPatientDataByUserID(userID string) *PatientData {
|
||||
for _, patient := range MockPatients {
|
||||
if patient.UserID == userID {
|
||||
return &patient
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// FindStudiesByReferringPhysician returns all study IUIDs that belong to a referring physician
|
||||
func FindStudiesByReferringPhysician(physicianName string) []string {
|
||||
var studies []string
|
||||
for _, patient := range MockPatients {
|
||||
if patient.ReferringPhysician == physicianName {
|
||||
studies = append(studies, patient.StudyIUIDs...)
|
||||
}
|
||||
}
|
||||
return studies
|
||||
}
|
||||
19
internal/api/models/patient.go
Normal file
19
internal/api/models/patient.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package models
|
||||
|
||||
// PatientDetails contains patient-specific data
|
||||
type PatientDetails struct {
|
||||
PatientID string `json:"patient_id"`
|
||||
PatientName string `json:"patient_name"`
|
||||
DateOfBirth string `json:"date_of_birth"` // YYYY-MM-DD format
|
||||
StudyInstanceUIDs []string `json:"study_instance_uids,omitempty"`
|
||||
AccessionNumbers []string `json:"accession_numbers,omitempty"`
|
||||
}
|
||||
|
||||
// Study represents a DICOM study associated with a patient
|
||||
type Study struct {
|
||||
StudyInstanceUID string `json:"study_instance_uid"`
|
||||
AccessionNumber string `json:"accession_number,omitempty"`
|
||||
StudyDate string `json:"study_date,omitempty"`
|
||||
StudyDescription string `json:"study_description,omitempty"`
|
||||
Modalities string `json:"modalities,omitempty"`
|
||||
}
|
||||
53
internal/api/models/shortlink.go
Normal file
53
internal/api/models/shortlink.go
Normal file
@@ -0,0 +1,53 @@
|
||||
package models
|
||||
|
||||
// ShortLink represents a short URL token for patient access
|
||||
type ShortLink struct {
|
||||
ID string `db:"id" json:"id"`
|
||||
Token string `db:"token" json:"token"` // The short token used in the URL
|
||||
PatientID string `db:"patient_id" json:"patient_id"`
|
||||
StudyUID string `db:"study_uid" json:"study_uid"` // The StudyInstanceUID this token grants access to
|
||||
HashedDOB string `db:"hashed_dob" json:"-"` // Hashed Date of Birth for verification
|
||||
ExpiresAt string `db:"expires_at" json:"expires_at"`
|
||||
IsRevoked bool `db:"is_revoked" json:"is_revoked"`
|
||||
CreatedAt string `db:"created_at" json:"created_at"`
|
||||
CreatedByID string `db:"created_by_id" json:"created_by_id"` // ID of admin who created this
|
||||
RemainingTries int `db:"remaining_tries" json:"-"` // Number of failed attempts allowed
|
||||
}
|
||||
|
||||
// GenerateShortLinkRequest represents request to create a short URL
|
||||
type GenerateShortLinkRequest struct {
|
||||
PatientID string `json:"patient_id"`
|
||||
StudyUID string `json:"study_uid"`
|
||||
DOB string `json:"dob"` // Date of birth in YYYY-MM-DD format
|
||||
ExpiresIn int `json:"expires_in"` // Expiry in hours (optional, defaults to 72)
|
||||
}
|
||||
|
||||
// GenerateShortLinkResponse is the response for a generated short link
|
||||
type GenerateShortLinkResponse struct {
|
||||
ShortToken string `json:"short_token"`
|
||||
FullURL string `json:"full_url"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
IsExisting bool `json:"is_existing"` // Indicates if this is an existing link that was reused
|
||||
}
|
||||
|
||||
// ShortLinkAuthRequest represents the shortlink authentication request
|
||||
type ShortLinkAuthRequest struct {
|
||||
ShortToken string `json:"short_token,omitempty"` // The original field
|
||||
ShortTokenAlt string `json:"shortToken,omitempty"` // Support for camelCase naming from OHIF
|
||||
DOB string `json:"dob"` // Date of birth in YYYY-MM-DD format
|
||||
}
|
||||
|
||||
func (r *ShortLinkAuthRequest) GetToken() string {
|
||||
// Use ShortTokenAlt if ShortToken is empty
|
||||
if r.ShortToken == "" {
|
||||
return r.ShortTokenAlt
|
||||
}
|
||||
return r.ShortToken
|
||||
}
|
||||
|
||||
// ShortLinkAuthResponse is the response for successful shortlink authentication
|
||||
type ShortLinkAuthResponse struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
ExpiresIn int `json:"expires_in"` // Token expiry in seconds
|
||||
RedirectURL string `json:"redirect_url"`
|
||||
}
|
||||
46
internal/api/models/user.go
Normal file
46
internal/api/models/user.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package models
|
||||
|
||||
// User represents a system user
|
||||
type User struct {
|
||||
ID string `db:"id" json:"id"`
|
||||
Email string `db:"email" json:"email"`
|
||||
Password string `db:"password" json:"-"` // Never expose password in JSON
|
||||
Role string `db:"role" json:"role"`
|
||||
Name string `db:"name" json:"name"`
|
||||
CreatedAt string `db:"created_at" json:"created_at"`
|
||||
UpdatedAt string `db:"updated_at" json:"updated_at"`
|
||||
}
|
||||
|
||||
// RefreshToken represents a refresh token stored in the database
|
||||
type RefreshToken struct {
|
||||
ID string `db:"id" json:"id"`
|
||||
UserID string `db:"user_id" json:"user_id"`
|
||||
Token string `db:"token" json:"token"`
|
||||
ExpiresAt string `db:"expires_at" json:"expires_at"`
|
||||
IsRevoked bool `db:"is_revoked" json:"is_revoked"`
|
||||
CreatedAt string `db:"created_at" json:"created_at"`
|
||||
}
|
||||
|
||||
// LoginRequest represents the login form data
|
||||
type LoginRequest struct {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
// LoginResponse is the response sent after successful login
|
||||
type LoginResponse struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
User *User `json:"user"`
|
||||
RedirectURL string `json:"redirect_url"`
|
||||
}
|
||||
|
||||
// RefreshRequest represents the refresh token request
|
||||
type RefreshRequest struct {
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
}
|
||||
|
||||
// RefreshResponse is the response for a token refresh
|
||||
type RefreshResponse struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
}
|
||||
59
internal/api/repository/doctor.go
Normal file
59
internal/api/repository/doctor.go
Normal file
@@ -0,0 +1,59 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/models"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/database"
|
||||
"github.com/jmoiron/sqlx"
|
||||
)
|
||||
|
||||
// DBDoctor represents a doctor from the database
|
||||
type DBDoctor struct {
|
||||
ID int `db:"id"`
|
||||
Doctor_UsersID string `db:"Doctor_UsersID"`
|
||||
DoctorID string `db:"DoctorID"`
|
||||
DoctorName string `db:"DoctorName"`
|
||||
DoctorCreatedAt time.Time `db:"DoctorCreatedAt"`
|
||||
DoctorLastUpdatedAt time.Time `db:"DoctorLastUpdatedAt"`
|
||||
}
|
||||
|
||||
// DoctorRepository handles database operations related to doctors
|
||||
type DoctorRepository struct {
|
||||
*Repository
|
||||
}
|
||||
|
||||
// NewDoctorRepository creates a new doctor repository
|
||||
func NewDoctorRepository() *DoctorRepository {
|
||||
return &DoctorRepository{
|
||||
Repository: NewRepository(),
|
||||
}
|
||||
}
|
||||
|
||||
// GetDoctorDetailsByUserID retrieves doctor details for a user
|
||||
func (r *DoctorRepository) GetDoctorDetailsByUserID(userID string) (*DBDoctor, error) {
|
||||
var dbDoctor DBDoctor
|
||||
|
||||
query := `SELECT * FROM doctor WHERE Doctor_UsersID = ?`
|
||||
err := database.DB.Get(&dbDoctor, query, userID)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("database error getting doctor details: %w", err)
|
||||
}
|
||||
|
||||
return &dbDoctor, nil
|
||||
}
|
||||
|
||||
// CreateDoctorTx creates a new doctor record within a transaction
|
||||
func (r *DoctorRepository) CreateDoctorTx(tx *sqlx.Tx, doctorDetails *models.DoctorDetails, userID string) error {
|
||||
query := `INSERT INTO doctor (Doctor_UsersID, DoctorID, DoctorName, DoctorCreatedAt, DoctorLastUpdatedAt)
|
||||
VALUES (?, ?, ?, NOW(), NOW())`
|
||||
|
||||
_, err := tx.Exec(query, userID, doctorDetails.DoctorID, doctorDetails.DoctorName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("database error creating doctor: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
82
internal/api/repository/patient.go
Normal file
82
internal/api/repository/patient.go
Normal file
@@ -0,0 +1,82 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/models"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/database"
|
||||
"github.com/jmoiron/sqlx"
|
||||
)
|
||||
|
||||
// DBPatient represents a patient from the database
|
||||
type DBPatient struct {
|
||||
ID int `db:"id"`
|
||||
Patient_UsersID string `db:"Patient_UsersID"`
|
||||
PatientMedrec string `db:"PatientMedrec"`
|
||||
PatientName string `db:"PatientName"`
|
||||
PatientDoB time.Time `db:"PatientDoB"`
|
||||
PatientCreatedAt time.Time `db:"PatientCreatedAt"`
|
||||
PatientUpdatedAt time.Time `db:"PatientUpdatedAt"`
|
||||
}
|
||||
|
||||
// PatientRepository handles database operations related to patients
|
||||
type PatientRepository struct {
|
||||
*Repository
|
||||
}
|
||||
|
||||
// NewPatientRepository creates a new patient repository
|
||||
func NewPatientRepository() *PatientRepository {
|
||||
return &PatientRepository{
|
||||
Repository: NewRepository(),
|
||||
}
|
||||
}
|
||||
|
||||
// GetPatientDetailsByUserID retrieves patient details for a user
|
||||
func (r *PatientRepository) GetPatientDetailsByUserID(userID string) (*models.PatientDetails, error) {
|
||||
var dbPatient DBPatient
|
||||
|
||||
query := `SELECT * FROM patient WHERE Patient_UsersID = ?`
|
||||
err := database.DB.Get(&dbPatient, query, userID)
|
||||
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("database error getting patient details: %w", err)
|
||||
}
|
||||
|
||||
// Create StudyRepository to get patient studies
|
||||
studyRepo := NewStudyRepository()
|
||||
studyUIDs, accessionNumbers, err := studyRepo.GetPatientStudies(dbPatient.PatientMedrec)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &models.PatientDetails{
|
||||
PatientID: dbPatient.PatientMedrec,
|
||||
PatientName: dbPatient.PatientName,
|
||||
StudyInstanceUIDs: studyUIDs,
|
||||
AccessionNumbers: accessionNumbers,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// CreatePatientTx creates a new patient record within a transaction
|
||||
func (r *PatientRepository) CreatePatientTx(tx *sqlx.Tx, patientRecord *models.PatientDetails, userID string) error {
|
||||
// Parse DOB to time.Time. 2006-1-02 = reference format YYYY-MM-DD in Go, not a default value
|
||||
dob, err := time.Parse("2006-01-02", patientRecord.DateOfBirth)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid date of birth format: %w", err)
|
||||
}
|
||||
|
||||
query := `INSERT INTO patient (Patient_UsersID, PatientMedrec, PatientName, PatientDoB, PatientCreatedAt, PatientUpdatedAt)
|
||||
VALUES (?, ?, ?, ?, NOW(), NOW())`
|
||||
|
||||
_, err = tx.Exec(query, userID, patientRecord.PatientID, patientRecord.PatientName, dob)
|
||||
if err != nil {
|
||||
return fmt.Errorf("database error creating patient: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
23
internal/api/repository/repository.go
Normal file
23
internal/api/repository/repository.go
Normal file
@@ -0,0 +1,23 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/database"
|
||||
"github.com/jmoiron/sqlx"
|
||||
)
|
||||
|
||||
// Repository provides a base interface to the database
|
||||
type Repository struct {
|
||||
db *sqlx.DB // Changed from *sql.DB to *sqlx.DB
|
||||
}
|
||||
|
||||
// NewRepository creates a new database repository
|
||||
func NewRepository() *Repository {
|
||||
return &Repository{
|
||||
db: database.DB,
|
||||
}
|
||||
}
|
||||
|
||||
// Close closes the database connection (no-op as DB is managed by database package)
|
||||
func (r *Repository) Close() error {
|
||||
return nil
|
||||
}
|
||||
167
internal/api/repository/shortlink.go
Normal file
167
internal/api/repository/shortlink.go
Normal file
@@ -0,0 +1,167 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/models"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/database"
|
||||
"github.com/jmoiron/sqlx"
|
||||
)
|
||||
|
||||
// DBShortLink represents a shortlink from the database
|
||||
type DBShortLink struct {
|
||||
ShortlinkID int `db:"ShortlinkID"`
|
||||
ShortlinkCode string `db:"ShortlinkCode"`
|
||||
Shortlink_PatientID string `db:"Shortlink_PatientID"`
|
||||
Shortlink_Study_IUID string `db:"Shortlink_Study_IUID"`
|
||||
ShortlinkHashDoB string `db:"ShortlinkHashDoB"`
|
||||
ShortlinkExpiredAt time.Time `db:"ShortlinkExpiredAt"`
|
||||
ShortlinkIsRevoked bool `db:"ShortlinkIsRevoked"`
|
||||
ShortlinkRemainingTries int `db:"ShortlinkRemainingTries"`
|
||||
ShortlinkCreatedAt time.Time `db:"ShortlinkCreatedAt"`
|
||||
ShortlinkCreate_UserID int `db:"ShortlinkCreate_UserID"`
|
||||
}
|
||||
|
||||
// ShortLinkRepository handles database operations related to shortlinks
|
||||
type ShortLinkRepository struct {
|
||||
*Repository
|
||||
}
|
||||
|
||||
// NewShortLinkRepository creates a new shortlink repository
|
||||
func NewShortLinkRepository() *ShortLinkRepository {
|
||||
return &ShortLinkRepository{
|
||||
Repository: NewRepository(),
|
||||
}
|
||||
}
|
||||
|
||||
// ToShortLink converts a DBShortLink to a ShortLink model
|
||||
func (s *DBShortLink) ToShortLink() *models.ShortLink {
|
||||
return &models.ShortLink{
|
||||
ID: fmt.Sprintf("%d", s.ShortlinkID),
|
||||
Token: s.ShortlinkCode,
|
||||
PatientID: s.Shortlink_PatientID,
|
||||
StudyUID: s.Shortlink_Study_IUID,
|
||||
HashedDOB: s.ShortlinkHashDoB,
|
||||
ExpiresAt: s.ShortlinkExpiredAt.Format(time.RFC3339),
|
||||
IsRevoked: s.ShortlinkIsRevoked,
|
||||
RemainingTries: s.ShortlinkRemainingTries,
|
||||
CreatedAt: s.ShortlinkCreatedAt.Format(time.RFC3339),
|
||||
CreatedByID: fmt.Sprintf("%d", s.ShortlinkCreate_UserID),
|
||||
}
|
||||
}
|
||||
|
||||
// GetShortLinkByToken retrieves a shortlink by token
|
||||
func (r *ShortLinkRepository) GetShortLinkByToken(token string) (*models.ShortLink, error) {
|
||||
var dbShortLink DBShortLink
|
||||
|
||||
query := `SELECT * FROM shortlink WHERE ShortlinkCode = ?`
|
||||
err := database.DB.Get(&dbShortLink, query, token)
|
||||
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("database error getting shortlink: %w", err)
|
||||
}
|
||||
|
||||
return dbShortLink.ToShortLink(), nil
|
||||
}
|
||||
|
||||
// CreateShortLinkTx stores a new shortlink in the database within a transaction
|
||||
func (r *ShortLinkRepository) CreateShortLinkTx(tx *sqlx.Tx, shortLink *models.ShortLink) error {
|
||||
query := `INSERT INTO shortlink (
|
||||
ShortlinkCode,
|
||||
Shortlink_PatientID,
|
||||
Shortlink_Study_IUID,
|
||||
ShortlinkHashDoB,
|
||||
ShortlinkExpiredAt,
|
||||
ShortlinkIsRevoked,
|
||||
ShortlinkRemainingTries,
|
||||
ShortlinkCreatedAt,
|
||||
ShortlinkCreate_UserID)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), ?)`
|
||||
|
||||
createdByID, err := strconv.Atoi(shortLink.CreatedByID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid created by ID: %w", err)
|
||||
}
|
||||
|
||||
expiresAt, err := time.Parse(time.RFC3339, shortLink.ExpiresAt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid expiration date: %w", err)
|
||||
}
|
||||
|
||||
_, err = tx.Exec(
|
||||
query,
|
||||
shortLink.Token,
|
||||
shortLink.PatientID,
|
||||
shortLink.StudyUID,
|
||||
shortLink.HashedDOB,
|
||||
expiresAt,
|
||||
shortLink.IsRevoked,
|
||||
shortLink.RemainingTries,
|
||||
createdByID,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("database error creating shortlink: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateShortLinkTx updates an existing shortlink in the database within a transaction
|
||||
func (r *ShortLinkRepository) UpdateShortLinkTx(tx *sqlx.Tx, shortLink *models.ShortLink) error {
|
||||
query := `UPDATE shortlink SET
|
||||
ShortlinkIsRevoked = ?,
|
||||
ShortlinkRemainingTries = ?,
|
||||
ShortlinkExpiredAt = ?
|
||||
WHERE ShortlinkCode = ?`
|
||||
|
||||
expiresAt, err := time.Parse(time.RFC3339, shortLink.ExpiresAt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid expiration date: %w", err)
|
||||
}
|
||||
|
||||
_, err = tx.Exec(
|
||||
query,
|
||||
shortLink.IsRevoked,
|
||||
shortLink.RemainingTries,
|
||||
expiresAt,
|
||||
shortLink.Token,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("database error updating shortlink: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetActiveShortLinkByPatientAndStudy retrieves an active (unexpired, not revoked) shortlink
|
||||
// for the given patient ID and study UID
|
||||
func (r *ShortLinkRepository) GetActiveShortLinkByPatientAndStudy(patientID string, studyUID string) (*models.ShortLink, error) {
|
||||
var dbShortLink DBShortLink
|
||||
|
||||
query := `SELECT * FROM shortlink
|
||||
WHERE Shortlink_PatientID = ?
|
||||
AND Shortlink_Study_IUID = ?
|
||||
AND ShortlinkExpiredAt > NOW()
|
||||
AND ShortlinkIsRevoked = FALSE
|
||||
ORDER BY ShortlinkExpiredAt DESC
|
||||
LIMIT 1`
|
||||
|
||||
err := database.DB.Get(&dbShortLink, query, patientID, studyUID)
|
||||
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("database error getting active shortlink: %w", err)
|
||||
}
|
||||
|
||||
return dbShortLink.ToShortLink(), nil
|
||||
}
|
||||
100
internal/api/repository/study.go
Normal file
100
internal/api/repository/study.go
Normal file
@@ -0,0 +1,100 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/models"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/database"
|
||||
"github.com/jmoiron/sqlx"
|
||||
)
|
||||
|
||||
// DBStudy represents a study from the database
|
||||
type DBStudy struct {
|
||||
ID int `db:"id"`
|
||||
Study_PatientID string `db:"Study_PatientID"`
|
||||
StudyIUID string `db:"StudyIUID"`
|
||||
StudyAccessionNumber string `db:"StudyAccessionNumber"`
|
||||
StudyDate time.Time `db:"StudyDate"`
|
||||
StudyCreatedAt time.Time `db:"StudyCreatedAt"`
|
||||
StudyUpdatedAt time.Time `db:"StudyUpdatedAt"`
|
||||
}
|
||||
|
||||
// StudyRepository handles database operations related to studies
|
||||
type StudyRepository struct {
|
||||
*Repository
|
||||
}
|
||||
|
||||
// NewStudyRepository creates a new study repository
|
||||
func NewStudyRepository() *StudyRepository {
|
||||
return &StudyRepository{
|
||||
Repository: NewRepository(),
|
||||
}
|
||||
}
|
||||
|
||||
// GetPatientStudies retrieves all studies for a patient
|
||||
func (r *StudyRepository) GetPatientStudies(patientID string) ([]string, []string, error) {
|
||||
var studies []DBStudy
|
||||
|
||||
query := `SELECT * FROM study WHERE Study_PatientID = ?`
|
||||
err := database.DB.Select(&studies, query, patientID)
|
||||
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("database error getting patient studies: %w", err)
|
||||
}
|
||||
|
||||
var studyUIDs []string
|
||||
var accessionNumbers []string
|
||||
|
||||
for _, study := range studies {
|
||||
studyUIDs = append(studyUIDs, study.StudyIUID)
|
||||
if study.StudyAccessionNumber != "" {
|
||||
accessionNumbers = append(accessionNumbers, study.StudyAccessionNumber)
|
||||
}
|
||||
}
|
||||
|
||||
return studyUIDs, accessionNumbers, nil
|
||||
}
|
||||
|
||||
// GetStudyByUID retrieves a study by its UID
|
||||
func (r *StudyRepository) GetStudyByUID(studyUID string) (*DBStudy, error) {
|
||||
var study DBStudy
|
||||
|
||||
query := `SELECT * FROM study WHERE StudyIUID = ?`
|
||||
err := database.DB.Get(&study, query, studyUID)
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("database error getting study: %w", err)
|
||||
}
|
||||
|
||||
return &study, nil
|
||||
}
|
||||
|
||||
// CreateStudyTx creates a new study record for a patient within a transaction
|
||||
func (r *StudyRepository) CreateStudyTx(tx *sqlx.Tx, patientID string, study models.Study) error {
|
||||
// Parse study date if provided
|
||||
var studyDate *time.Time
|
||||
if study.StudyDate != "" {
|
||||
parsedTime, err := time.Parse("2006-01-02", study.StudyDate)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid study date format: %w", err)
|
||||
}
|
||||
studyDate = &parsedTime
|
||||
}
|
||||
|
||||
query := `INSERT INTO study
|
||||
(Study_PatientID, StudyIUID, StudyAccessionNumber, StudyDate, StudyCreatedAt, StudyUpdatedAt)
|
||||
VALUES (?, ?, ?, ?, NOW(), NOW())`
|
||||
|
||||
_, err := tx.Exec(query,
|
||||
patientID,
|
||||
study.StudyInstanceUID,
|
||||
study.AccessionNumber,
|
||||
studyDate)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("database error creating study: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
169
internal/api/repository/user.go
Normal file
169
internal/api/repository/user.go
Normal file
@@ -0,0 +1,169 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/models"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/database"
|
||||
"github.com/jmoiron/sqlx"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// DBUser represents a user from the database
|
||||
type DBUser struct {
|
||||
UserID int `db:"UserID"`
|
||||
UserEmail string `db:"UserEmail"`
|
||||
UserPassword string `db:"UserPassword"`
|
||||
UserRole string `db:"UserRole"`
|
||||
UserName string `db:"UserName"`
|
||||
UserCreatedAt time.Time `db:"UserCreatedAt"`
|
||||
UserUpdatedAt time.Time `db:"UserUpdatedAt"`
|
||||
}
|
||||
|
||||
// DBRefreshToken represents a refresh token from the database
|
||||
type DBRefreshToken struct {
|
||||
ID int `db:"id"`
|
||||
Token string `db:"token"`
|
||||
UserID string `db:"user_id"`
|
||||
ExpiresAt time.Time `db:"expires_at"`
|
||||
IsRevoked bool `db:"is_revoked"`
|
||||
CreatedAt time.Time `db:"created_at"`
|
||||
}
|
||||
|
||||
// UserRepository handles database operations related to users
|
||||
type UserRepository struct {
|
||||
*Repository
|
||||
}
|
||||
|
||||
// NewUserRepository creates a new user repository
|
||||
func NewUserRepository() *UserRepository {
|
||||
return &UserRepository{
|
||||
Repository: NewRepository(),
|
||||
}
|
||||
}
|
||||
|
||||
// ToUser converts a DBUser to a User model
|
||||
func (u *DBUser) ToUser() *models.User {
|
||||
return &models.User{
|
||||
ID: fmt.Sprintf("%d", u.UserID),
|
||||
Email: u.UserEmail,
|
||||
Password: u.UserPassword,
|
||||
Role: u.UserRole,
|
||||
Name: u.UserName,
|
||||
CreatedAt: u.UserCreatedAt.Format(time.RFC3339),
|
||||
UpdatedAt: u.UserUpdatedAt.Format(time.RFC3339),
|
||||
}
|
||||
}
|
||||
|
||||
// GetUserByEmail retrieves a user by email
|
||||
func (r *UserRepository) GetUserByEmail(email string) (*models.User, error) {
|
||||
var dbUser DBUser
|
||||
|
||||
query := `SELECT * FROM user WHERE UserEmail = ?`
|
||||
err := database.DB.Get(&dbUser, query, email)
|
||||
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("database error getting user by email: %w", err)
|
||||
}
|
||||
|
||||
return dbUser.ToUser(), nil
|
||||
}
|
||||
|
||||
// GetUserByID retrieves a user by ID
|
||||
func (r *UserRepository) GetUserByID(id string) (*models.User, error) {
|
||||
var dbUser DBUser
|
||||
|
||||
query := `SELECT * FROM user WHERE UserID = ?`
|
||||
err := database.DB.Get(&dbUser, query, id)
|
||||
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("database error getting user by ID: %w", err)
|
||||
}
|
||||
|
||||
return dbUser.ToUser(), nil
|
||||
}
|
||||
|
||||
// StoreRefreshToken saves a refresh token to the database
|
||||
func (r *UserRepository) StoreRefreshToken(userID string, token string, expiresAt time.Time) error {
|
||||
query := `INSERT INTO refresh_tokens (token, user_id, expires_at, is_revoked, created_at)
|
||||
VALUES (?, ?, ?, false, NOW())`
|
||||
|
||||
_, err := database.DB.Exec(query, token, userID, expiresAt)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("database error storing refresh token: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetRefreshToken retrieves a refresh token from the database
|
||||
func (r *UserRepository) GetRefreshToken(token string) (*models.RefreshToken, error) {
|
||||
var dbToken DBRefreshToken
|
||||
|
||||
query := `SELECT * FROM refresh_tokens WHERE token = ?`
|
||||
err := database.DB.Get(&dbToken, query, token)
|
||||
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("database error getting refresh token: %w", err)
|
||||
}
|
||||
|
||||
return &models.RefreshToken{
|
||||
ID: fmt.Sprintf("%d", dbToken.ID),
|
||||
UserID: dbToken.UserID,
|
||||
Token: dbToken.Token,
|
||||
ExpiresAt: dbToken.ExpiresAt.Format(time.RFC3339),
|
||||
IsRevoked: dbToken.IsRevoked,
|
||||
CreatedAt: dbToken.CreatedAt.Format(time.RFC3339),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// RevokeRefreshToken marks a refresh token as revoked
|
||||
func (r *UserRepository) RevokeRefreshToken(token string) error {
|
||||
query := `UPDATE refresh_tokens SET is_revoked = true WHERE token = ?`
|
||||
_, err := database.DB.Exec(query, token)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("database error revoking refresh token: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreateUserTx creates a new user within a transaction
|
||||
func (r *UserRepository) CreateUserTx(tx *sqlx.Tx, user *models.User) error {
|
||||
// Hash the password before storing
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(user.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to hash password: %w", err)
|
||||
}
|
||||
|
||||
query := `INSERT INTO user (UserEmail, UserPassword, UserRole, UserName, UserCreatedAt, UserUpdatedAt)
|
||||
VALUES (?, ?, ?, ?, NOW(), NOW())`
|
||||
|
||||
result, err := tx.Exec(query, user.Email, string(hashedPassword), user.Role, user.Name)
|
||||
if err != nil {
|
||||
return fmt.Errorf("database error creating user: %w", err)
|
||||
}
|
||||
|
||||
// Get the last inserted ID
|
||||
id, err := result.LastInsertId()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get last insert ID: %w", err)
|
||||
}
|
||||
|
||||
// Update the user ID
|
||||
user.ID = fmt.Sprintf("%d", id)
|
||||
return nil
|
||||
}
|
||||
142
internal/api/routes.go
Normal file
142
internal/api/routes.go
Normal file
@@ -0,0 +1,142 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/config"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/handlers"
|
||||
apiMiddleware "devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/middleware"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/service"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/auth"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/proxy"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/go-chi/cors"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// SetupRouter configures and returns the API router
|
||||
func SetupRouter(cfg *config.Config, logger *zap.Logger) http.Handler {
|
||||
r := chi.NewRouter()
|
||||
|
||||
// Base middleware
|
||||
r.Use(middleware.RequestID)
|
||||
r.Use(middleware.RealIP)
|
||||
r.Use(middleware.Recoverer)
|
||||
r.Use(apiMiddleware.Logger(logger))
|
||||
|
||||
// CORS configuration
|
||||
r.Use(cors.Handler(cors.Options{
|
||||
AllowedOrigins: []string{"*"}, // In production, restrict this to your frontend domains
|
||||
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
|
||||
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token", "X-Requested-With"},
|
||||
ExposedHeaders: []string{"Link", "Content-Length", "Content-Disposition", "Content-Type"},
|
||||
AllowCredentials: true,
|
||||
MaxAge: 300, // Maximum value not ignored by any of major browsers
|
||||
}))
|
||||
|
||||
r.Options("/*", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
|
||||
// Initialize Google auth client for proxy
|
||||
googleAuth, err := auth.NewGoogleClient(cfg.Google.CredentialsPath)
|
||||
if err != nil {
|
||||
logger.Fatal("Failed to initialize Google auth client", zap.Error(err))
|
||||
}
|
||||
|
||||
// Initialize Healthcare API client
|
||||
healthcareClient := proxy.NewClient(googleAuth, cfg.Google)
|
||||
|
||||
// Initialize JWT auth service
|
||||
jwtSecret := cfg.Auth.JWTSecret
|
||||
if jwtSecret == "" {
|
||||
logger.Warn("JWT secret not provided in config, using default value. This is insecure for production!")
|
||||
jwtSecret = "vQ6PQqUyh7pBNOytClgN+Nw1XBq7F8Qo6VP3VwIqvHY="
|
||||
}
|
||||
|
||||
// Convert config values to time.Duration
|
||||
accessExpiry := time.Duration(cfg.Auth.AccessTokenExpiry) * time.Minute
|
||||
refreshExpiry := time.Duration(cfg.Auth.RefreshTokenExpiry) * time.Hour
|
||||
|
||||
// Create JWT manager with config values
|
||||
jwtManager := auth.NewJWTManager(jwtSecret, accessExpiry, refreshExpiry)
|
||||
|
||||
// Initialize services with domain-specific repositories
|
||||
authService := service.NewAuthService(jwtManager)
|
||||
|
||||
// Initialize shortlink service with config values
|
||||
shortLinkService := service.NewShortLinkService(
|
||||
jwtManager,
|
||||
logger,
|
||||
cfg.Shortlink.BaseURL,
|
||||
cfg.Shortlink.DefaultExpiryHours,
|
||||
cfg.Shortlink.MaxAttempts,
|
||||
)
|
||||
|
||||
// Public routes that don't require authentication
|
||||
r.Group(func(r chi.Router) {
|
||||
// Health check
|
||||
r.Get("/health", handlers.HealthCheck)
|
||||
|
||||
// Authentication endpoints
|
||||
r.Route("/auth", func(r chi.Router) {
|
||||
authHandler := handlers.NewAuthHandler(logger, authService)
|
||||
r.Post("/login", authHandler.Login)
|
||||
r.Post("/refresh", authHandler.RefreshToken)
|
||||
r.Post("/logout", authHandler.Logout)
|
||||
|
||||
// Registration endpoint
|
||||
registerService := service.NewRegisterService(logger)
|
||||
registerHandler := handlers.NewRegisterHandler(logger, registerService)
|
||||
r.Post("/register", registerHandler.Register)
|
||||
|
||||
// ShortLink authentication - no auth required
|
||||
shortLinkHandler := handlers.NewShortLinkHandler(logger, shortLinkService)
|
||||
r.Post("/shortlink", shortLinkHandler.ShortLinkAuth)
|
||||
})
|
||||
})
|
||||
|
||||
// Protected routes that require authentication
|
||||
r.Group(func(r chi.Router) {
|
||||
// Apply authentication middleware
|
||||
r.Use(apiMiddleware.Auth(authService, logger))
|
||||
|
||||
// Shortlink generation - only for admin and expertise_doctor roles
|
||||
shortLinkHandler := handlers.NewShortLinkHandler(logger, shortLinkService)
|
||||
r.Post("/generate-link", shortLinkHandler.GenerateShortLink)
|
||||
|
||||
// DICOM Web routes
|
||||
r.Route("/dicomWeb", func(r chi.Router) {
|
||||
// Add audit logging middleware to DICOM routes
|
||||
r.Use(apiMiddleware.AuditLog(logger))
|
||||
|
||||
// Add patient view restriction for patient role
|
||||
r.Use(apiMiddleware.PatientViewRestriction(logger))
|
||||
|
||||
// Create handler for all DICOM requests
|
||||
dicomHandler := handlers.NewDicomHandler(healthcareClient, logger)
|
||||
|
||||
// Common routes for studies with role-specific handling
|
||||
r.Route("/studies", func(r chi.Router) {
|
||||
// StudyInstanceUID parameter routes - accessible by all roles
|
||||
r.Get("/{studyInstanceUID}", dicomHandler.ForwardRequest) // Study details
|
||||
r.Get("/{studyInstanceUID}/series", dicomHandler.ForwardRequest) // Series list for study
|
||||
|
||||
// Deep hierarchy routes - accessible by patients and all doctors
|
||||
r.Get("/{studyInstanceUID}/series/{seriesUID}/metadata", dicomHandler.ForwardRequest)
|
||||
r.Get("/{studyInstanceUID}/series/{seriesUID}/instances/{instanceUID}/frames/{frame}", dicomHandler.ForwardRequest)
|
||||
|
||||
// Query routes - accessible by all roles
|
||||
r.Get("/", dicomHandler.ForwardRequest) // Study list with filters
|
||||
})
|
||||
|
||||
// Expertise doctors have full access to all DICOM endpoints
|
||||
r.With(apiMiddleware.RoleRequired("expertise_doctor")).HandleFunc("/*", dicomHandler.ForwardRequest)
|
||||
})
|
||||
})
|
||||
|
||||
return r
|
||||
}
|
||||
232
internal/api/service/auth_service.go
Normal file
232
internal/api/service/auth_service.go
Normal file
@@ -0,0 +1,232 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/models"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/repository"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/auth"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidCredentials = errors.New("invalid credentials")
|
||||
ErrUserNotFound = errors.New("user not found")
|
||||
)
|
||||
|
||||
// AuthService handles authentication operations
|
||||
type AuthService struct {
|
||||
jwtManager *auth.JWTManager
|
||||
userRepo *repository.UserRepository
|
||||
patientRepo *repository.PatientRepository
|
||||
}
|
||||
|
||||
// NewAuthService creates a new authentication service
|
||||
func NewAuthService(jwtManager *auth.JWTManager) *AuthService {
|
||||
return &AuthService{
|
||||
jwtManager: jwtManager,
|
||||
userRepo: repository.NewUserRepository(),
|
||||
patientRepo: repository.NewPatientRepository(),
|
||||
}
|
||||
}
|
||||
|
||||
// Login authenticates a user and generates tokens
|
||||
func (s *AuthService) Login(email, password string) (*models.LoginResponse, error) {
|
||||
// Find user in database
|
||||
user, err := s.userRepo.GetUserByEmail(email)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error finding user: %w", err)
|
||||
}
|
||||
|
||||
if user == nil {
|
||||
return nil, ErrUserNotFound
|
||||
}
|
||||
|
||||
// Verify password
|
||||
if err := CheckPassword(password, user.Password); err != nil {
|
||||
return nil, ErrInvalidCredentials
|
||||
}
|
||||
|
||||
// Create token claims based on user role
|
||||
additionalClaims := make(map[string]interface{})
|
||||
var redirectURL string
|
||||
|
||||
switch user.Role {
|
||||
case "patient":
|
||||
// Get patient data
|
||||
patientData, err := s.patientRepo.GetPatientDetailsByUserID(user.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error getting patient details: %w", err)
|
||||
}
|
||||
|
||||
if patientData == nil {
|
||||
return nil, ErrUserNotFound
|
||||
}
|
||||
|
||||
// Set patient-specific claims
|
||||
additionalClaims["patient_id"] = patientData.PatientID
|
||||
additionalClaims["patient_name"] = patientData.PatientName
|
||||
additionalClaims["study_iuids"] = patientData.StudyInstanceUIDs
|
||||
additionalClaims["accession_numbers"] = patientData.AccessionNumbers
|
||||
|
||||
// For redirectURL and home_url, use first study for simplicity
|
||||
if len(patientData.StudyInstanceUIDs) > 0 {
|
||||
additionalClaims["home_url"] = fmt.Sprintf("viewer?StudyInstanceUIDs=%s", patientData.StudyInstanceUIDs[0])
|
||||
redirectURL = fmt.Sprintf("/viewer?StudyInstanceUIDs=%s", patientData.StudyInstanceUIDs[0])
|
||||
} else {
|
||||
// Fallback for empty studies array
|
||||
additionalClaims["home_url"] = "/"
|
||||
redirectURL = "/"
|
||||
}
|
||||
|
||||
additionalClaims["study_list"] = "disabled"
|
||||
|
||||
case "ref_doctor":
|
||||
// Set referring doctor claims
|
||||
encodedName := url.QueryEscape(user.Name)
|
||||
filterURL := fmt.Sprintf("studies?limit=101&offset=0&fuzzymatching=false&includefield=00081030,00080060,00080090&00080090=%s", encodedName)
|
||||
|
||||
additionalClaims["home_url"] = "/"
|
||||
additionalClaims["study_list"] = "enabled"
|
||||
additionalClaims["filter_url"] = filterURL
|
||||
|
||||
redirectURL = "/"
|
||||
|
||||
case "expertise_doctor", "admin":
|
||||
// Expertise doctors have full access
|
||||
additionalClaims["home_url"] = "/"
|
||||
additionalClaims["study_list"] = "enabled"
|
||||
|
||||
redirectURL = "/"
|
||||
}
|
||||
|
||||
// TODO: Apakah kita perlu param email untuk generate access token?
|
||||
// Generate tokens
|
||||
accessToken, err := s.jwtManager.GenerateAccessToken(user.ID, user.Email, user.Role, user.Name, additionalClaims)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
refreshToken, err := s.jwtManager.GenerateRefreshToken(user.ID, user.Email, user.Role, user.Name, additionalClaims)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Store refresh token in database
|
||||
expiresAt := time.Now().Add(s.jwtManager.GetRefreshExpiry())
|
||||
if err := s.userRepo.StoreRefreshToken(user.ID, refreshToken, expiresAt); err != nil {
|
||||
return nil, fmt.Errorf("failed to store refresh token: %w", err)
|
||||
}
|
||||
|
||||
return &models.LoginResponse{
|
||||
AccessToken: accessToken,
|
||||
RefreshToken: refreshToken,
|
||||
User: user,
|
||||
RedirectURL: redirectURL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// RefreshToken generates a new access token using a refresh token
|
||||
func (s *AuthService) RefreshToken(refreshToken string) (string, error) {
|
||||
// Check if token exists and is not revoked
|
||||
dbToken, err := s.userRepo.GetRefreshToken(refreshToken)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to get refresh token: %w", err)
|
||||
}
|
||||
|
||||
if dbToken == nil || dbToken.IsRevoked {
|
||||
return "", errors.New("invalid or revoked refresh token")
|
||||
}
|
||||
|
||||
// Parse expiry time
|
||||
expiresAt, err := time.Parse(time.RFC3339, dbToken.ExpiresAt)
|
||||
if err != nil {
|
||||
return "", errors.New("invalid token expiry format")
|
||||
}
|
||||
|
||||
// Check if token is expired
|
||||
if time.Now().After(expiresAt) {
|
||||
return "", auth.ErrExpiredToken
|
||||
}
|
||||
|
||||
// Validate the refresh token
|
||||
claims, err := s.jwtManager.ValidateToken(refreshToken)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// Check if token is a refresh token
|
||||
if claims.TokenType != "refresh" {
|
||||
return "", errors.New("invalid token type")
|
||||
}
|
||||
|
||||
// Build additionalClaims from the refresh token
|
||||
additionalClaims := make(map[string]interface{})
|
||||
|
||||
// Add string claims
|
||||
if claims.PatientID != "" {
|
||||
additionalClaims["patient_id"] = claims.PatientID
|
||||
}
|
||||
if claims.PatientName != "" {
|
||||
additionalClaims["patient_name"] = claims.PatientName
|
||||
}
|
||||
if claims.HomeURL != "" {
|
||||
additionalClaims["home_url"] = claims.HomeURL
|
||||
}
|
||||
if claims.StudyList != "" {
|
||||
additionalClaims["study_list"] = claims.StudyList
|
||||
}
|
||||
if claims.FilterURL != "" {
|
||||
additionalClaims["filter_url"] = claims.FilterURL
|
||||
}
|
||||
|
||||
// Add array claims
|
||||
if len(claims.StudyIUIDs) > 0 {
|
||||
additionalClaims["study_iuids"] = claims.StudyIUIDs
|
||||
}
|
||||
if len(claims.AccessionNumbers) > 0 {
|
||||
additionalClaims["accession_numbers"] = claims.AccessionNumbers
|
||||
}
|
||||
|
||||
// Generate a new access token with the same claims
|
||||
accessToken, err := s.jwtManager.GenerateAccessToken(
|
||||
claims.UserID,
|
||||
claims.Email,
|
||||
claims.Role,
|
||||
claims.UserName,
|
||||
additionalClaims,
|
||||
)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return accessToken, nil
|
||||
}
|
||||
|
||||
// ValidateToken validates a token and returns the claims
|
||||
func (s *AuthService) ValidateToken(token string) (*auth.CustomClaims, error) {
|
||||
return s.jwtManager.ValidateToken(token)
|
||||
}
|
||||
|
||||
// Logout revokes a refresh token
|
||||
func (s *AuthService) Logout(refreshToken string) error {
|
||||
return s.userRepo.RevokeRefreshToken(refreshToken)
|
||||
}
|
||||
|
||||
// HashPassword hashes a password using bcrypt
|
||||
func HashPassword(password string) (string, error) {
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(hashedPassword), nil
|
||||
}
|
||||
|
||||
// CheckPassword compares a password with a hash
|
||||
func CheckPassword(password, hash string) error {
|
||||
return bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
||||
}
|
||||
165
internal/api/service/register_service.go
Normal file
165
internal/api/service/register_service.go
Normal file
@@ -0,0 +1,165 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/models"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/repository"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/database"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrEmailExists = errors.New("email already exists")
|
||||
ErrUserNotCreated = errors.New("failed to create user")
|
||||
ErrInvalidRole = errors.New("invalid user role")
|
||||
ErrInvalidPatient = errors.New("invalid patient data")
|
||||
ErrInvalidDoctor = errors.New("invalid doctor data")
|
||||
ErrTransaction = errors.New("transaction error")
|
||||
)
|
||||
|
||||
// RegisterRequest represents a user registration request
|
||||
type RegisterRequest struct {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
Name string `json:"name"`
|
||||
Role string `json:"role"` // "patient", "ref_doctor", "expertise_doctor", or "admin"
|
||||
Patient *models.PatientDetails `json:"patient,omitempty"`
|
||||
Doctor *models.DoctorDetails `json:"doctor,omitempty"`
|
||||
Studies []models.Study `json:"studies,omitempty"` // Study records for patient
|
||||
}
|
||||
|
||||
// RegisterService handles user registration
|
||||
type RegisterService struct {
|
||||
userRepo *repository.UserRepository
|
||||
patientRepo *repository.PatientRepository
|
||||
doctorRepo *repository.DoctorRepository
|
||||
studyRepo *repository.StudyRepository
|
||||
logger *zap.Logger
|
||||
}
|
||||
|
||||
// NewRegisterService creates a new register service
|
||||
func NewRegisterService(logger *zap.Logger) *RegisterService {
|
||||
if logger == nil {
|
||||
// If no logger is provided, create a no-op logger
|
||||
logger = zap.NewNop()
|
||||
}
|
||||
|
||||
return &RegisterService{
|
||||
userRepo: repository.NewUserRepository(),
|
||||
patientRepo: repository.NewPatientRepository(),
|
||||
doctorRepo: repository.NewDoctorRepository(),
|
||||
studyRepo: repository.NewStudyRepository(),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// Register creates a new user with their associated role-specific data
|
||||
func (s *RegisterService) Register(req *RegisterRequest) (*models.User, error) {
|
||||
// Validate role
|
||||
if req.Role != "patient" && req.Role != "ref_doctor" && req.Role != "expertise_doctor" && req.Role != "admin" {
|
||||
return nil, ErrInvalidRole
|
||||
}
|
||||
|
||||
// Check role-specific data
|
||||
if req.Role == "patient" && (req.Patient == nil || req.Patient.PatientID == "" || req.Patient.DateOfBirth == "") {
|
||||
return nil, ErrInvalidPatient
|
||||
}
|
||||
|
||||
if (req.Role == "ref_doctor" || req.Role == "expertise_doctor") && (req.Doctor == nil || req.Doctor.DoctorID == "") {
|
||||
return nil, ErrInvalidDoctor
|
||||
}
|
||||
|
||||
// Check if email already exists - do this outside the transaction
|
||||
existingUser, err := s.userRepo.GetUserByEmail(req.Email)
|
||||
if err != nil && err != sql.ErrNoRows {
|
||||
return nil, fmt.Errorf("error checking existing user: %w", err)
|
||||
}
|
||||
|
||||
if existingUser != nil {
|
||||
return nil, ErrEmailExists
|
||||
}
|
||||
|
||||
// Start a transaction
|
||||
tx, err := database.DB.Beginx()
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to begin transaction", zap.Error(err))
|
||||
return nil, fmt.Errorf("%w: failed to begin transaction", ErrTransaction)
|
||||
}
|
||||
|
||||
// Ensure the transaction is rolled back if we return an error
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
s.logger.Error("Panic in transaction", zap.Any("recover", r))
|
||||
tx.Rollback()
|
||||
panic(r) // re-throw the panic after cleanup
|
||||
}
|
||||
}()
|
||||
|
||||
// Create user
|
||||
newUser := &models.User{
|
||||
Email: req.Email,
|
||||
Password: req.Password, // Will be hashed in repository
|
||||
Role: req.Role,
|
||||
Name: req.Name,
|
||||
}
|
||||
|
||||
// Use the transaction for user creation
|
||||
if err := s.userRepo.CreateUserTx(tx, newUser); err != nil {
|
||||
s.logger.Error("Failed to create user", zap.Error(err), zap.String("email", req.Email))
|
||||
tx.Rollback()
|
||||
return nil, fmt.Errorf("error creating user: %w", err)
|
||||
}
|
||||
|
||||
// Create role-specific data
|
||||
if req.Role == "patient" {
|
||||
err = s.patientRepo.CreatePatientTx(tx, req.Patient, newUser.ID)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to create patient", zap.Error(err), zap.String("patientID", req.Patient.PatientID))
|
||||
tx.Rollback()
|
||||
return nil, fmt.Errorf("error creating patient: %w", err)
|
||||
}
|
||||
|
||||
// Create associated study records if provided
|
||||
if len(req.Studies) > 0 {
|
||||
for _, study := range req.Studies {
|
||||
if study.StudyInstanceUID == "" {
|
||||
continue // Skip studies without UIDs
|
||||
}
|
||||
|
||||
err = s.studyRepo.CreateStudyTx(tx, req.Patient.PatientID, study)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to create study",
|
||||
zap.Error(err),
|
||||
zap.String("patientID", req.Patient.PatientID),
|
||||
zap.String("studyUID", study.StudyInstanceUID))
|
||||
tx.Rollback()
|
||||
return nil, fmt.Errorf("error creating study for patient: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if req.Role == "ref_doctor" || req.Role == "expertise_doctor" {
|
||||
err = s.doctorRepo.CreateDoctorTx(tx, req.Doctor, newUser.ID)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to create doctor", zap.Error(err), zap.String("doctorID", req.Doctor.DoctorID))
|
||||
tx.Rollback()
|
||||
return nil, fmt.Errorf("error creating doctor: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Commit the transaction
|
||||
if err := tx.Commit(); err != nil {
|
||||
s.logger.Error("Failed to commit transaction", zap.Error(err))
|
||||
tx.Rollback() // This is actually redundant as the transaction will be rolled back on failure
|
||||
return nil, fmt.Errorf("%w: failed to commit transaction", ErrTransaction)
|
||||
}
|
||||
|
||||
s.logger.Info("Successfully registered new user",
|
||||
zap.String("email", req.Email),
|
||||
zap.String("role", req.Role),
|
||||
zap.String("userID", newUser.ID))
|
||||
|
||||
return newUser, nil
|
||||
}
|
||||
435
internal/api/service/shortlink_service.go
Normal file
435
internal/api/service/shortlink_service.go
Normal file
@@ -0,0 +1,435 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/models"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/repository"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/auth"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/database"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultShortLinkExpiry is the default expiration time for short links (72 hours)
|
||||
DefaultShortLinkExpiry = 72 * time.Hour
|
||||
|
||||
// DefaultMaxTries is the default number of login attempts allowed for a shortlink
|
||||
DefaultMaxTries = 5
|
||||
|
||||
// ShortTokenLength is the length of the generated short token
|
||||
ShortTokenLength = 8
|
||||
)
|
||||
|
||||
var (
|
||||
ErrShortLinkNotFound = errors.New("short link not found or expired")
|
||||
ErrInvalidDOB = errors.New("invalid date of birth")
|
||||
ErrShortLinkExpired = errors.New("short link has expired")
|
||||
ErrTooManyAttempts = errors.New("too many failed attempts")
|
||||
ErrCreationFailed = errors.New("failed to create short link")
|
||||
ErrInvalidStudyUID = errors.New("invalid or missing StudyInstanceUID")
|
||||
ErrAdminRoleRequired = errors.New("admin role required to generate shortlinks")
|
||||
)
|
||||
|
||||
// ShortLinkService handles operations related to short links
|
||||
type ShortLinkService struct {
|
||||
jwtManager *auth.JWTManager
|
||||
logger *zap.Logger
|
||||
shortLinkRepo *repository.ShortLinkRepository
|
||||
patientRepo *repository.PatientRepository
|
||||
// Configuration settings
|
||||
baseURL string
|
||||
defaultExpiryTime time.Duration
|
||||
maxAttempts int
|
||||
}
|
||||
|
||||
// NewShortLinkService creates a new short link service
|
||||
func NewShortLinkService(jwtManager *auth.JWTManager, logger *zap.Logger, baseURL string, defaultExpiryHours int, maxAttempts int) *ShortLinkService {
|
||||
// Set default values if not provided
|
||||
if baseURL == "" {
|
||||
baseURL = "http://localhost:3000"
|
||||
}
|
||||
|
||||
if defaultExpiryHours <= 0 {
|
||||
defaultExpiryHours = 72 // Default to 72 hours if not specified
|
||||
}
|
||||
|
||||
if maxAttempts <= 0 {
|
||||
maxAttempts = 5 // Default to 5 attempts if not specified
|
||||
}
|
||||
|
||||
return &ShortLinkService{
|
||||
jwtManager: jwtManager,
|
||||
logger: logger,
|
||||
shortLinkRepo: repository.NewShortLinkRepository(),
|
||||
patientRepo: repository.NewPatientRepository(),
|
||||
baseURL: baseURL,
|
||||
defaultExpiryTime: time.Duration(defaultExpiryHours) * time.Hour,
|
||||
maxAttempts: maxAttempts,
|
||||
}
|
||||
}
|
||||
|
||||
// GenerateShortLink creates a new short link for patient and study access
|
||||
func (s *ShortLinkService) GenerateShortLink(req *models.GenerateShortLinkRequest, creatorID string) (*models.GenerateShortLinkResponse, error) {
|
||||
// Validate inputs
|
||||
if req.PatientID == "" {
|
||||
return nil, errors.New("patient ID is required")
|
||||
}
|
||||
if req.StudyUID == "" {
|
||||
return nil, ErrInvalidStudyUID
|
||||
}
|
||||
if req.DOB == "" {
|
||||
return nil, errors.New("date of birth is required")
|
||||
}
|
||||
|
||||
// Normalize DOB format (ensure YYYY-MM-DD)
|
||||
dob := normalizeDOB(req.DOB)
|
||||
if !isValidDOBFormat(dob) {
|
||||
return nil, errors.New("invalid date of birth format, expected YYYY-MM-DD")
|
||||
}
|
||||
|
||||
// Check if an unexpired shortlink already exists for this patient and study
|
||||
existingShortLink, err := s.shortLinkRepo.GetActiveShortLinkByPatientAndStudy(req.PatientID, req.StudyUID)
|
||||
if err != nil {
|
||||
s.logger.Error("Error checking for existing shortlinks", zap.Error(err))
|
||||
return nil, ErrCreationFailed
|
||||
}
|
||||
|
||||
// If an active shortlink exists, return it instead of creating a new one
|
||||
if existingShortLink != nil {
|
||||
s.logger.Info("Returning existing active shortlink",
|
||||
zap.String("patientID", req.PatientID),
|
||||
zap.String("studyUID", req.StudyUID),
|
||||
zap.String("token", existingShortLink.Token))
|
||||
|
||||
// Generate the full URL using the configured base URL
|
||||
fullURL := fmt.Sprintf("%s/short-auth?short=%s", s.baseURL, existingShortLink.Token)
|
||||
|
||||
return &models.GenerateShortLinkResponse{
|
||||
ShortToken: existingShortLink.Token,
|
||||
FullURL: fullURL,
|
||||
ExpiresAt: existingShortLink.ExpiresAt,
|
||||
IsExisting: true,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Set expiration if not provided
|
||||
expiresIn := s.defaultExpiryTime
|
||||
if req.ExpiresIn > 0 {
|
||||
expiresIn = time.Duration(req.ExpiresIn) * time.Hour
|
||||
}
|
||||
expiresAt := time.Now().Add(expiresIn)
|
||||
|
||||
// Generate a secure random token
|
||||
token, err := generateSecureToken(ShortTokenLength)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to generate secure token", zap.Error(err))
|
||||
return nil, ErrCreationFailed
|
||||
}
|
||||
|
||||
// Hash the DOB for secure storage
|
||||
hashedDOB := hashDOB(dob)
|
||||
|
||||
// Create the short link record
|
||||
shortLink := &models.ShortLink{
|
||||
ID: generateID(),
|
||||
Token: token,
|
||||
PatientID: req.PatientID,
|
||||
StudyUID: req.StudyUID,
|
||||
HashedDOB: hashedDOB,
|
||||
ExpiresAt: expiresAt.Format(time.RFC3339),
|
||||
IsRevoked: false,
|
||||
CreatedAt: time.Now().Format(time.RFC3339),
|
||||
CreatedByID: creatorID,
|
||||
RemainingTries: s.maxAttempts,
|
||||
}
|
||||
|
||||
// Start a transaction for creating the shortlink
|
||||
tx, err := database.DB.Beginx()
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to start transaction", zap.Error(err))
|
||||
return nil, fmt.Errorf("database error: %w", err)
|
||||
}
|
||||
|
||||
// Set up deferred rollback that will be canceled if we commit
|
||||
defer func() {
|
||||
if tx != nil {
|
||||
tx.Rollback()
|
||||
}
|
||||
}()
|
||||
|
||||
// Store the short link in the database using transaction
|
||||
err = s.shortLinkRepo.CreateShortLinkTx(tx, shortLink)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to store shortlink in database", zap.Error(err))
|
||||
return nil, ErrCreationFailed
|
||||
}
|
||||
|
||||
// Commit the transaction
|
||||
if err = tx.Commit(); err != nil {
|
||||
s.logger.Error("Failed to commit transaction", zap.Error(err))
|
||||
return nil, errors.New("database error")
|
||||
}
|
||||
|
||||
// Clear the tx to prevent the deferred rollback
|
||||
tx = nil
|
||||
|
||||
// Generate the full URL using the configured base URL
|
||||
fullURL := fmt.Sprintf("%s/short-auth?short=%s", s.baseURL, token)
|
||||
|
||||
return &models.GenerateShortLinkResponse{
|
||||
ShortToken: token,
|
||||
FullURL: fullURL,
|
||||
ExpiresAt: shortLink.ExpiresAt,
|
||||
IsExisting: false,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ValidateShortLink validates a short link token and DOB
|
||||
func (s *ShortLinkService) ValidateShortLink(req *models.ShortLinkAuthRequest) (*models.ShortLink, error) {
|
||||
// Get the token using the helper method that handles both field names
|
||||
token := req.GetToken()
|
||||
|
||||
// Find the short link in the database
|
||||
shortLink, err := s.shortLinkRepo.GetShortLinkByToken(token)
|
||||
if err != nil {
|
||||
s.logger.Error("Error retrieving shortlink", zap.Error(err), zap.String("token", token))
|
||||
return nil, ErrShortLinkNotFound
|
||||
}
|
||||
|
||||
if shortLink == nil {
|
||||
return nil, ErrShortLinkNotFound
|
||||
}
|
||||
|
||||
// Check if expired
|
||||
expiresAt, err := time.Parse(time.RFC3339, shortLink.ExpiresAt)
|
||||
if err != nil || time.Now().After(expiresAt) {
|
||||
return nil, ErrShortLinkExpired
|
||||
}
|
||||
|
||||
// Check if revoked
|
||||
if shortLink.IsRevoked {
|
||||
return nil, ErrShortLinkNotFound
|
||||
}
|
||||
|
||||
// Check remaining tries
|
||||
if shortLink.RemainingTries <= 0 {
|
||||
return nil, ErrTooManyAttempts
|
||||
}
|
||||
|
||||
// Normalize and hash the provided DOB
|
||||
dob := normalizeDOB(req.DOB)
|
||||
if !isValidDOBFormat(dob) {
|
||||
// Use a transaction for updating the tries counter
|
||||
tx, err := database.DB.Beginx()
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to start transaction", zap.Error(err))
|
||||
return nil, fmt.Errorf("database error: %w", err)
|
||||
}
|
||||
|
||||
// Set up deferred rollback that will be canceled if we commit
|
||||
defer func() {
|
||||
if tx != nil {
|
||||
tx.Rollback()
|
||||
}
|
||||
}()
|
||||
|
||||
// Decrement remaining tries on invalid format
|
||||
shortLink.RemainingTries--
|
||||
|
||||
// Update the shortlink in the database using the transaction
|
||||
err = s.shortLinkRepo.UpdateShortLinkTx(tx, shortLink)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to update shortlink tries", zap.Error(err))
|
||||
return nil, errors.New("invalid date of birth format, expected YYYY-MM-DD")
|
||||
}
|
||||
|
||||
// Commit the transaction
|
||||
if err = tx.Commit(); err != nil {
|
||||
s.logger.Error("Failed to commit transaction", zap.Error(err))
|
||||
return nil, errors.New("database error")
|
||||
}
|
||||
|
||||
// Clear the tx to prevent the deferred rollback
|
||||
tx = nil
|
||||
|
||||
return nil, errors.New("invalid date of birth format, expected YYYY-MM-DD")
|
||||
}
|
||||
|
||||
hashedDOB := hashDOB(dob)
|
||||
|
||||
// Start a transaction for updating the tries counter
|
||||
tx, err := database.DB.Beginx()
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to start transaction", zap.Error(err))
|
||||
return nil, fmt.Errorf("database error: %w", err)
|
||||
}
|
||||
|
||||
// Set up deferred rollback that will be canceled if we commit
|
||||
defer func() {
|
||||
if tx != nil {
|
||||
tx.Rollback()
|
||||
}
|
||||
}()
|
||||
|
||||
// Verify the DOB
|
||||
if hashedDOB != shortLink.HashedDOB {
|
||||
// Decrement remaining tries on failed verification
|
||||
shortLink.RemainingTries--
|
||||
|
||||
// Update the shortlink in the database using the transaction
|
||||
err = s.shortLinkRepo.UpdateShortLinkTx(tx, shortLink)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to update shortlink tries", zap.Error(err))
|
||||
return nil, ErrInvalidDOB
|
||||
}
|
||||
|
||||
// Commit the transaction
|
||||
if err = tx.Commit(); err != nil {
|
||||
s.logger.Error("Failed to commit transaction", zap.Error(err))
|
||||
return nil, errors.New("database error")
|
||||
}
|
||||
|
||||
// Clear the tx to prevent the deferred rollback
|
||||
tx = nil
|
||||
|
||||
return nil, ErrInvalidDOB
|
||||
}
|
||||
|
||||
// DOB verified, reset tries count as successful login
|
||||
shortLink.RemainingTries = s.maxAttempts
|
||||
|
||||
// Update the shortlink in the database using the transaction
|
||||
err = s.shortLinkRepo.UpdateShortLinkTx(tx, shortLink)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to update shortlink tries after successful validation", zap.Error(err))
|
||||
return nil, errors.New("database error")
|
||||
}
|
||||
|
||||
// Commit the transaction
|
||||
if err = tx.Commit(); err != nil {
|
||||
s.logger.Error("Failed to commit transaction", zap.Error(err))
|
||||
return nil, errors.New("database error")
|
||||
}
|
||||
|
||||
// Clear the tx to prevent the deferred rollback
|
||||
tx = nil
|
||||
|
||||
return shortLink, nil
|
||||
}
|
||||
|
||||
// AuthenticateWithShortLink authenticates a user using a short link and DOB
|
||||
func (s *ShortLinkService) AuthenticateWithShortLink(req *models.ShortLinkAuthRequest) (*models.ShortLinkAuthResponse, error) {
|
||||
// Validate the short link
|
||||
shortLink, err := s.ValidateShortLink(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Determine patient name (could be fetched from a database)
|
||||
patientName := "Patient" // Placeholder, in production get real name
|
||||
|
||||
// Create additional claims for the JWT
|
||||
additionalClaims := make(map[string]interface{})
|
||||
additionalClaims["patient_id"] = shortLink.PatientID
|
||||
additionalClaims["patient_name"] = patientName
|
||||
additionalClaims["study_iuids"] = []string{shortLink.StudyUID}
|
||||
additionalClaims["home_url"] = fmt.Sprintf("viewer?StudyInstanceUIDs=%s", shortLink.StudyUID)
|
||||
additionalClaims["study_list"] = "disabled"
|
||||
|
||||
// Generate JWT
|
||||
// Using a virtual "user" for the patient with a patient role
|
||||
userID := fmt.Sprintf("shortlink_%s", shortLink.ID)
|
||||
email := fmt.Sprintf("patient_%s@shortlink.local", shortLink.ID) // Virtual email for JWT
|
||||
role := "patient" // Always patient role for shortlinks
|
||||
|
||||
// Generate access token (24-hour validity for patient access)
|
||||
accessToken, err := s.jwtManager.GenerateAccessToken(userID, email, role, patientName, additionalClaims)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to generate JWT for shortlink auth", zap.Error(err))
|
||||
return nil, errors.New("authentication error")
|
||||
}
|
||||
|
||||
// Create response
|
||||
redirectURL := fmt.Sprintf("/viewer?StudyInstanceUIDs=%s", shortLink.StudyUID)
|
||||
|
||||
return &models.ShortLinkAuthResponse{
|
||||
AccessToken: accessToken,
|
||||
ExpiresIn: int(s.jwtManager.GetAccessExpiry().Seconds()),
|
||||
RedirectURL: redirectURL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Helper functions
|
||||
|
||||
// hashDOB creates a secure hash of a date of birth
|
||||
func hashDOB(dob string) string {
|
||||
hash := sha256.Sum256([]byte(dob))
|
||||
return hex.EncodeToString(hash[:])
|
||||
}
|
||||
|
||||
// generateSecureToken generates a secure random token for short links
|
||||
func generateSecureToken(length int) (string, error) {
|
||||
b := make([]byte, length)
|
||||
_, err := rand.Read(b)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.URLEncoding.EncodeToString(b)[:length], nil
|
||||
}
|
||||
|
||||
// generateID generates a unique ID for a shortlink
|
||||
func generateID() string {
|
||||
b := make([]byte, 6)
|
||||
rand.Read(b)
|
||||
return fmt.Sprintf("sl_%s", hex.EncodeToString(b))
|
||||
}
|
||||
|
||||
// normalizeDOB normalizes date of birth to YYYY-MM-DD format
|
||||
func normalizeDOB(dob string) string {
|
||||
// Remove any non-alphanumeric characters except dash
|
||||
dob = strings.Map(func(r rune) rune {
|
||||
if (r >= '0' && r <= '9') || r == '-' {
|
||||
return r
|
||||
}
|
||||
return -1
|
||||
}, dob)
|
||||
|
||||
return dob
|
||||
}
|
||||
|
||||
// isValidDOBFormat checks if the DOB is in YYYY-MM-DD format
|
||||
func isValidDOBFormat(dob string) bool {
|
||||
// Check basic format
|
||||
if len(dob) != 10 {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check dashes
|
||||
if dob[4] != '-' || dob[7] != '-' {
|
||||
return false
|
||||
}
|
||||
|
||||
// Parse year, month, day
|
||||
yearStr := dob[0:4]
|
||||
monthStr := dob[5:7]
|
||||
dayStr := dob[8:10]
|
||||
|
||||
// Check if all are numeric
|
||||
for _, ch := range yearStr + monthStr + dayStr {
|
||||
if ch < '0' || ch > '9' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Could add more validation here (leap years, month/day ranges)
|
||||
|
||||
return true
|
||||
}
|
||||
Reference in New Issue
Block a user