Squashed commit of the following:

commit d2ec8c0f07
Author: mario <dev.mario@sismedika@gmail.com>
Date:   Thu May 15 15:42:33 2025 +0700

    add: db tx commit and rollback implementation

commit 264435f67e
Author: mario <dev.mario@sismedika@gmail.com>
Date:   Thu May 15 14:34:20 2025 +0700

    fix: shortlink generation logic update/create

commit 047ab1937a
Author: 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

commit c13f834b92
Author: 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

commit dd4451c2a8
Author: mario <dev.mario@sismedika@gmail.com>
Date:   Wed May 14 10:23:33 2025 +0700

    new file structure & koneksi ke DB

commit 8289881df3
Author: mario <dev.mario@sismedika@gmail.com>
Date:   Tue May 13 16:49:07 2025 +0700

    edit: rm debug route

commit dd784da232
Author: mario <dev.mario@sismedika@gmail.com>
Date:   Tue May 13 15:44:11 2025 +0700

    add: implement shortlink

commit 2687a761cc
Author: mario <dev.mario@sismedika@gmail.com>
Date:   Tue May 13 11:47:19 2025 +0700

    add new dummy doctor user

commit eb67eaca46
Author: mario <dev.mario@sismedika@gmail.com>
Date:   Tue May 13 11:46:28 2025 +0700

    add: ref_doctor studylist filter

commit 0d4825d152
Author: mario <dev.mario@sismedika@gmail.com>
Date:   Tue May 13 10:07:16 2025 +0700

    edit study_iuids & accNum in patient jwt to array

commit 2d1f135fda
Author: mario <dev.mario@sismedika@gmail.com>
Date:   Tue May 13 09:52:45 2025 +0700

    patient see their multiple studies

commit 13bb380f51
Author: mario <dev.mario@sismedika@gmail.com>
Date:   Fri May 9 10:13:16 2025 +0700

    add: cors handler route and readme

commit 6c9ab574ce
Author: mario <dev.mario@sismedika@gmail.com>
Date:   Mon May 5 11:50:36 2025 +0700

    add: login & token validation tapi belum connect ke DB

commit 297c9a6a01
Author: mario <dev.mario@sismedika@gmail.com>
Date:   Mon Apr 28 15:37:02 2025 +0700

    add readme.md

commit 9b8e0260f3
Author: mario <dev.mario@sismedika@gmail.com>
Date:   Mon Apr 7 15:46:07 2025 +0700

    connected-to-google

commit f340bc5916
Author: mario <dev.mario@sismedika.com>
Date:   Mon Apr 7 11:14:18 2025 +0700

    init
This commit is contained in:
mario
2025-05-15 15:50:40 +07:00
parent 8a000ca6c8
commit c35ec4180d
42 changed files with 4826 additions and 19 deletions

View 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))
}

View 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
}

View 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
}