Compare commits
19 Commits
v1-router-
...
new-domain
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3aa155dfbc | ||
|
|
ed3feb77d2 | ||
|
|
36417fe515 | ||
|
|
28339e855c | ||
|
|
d2ec8c0f07 | ||
|
|
264435f67e | ||
|
|
047ab1937a | ||
|
|
c13f834b92 | ||
|
|
dd4451c2a8 | ||
|
|
8289881df3 | ||
|
|
dd784da232 | ||
|
|
2687a761cc | ||
|
|
eb67eaca46 | ||
|
|
0d4825d152 | ||
|
|
2d1f135fda | ||
|
|
13bb380f51 | ||
|
|
6c9ab574ce | ||
|
|
297c9a6a01 | ||
|
|
9b8e0260f3 |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,6 +1,7 @@
|
||||
# Binary files
|
||||
bin/
|
||||
dicom-proxy
|
||||
build/*
|
||||
|
||||
# Credentials
|
||||
credentials/*.json
|
||||
@@ -18,4 +19,4 @@ vendor/
|
||||
|
||||
# OS specific files
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
Thumbs.db
|
||||
|
||||
19
Dockerfile
19
Dockerfile
@@ -1,5 +1,5 @@
|
||||
# Build stage
|
||||
FROM golang:1.18-alpine AS builder
|
||||
FROM golang:1.22 AS builder
|
||||
|
||||
# Set working directory
|
||||
WORKDIR /app
|
||||
@@ -14,10 +14,10 @@ RUN go mod download
|
||||
COPY . .
|
||||
|
||||
# Build the application
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o dicom-proxy cmd/server/main.go
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o ohif-proxy cmd/server/main.go
|
||||
|
||||
# Final stage
|
||||
FROM alpine:3.15
|
||||
FROM alpine:3.18
|
||||
|
||||
# Install CA certificates for HTTPS connections
|
||||
RUN apk --no-cache add ca-certificates
|
||||
@@ -26,19 +26,14 @@ RUN apk --no-cache add ca-certificates
|
||||
WORKDIR /app
|
||||
|
||||
# Copy binary from build stage
|
||||
COPY --from=builder /app/dicom-proxy .
|
||||
COPY --from=builder /app/ohif-proxy .
|
||||
|
||||
# Copy configuration
|
||||
# Copy configuration and create dirs
|
||||
COPY config/config.yaml ./config/
|
||||
|
||||
# Create directory for credentials
|
||||
RUN mkdir -p /app/credentials
|
||||
|
||||
# Expose port
|
||||
EXPOSE 8080
|
||||
|
||||
# Set environment variable for config file location
|
||||
ENV CONFIG_FILE=/app/config/config.yaml
|
||||
EXPOSE 5555
|
||||
|
||||
# Run the application
|
||||
ENTRYPOINT ["./dicom-proxy"]
|
||||
CMD ["./ohif-proxy"]
|
||||
399
README.md
Normal file
399
README.md
Normal file
@@ -0,0 +1,399 @@
|
||||
# GO-OHIF-Proxy
|
||||
|
||||
## 1. Gambaran Umum
|
||||
|
||||
### Tujuan
|
||||
|
||||
App ini dibuat untuk menyalurkan **dicomWeb** request dari OHIF ke Google Healthcare. Proxy berperan hanya sebagai authenticator ke Google dengan `service-account.json`, **tanpa merubah / menambah request**
|
||||
|
||||
Berikut adalah cara clone project ini:
|
||||
|
||||
|
||||
## 2. Alur Kerja Aplikasi
|
||||
|
||||
```
|
||||
+----------------+ +----------------+ +----------------------+
|
||||
| | | | | |
|
||||
| OHIF Viewer |----->| GO-OHIF-Proxy |----->| Google Healthcare |
|
||||
| (Web Client) |<-----| |<-----| DICOM API |
|
||||
| | | | | |
|
||||
+----------------+ +----------------+ +----------------------+
|
||||
```
|
||||
|
||||
1. **Permintaan Klien**: OHIF Viewer mengirimkan permintaan DICOMweb (misalnya, untuk mengambil studi).
|
||||
2. **Pemrosesan Proxy**:
|
||||
- Proxy mencegat permintaan.
|
||||
- Menambahkan header autentikasi yang sesuai.
|
||||
- Meneruskan permintaan ke Google Cloud Healthcare API.
|
||||
3. **Pemrosesan Google Cloud**: Healthcare API memproses permintaan DICOM.
|
||||
4. **Penanganan Respons**: Proxy meneruskan respons kembali ke klien.
|
||||
|
||||
## 2b. Arsitektur
|
||||
```txt
|
||||
go-ohif-proxy/
|
||||
│
|
||||
├── cmd/
|
||||
│ └── server/ # Application entry point
|
||||
│ └── main.go # Main server initialization
|
||||
│
|
||||
├── config/ # Configuration management
|
||||
│ ├── config.go # Configuration loader
|
||||
│ └── config.yaml # Application configuration
|
||||
│
|
||||
├── credentials/ # Authentication credentials
|
||||
│ └── service-account.json # Google Cloud service account
|
||||
│
|
||||
├── internal/
|
||||
│ ├── api/ # API endpoints
|
||||
│ │ ├── handler.go # HTTP request handlers
|
||||
│ │ ├── middleware.go # Request middleware
|
||||
│ │ └── routes.go # API route definitions
|
||||
│ │
|
||||
│ ├── auth/ # Authentication services
|
||||
│ │ └── google.go # Google Cloud authentication
|
||||
│ │
|
||||
│ ├── proxy/ # Proxy service
|
||||
│ │ └── dicomweb.go # DICOMweb request handling
|
||||
│ │
|
||||
│ └── utils/ # Utility functions
|
||||
│ ├── http.go # HTTP utilities
|
||||
│ └── logger.go # Logging functionality
|
||||
│
|
||||
├── test/ # Testing resources
|
||||
│ └── http/ # HTTP test requests
|
||||
│
|
||||
├── Dockerfile # Container definition
|
||||
├── docker-compose.yml # Multi-container orchestration
|
||||
├── go.mod # Go module definition
|
||||
├── go.sum # Module dependency checksums
|
||||
└── README.md # Project documentation
|
||||
```
|
||||
|
||||
## 2c. Alur Kerja Kode
|
||||
Secara umum kode di repo ini kurang lebih memiliki alur:
|
||||
```
|
||||
Routes --> Handlers --> Service --> Repository
|
||||
```
|
||||
|
||||
## 3. Instalasi dan Penggunaan
|
||||
|
||||
### Prasyarat
|
||||
|
||||
- Go versi 1.19 atau lebih tinggi.
|
||||
- Akun Google Cloud dengan Healthcare API diaktifkan.
|
||||
- Kredensial akun layanan dengan akses ke DICOM store.
|
||||
|
||||
### Clone dan Setup
|
||||
|
||||
```bash
|
||||
# Clone repositori
|
||||
git clone https://devone.aplikasi.web.id/gitea/mario/go-ohif-proxy.git
|
||||
cd go-ohif-proxy
|
||||
|
||||
# Install dependencies
|
||||
go mod download
|
||||
```
|
||||
|
||||
### Konfigurasi
|
||||
|
||||
1. Salin file konfigurasi contoh:
|
||||
```bash
|
||||
cp config/config.yaml.example config/config.yaml
|
||||
```
|
||||
|
||||
2. Edit `config/config.yaml` sesuai kebutuhan:
|
||||
```yaml
|
||||
server:
|
||||
port: 5555
|
||||
read_timeout_seconds: 30
|
||||
write_timeout_seconds: 30
|
||||
idle_timeout_seconds: 60
|
||||
|
||||
log_level: "info" # debug, info, warn, error
|
||||
|
||||
google:
|
||||
project_id: "id-proyek-gcp-anda"
|
||||
location: "lokasi-anda"
|
||||
dataset: "nama-dataset-anda"
|
||||
dicom_store: "nama-dicom-store-anda"
|
||||
credentials_path: "./credentials/service-account.json"
|
||||
|
||||
allowed_origins:
|
||||
- "http://localhost:3000" # URL OHIF Viewer
|
||||
```
|
||||
|
||||
3. Letakkan kredensial akun layanan Google Cloud Anda di `credentials/service-account.json`.
|
||||
|
||||
### Menjalankan Aplikasi
|
||||
|
||||
#### Build dan Jalankan Secara Langsung
|
||||
|
||||
```bash
|
||||
# Build aplikasi
|
||||
go build -o ohif-proxy ./cmd/server
|
||||
|
||||
# Jalankan aplikasi
|
||||
./ohif-proxy
|
||||
```
|
||||
|
||||
#### Menggunakan Docker
|
||||
|
||||
```bash
|
||||
# Build image Docker
|
||||
docker build -t go-ohif-proxy .
|
||||
|
||||
# Jalankan dengan Docker
|
||||
docker run -p 5555:5555 -v $(pwd)/config:/app/config -v $(pwd)/credentials:/app/credentials go-ohif-proxy
|
||||
```
|
||||
|
||||
#### Menggunakan Docker Compose
|
||||
|
||||
```bash
|
||||
docker-compose up
|
||||
```
|
||||
|
||||
### Run Aplikasi Tanpa Build
|
||||
|
||||
1. Transfer `./ohif-proxy` ke server tujuan. Contoh:
|
||||
```sh
|
||||
scp ohif-proxy pacs@152.42.173.210:/home/pacs/google-ohif-proxy
|
||||
```
|
||||
2. Pastikan server tujuan terinstall **go versi >1.19**. Cek dengan:
|
||||
3. Buat direktori:
|
||||
```sh
|
||||
mkdir -p ~/google-ohif-proxy
|
||||
mkdir -p ~/google-ohif-proxy/config
|
||||
mkdir -p ~/google-ohif-proxy/credentials
|
||||
```
|
||||
4. Tambahkan `config.go` dan `config.yaml`.
|
||||
```sh
|
||||
scp -r config/* pacs@152.42.173.210:/home/pacs/google-ohif-proxy/config/
|
||||
```
|
||||
5. Tambahkan credential `/credentials/service-account.json`
|
||||
```
|
||||
nano credentials/service-account.json
|
||||
# atau
|
||||
# scp dari local
|
||||
```
|
||||
|
||||
|
||||
### Pengujian
|
||||
|
||||
Aplikasi ini menyertakan permintaan HTTP uji di direktori `test/http` yang dapat digunakan dengan klien REST seperti ekstensi REST Client di VSCode.
|
||||
|
||||
```bash
|
||||
# Jalankan pengujian yang disertakan
|
||||
make test
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
Untuk informasi lebih lanjut tentang OHIF: [https://ohif.org/](https://ohif.org/)
|
||||
Untuk informasi lebih lanjut tentang Google Cloud Healthcare API: [https://cloud.google.com/healthcare](https://cloud.google.com/healthcare)
|
||||
|
||||
# GO-OHIF-Proxy Architecture
|
||||
|
||||
## Project Structure
|
||||
```
|
||||
go-ohif-proxy/
|
||||
├── cmd/
|
||||
│ └── server/ # Application entry point
|
||||
│ └── main.go # Main function and application start
|
||||
│
|
||||
├── config/ # Configuration
|
||||
│ ├── config.go # Config structure definitions
|
||||
│ └── config.yaml # YAML configuration file
|
||||
│
|
||||
├── credentials/ # Authentication credentials
|
||||
│ └── service-account.json # Google service account credentials
|
||||
│
|
||||
├── internal/ # Internal packages (not importable)
|
||||
│ ├── api/ # API implementation
|
||||
│ │ ├── handlers/ # HTTP request handlers
|
||||
│ │ │ ├── auth.go # Authentication handlers
|
||||
│ │ │ ├── dicom.go # DICOM request handlers
|
||||
│ │ │ └── healthcheck.go # Health check endpoint
|
||||
│ │ │
|
||||
│ │ ├── middleware/ # HTTP middleware
|
||||
│ │ │ ├── auth.go # Authentication middleware
|
||||
│ │ │ └── logging.go # Request logging middleware
|
||||
│ │ │
|
||||
│ │ ├── models/ # Data models
|
||||
│ │ │ └── user.go # User and authentication models
|
||||
│ │ │
|
||||
│ │ ├── repository/ # Data access layer
|
||||
│ │ │ ├── interfaces.go # Repository interfaces
|
||||
│ │ │ └── mysql_repository.go # MySQL implementation
|
||||
│ │ │
|
||||
│ │ ├── service/ # Business logic
|
||||
│ │ │ ├── auth_service.go # Authentication service
|
||||
│ │ │ └── db_repository.go # Legacy repository code (to be removed)
|
||||
│ │ │
|
||||
│ │ └── routes.go # API route definitions
|
||||
│ │
|
||||
│ ├── auth/ # Authentication utilities
|
||||
│ │ ├── google.go # Google authentication client
|
||||
│ │ └── jwt.go # JWT generation and validation
|
||||
│ │
|
||||
│ ├── logger/ # Logging utilities
|
||||
│ │ └── logger.go # Logger configuration
|
||||
│ │
|
||||
│ └── proxy/ # DICOM web proxy functionality
|
||||
│ └── client.go # Google Healthcare API client
|
||||
│
|
||||
├── pkg/ # Public packages (importable)
|
||||
│
|
||||
├── test/ # Test files
|
||||
│ └── http/ # HTTP test requests
|
||||
│ ├── ohif-flow.http # OHIF workflow tests
|
||||
│ └── test.http # General API tests
|
||||
│
|
||||
├── docker-compose.yaml # Docker Compose configuration
|
||||
├── Dockerfile # Docker build instructions
|
||||
├── go.mod # Go module definition
|
||||
├── go.sum # Go module checksums
|
||||
├── Makefile # Build automation
|
||||
└── README.md # Project documentation
|
||||
```
|
||||
|
||||
## Architecture Diagram
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
subgraph Client
|
||||
OHIF[OHIF Viewer]
|
||||
end
|
||||
|
||||
subgraph API_Gateway
|
||||
Router[Chi Router]
|
||||
Auth_MW[Auth Middleware]
|
||||
Logging_MW[Logging Middleware]
|
||||
CORS_MW[CORS Middleware]
|
||||
PatientView_MW[Patient View Restriction]
|
||||
end
|
||||
|
||||
subgraph Services
|
||||
AuthService[Auth Service]
|
||||
DicomService[DICOM Service]
|
||||
end
|
||||
|
||||
subgraph Repositories
|
||||
UserRepo[User Repository]
|
||||
TokenRepo[Token Repository]
|
||||
PatientRepo[Patient Repository]
|
||||
DoctorRepo[Doctor Repository]
|
||||
end
|
||||
|
||||
subgraph External
|
||||
GoogleHealthcare[Google Healthcare API]
|
||||
MySQL[MySQL Database]
|
||||
end
|
||||
|
||||
subgraph Utilities
|
||||
JWTManager[JWT Manager]
|
||||
GoogleAuth[Google Auth Client]
|
||||
Logger[Logger]
|
||||
end
|
||||
|
||||
OHIF -->|HTTP Requests| Router
|
||||
Router --> Auth_MW
|
||||
Auth_MW --> Logging_MW
|
||||
Logging_MW --> CORS_MW
|
||||
CORS_MW --> PatientView_MW
|
||||
PatientView_MW --> DicomService
|
||||
|
||||
Router -->|Auth Routes| AuthService
|
||||
AuthService -->|Uses| JWTManager
|
||||
AuthService -->|Uses| UserRepo
|
||||
AuthService -->|Uses| TokenRepo
|
||||
|
||||
DicomService -->|Uses| GoogleHealthcare
|
||||
DicomService -->|Uses| PatientRepo
|
||||
|
||||
UserRepo -->|Implements| MySQL
|
||||
TokenRepo -->|Implements| MySQL
|
||||
PatientRepo -->|Implements| MySQL
|
||||
DoctorRepo -->|Implements| MySQL
|
||||
|
||||
DicomService -->|Uses| GoogleAuth
|
||||
GoogleAuth -->|Authenticates| GoogleHealthcare
|
||||
```
|
||||
|
||||
## Authentication Flow
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Client
|
||||
participant API as API Gateway
|
||||
participant AuthService
|
||||
participant Repo as Repository
|
||||
participant JWT as JWT Manager
|
||||
participant DB as Database
|
||||
|
||||
Client->>API: POST /auth/login
|
||||
API->>AuthService: Login(email, password)
|
||||
|
||||
alt Database Auth Enabled
|
||||
AuthService->>Repo: GetUserByEmail(email)
|
||||
Repo->>DB: SELECT * FROM users
|
||||
DB->>Repo: User Data
|
||||
Repo->>AuthService: User Object
|
||||
AuthService->>JWT: Generate Tokens
|
||||
JWT->>AuthService: Access + Refresh Tokens
|
||||
AuthService->>Repo: StoreRefreshToken()
|
||||
Repo->>DB: INSERT INTO refresh_tokens
|
||||
else Hardcoded Auth
|
||||
AuthService->>JWT: Generate Tokens
|
||||
JWT->>AuthService: Access + Refresh Tokens
|
||||
end
|
||||
|
||||
AuthService->>API: Tokens + User Info
|
||||
API->>Client: Auth Response
|
||||
|
||||
Note over Client,API: Later - Protected Request
|
||||
|
||||
Client->>API: GET /dicomWeb/* with Bearer Token
|
||||
API->>AuthService: ValidateToken()
|
||||
AuthService->>JWT: ParseToken()
|
||||
JWT->>AuthService: Claim Data
|
||||
AuthService->>API: User Context
|
||||
API->>Client: Protected Resource
|
||||
```
|
||||
|
||||
## DICOM Request Flow
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Client
|
||||
participant API as API Gateway
|
||||
participant Auth as Auth Middleware
|
||||
participant PatientMW as Patient Restriction MW
|
||||
participant DicomHandler
|
||||
participant GCP as Google Healthcare API
|
||||
|
||||
Client->>API: GET /dicomWeb/studies/{studyUID}
|
||||
|
||||
alt Whitelisted Path
|
||||
API->>DicomHandler: Forward Request (Skip Auth)
|
||||
else Protected Path
|
||||
API->>Auth: Check Authentication
|
||||
Auth->>API: User Context
|
||||
API->>PatientMW: Check Access Rights
|
||||
|
||||
alt Patient Role
|
||||
PatientMW->>Repo: IsStudyAssignedToPatient()
|
||||
Repo->>PatientMW: Access Result
|
||||
alt Study Assigned
|
||||
PatientMW->>DicomHandler: Forward Request
|
||||
else Study Not Assigned
|
||||
PatientMW->>Client: 403 Forbidden
|
||||
end
|
||||
else Doctor Role
|
||||
PatientMW->>DicomHandler: Forward Request
|
||||
end
|
||||
end
|
||||
|
||||
DicomHandler->>GCP: Forward Request to DICOM Store
|
||||
GCP->>DicomHandler: DICOM Data
|
||||
DicomHandler->>Client: DICOM Response
|
||||
```
|
||||
54
cmd/seed_shortcodes/seed_shortcodes.go
Normal file
54
cmd/seed_shortcodes/seed_shortcodes.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/repository"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/database"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
/*
|
||||
* HOW TO USE:
|
||||
* `go run cmd/seed_shortcodes/seed_shortcodes.go -dsn="user:password@tcp(host_db:port)/nama_db_ohif_proxy"`
|
||||
*
|
||||
* Ini akan seeding DB dengan 3333 data (sesuai var count)
|
||||
*/
|
||||
|
||||
// Parse command line flags
|
||||
count := flag.Int("count", 3333, "Number of shortcodes to generate")
|
||||
dsn := flag.String("dsn", "", "Database connection string (required)")
|
||||
flag.Parse()
|
||||
|
||||
// Check if DSN is provided
|
||||
if *dsn == "" {
|
||||
fmt.Println("Error: Database connection string (DSN) is required")
|
||||
fmt.Println("Usage: go run seed_shortcodes.go -dsn=user:password@tcp(localhost:3306)/database_name -count=1000")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Initialize database connection
|
||||
err := database.Initialize(*dsn, 10, 5, 60*time.Minute)
|
||||
if err != nil {
|
||||
fmt.Printf("Failed to connect to database: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer database.Close()
|
||||
|
||||
// Create a shortcode repository
|
||||
shortCodeRepo := repository.NewShortCodeRepository()
|
||||
|
||||
// Seed the shortcodes
|
||||
fmt.Printf("Seeding %d shortcodes...\n", *count)
|
||||
err = shortCodeRepo.SeedShortCodes(*count)
|
||||
if err != nil {
|
||||
fmt.Printf("Error seeding shortcodes: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
fmt.Println("Shortcode seeding completed successfully!")
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/config"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/logger"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/database"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
@@ -24,9 +24,42 @@ func main() {
|
||||
}
|
||||
|
||||
// Initialize logger
|
||||
l := logger.New(cfg.LogLevel)
|
||||
// l := logger.New(cfg.LogLevel)
|
||||
// defer l.Sync()
|
||||
|
||||
// * Uncomment kalau bukan debug
|
||||
config := zap.NewDevelopmentConfig()
|
||||
config.Level = zap.NewAtomicLevelAt(zap.DebugLevel)
|
||||
l, err := config.Build()
|
||||
if err != nil {
|
||||
log.Fatalf("can't initialize zap logger: %v", err)
|
||||
}
|
||||
defer l.Sync()
|
||||
|
||||
// Initialize database connection
|
||||
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?parseTime=true",
|
||||
cfg.Database.User,
|
||||
cfg.Database.Password,
|
||||
cfg.Database.Host,
|
||||
cfg.Database.Port,
|
||||
cfg.Database.Name)
|
||||
|
||||
err = database.Initialize(
|
||||
dsn,
|
||||
cfg.Database.MaxOpenConns,
|
||||
cfg.Database.MaxIdleConns,
|
||||
time.Duration(cfg.Database.ConnMaxLifetimeMins)*time.Minute,
|
||||
)
|
||||
if err != nil {
|
||||
l.Fatal("Failed to initialize database", zap.Error(err))
|
||||
}
|
||||
defer database.Close()
|
||||
|
||||
l.Info("Database connection established",
|
||||
zap.String("host", cfg.Database.Host),
|
||||
zap.Int("port", cfg.Database.Port),
|
||||
zap.String("database", cfg.Database.Name))
|
||||
|
||||
// Setup router
|
||||
router := api.SetupRouter(cfg, l)
|
||||
|
||||
@@ -26,6 +26,31 @@ type Config struct {
|
||||
CredentialsPath string `mapstructure:"credentials_path"`
|
||||
} `mapstructure:"google"`
|
||||
|
||||
Auth struct {
|
||||
JWTSecret string `mapstructure:"jwt_secret"`
|
||||
AccessTokenExpiry int `mapstructure:"access_token_expiry"` // in minutes
|
||||
RefreshTokenExpiry int `mapstructure:"refresh_token_expiry"` // in hours
|
||||
EnableDatabaseAuth bool `mapstructure:"enable_database_auth"`
|
||||
PydicomApiKey string `mapstructure:"pydicom_api_key"` // API Key for PYDICOM uploader service
|
||||
} `mapstructure:"auth"`
|
||||
|
||||
Shortlink struct {
|
||||
BaseURL string `mapstructure:"base_url"` // Base URL for shortlinks (e.g., https://example.com)
|
||||
DefaultExpiryHours int `mapstructure:"default_expiry_hours"` // Default expiry time in hours
|
||||
MaxAttempts int `mapstructure:"max_attempts"` // Maximum failed attempts allowed
|
||||
} `mapstructure:"shortlink"`
|
||||
|
||||
Database struct {
|
||||
Host string `mapstructure:"host"`
|
||||
Port int `mapstructure:"port"`
|
||||
User string `mapstructure:"user"`
|
||||
Password string `mapstructure:"password"`
|
||||
Name string `mapstructure:"name"`
|
||||
MaxOpenConns int `mapstructure:"max_open_conns"`
|
||||
MaxIdleConns int `mapstructure:"max_idle_conns"`
|
||||
ConnMaxLifetimeMins int `mapstructure:"conn_max_lifetime_mins"`
|
||||
} `mapstructure:"database"`
|
||||
|
||||
AllowedOrigins []string `mapstructure:"allowed_origins"`
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
server:
|
||||
port: 8080
|
||||
port: 5555
|
||||
read_timeout_seconds: 30
|
||||
write_timeout_seconds: 30
|
||||
idle_timeout_seconds: 60
|
||||
@@ -7,12 +7,33 @@ server:
|
||||
log_level: "info" # debug, info, warn, error
|
||||
|
||||
google:
|
||||
project_id: "your-project-id"
|
||||
location: "asia-southeast2"
|
||||
dataset: "dicom-storage"
|
||||
dicom_store: "ohif"
|
||||
project_id: "ohifproxy" # Replace with your GCP project ID
|
||||
location: "asia-southeast2" # Match your dataset region
|
||||
dataset: "sas-storage" # Your dataset name
|
||||
dicom_store: "store-1" # Your DICOM store name
|
||||
credentials_path: "./credentials/service-account.json"
|
||||
|
||||
# CORS settings - origins that are allowed to access the API
|
||||
auth:
|
||||
jwt_secret: "vQ6PQqUyh7pBNOytClgN+Nw1XBq7F8Qo6VP3VwIqvHY=" # Change this in production!
|
||||
access_token_expiry: 1440 # minutes (24 hours)
|
||||
refresh_token_expiry: 168 # hours (7 days)
|
||||
enable_database_auth: true # Changed to true to use database
|
||||
pydicom_api_key: "2f0ff447b2c3aeef2004e83a750ded97e29ba8c0ccc70053d5e26f5d715e42ff"
|
||||
|
||||
shortlink:
|
||||
base_url: "http://localhost:3333" # The base URL for generated OHIF Auth shortlinks
|
||||
default_expiry_hours: 720 # Default expiry time for shortlinks (30 days = 30 * 24 = 720 hours)
|
||||
max_attempts: 5 # Maximum number of failed login attempts
|
||||
|
||||
database:
|
||||
host: "localhost"
|
||||
port: 3306
|
||||
user: "root"
|
||||
password: "alfandi102938" # Change this to your MariaDB password
|
||||
name: "ohif_proxy"
|
||||
max_open_conns: 10
|
||||
max_idle_conns: 5
|
||||
conn_max_lifetime_mins: 60
|
||||
|
||||
allowed_origins:
|
||||
- "*" # Allow all origins (you may want to restrict this in production)
|
||||
- "*" # For development; restrict this in production
|
||||
12
docker-compose.yaml
Normal file
12
docker-compose.yaml
Normal file
@@ -0,0 +1,12 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
ohif-proxy:
|
||||
build: .
|
||||
ports:
|
||||
- "5555:5555"
|
||||
volumes:
|
||||
- ./config:/app/config
|
||||
- ./credentials:/app/credentials
|
||||
environment:
|
||||
- LOG_LEVEL=debug
|
||||
32
go.mod
32
go.mod
@@ -1,11 +1,19 @@
|
||||
module devone.aplikasi.web.id/gitea/mario/go-ohif-proxy
|
||||
|
||||
go 1.19
|
||||
go 1.21.0
|
||||
|
||||
toolchain go1.23.8
|
||||
|
||||
require (
|
||||
github.com/gin-gonic/gin v1.9.1
|
||||
github.com/go-chi/chi/v5 v5.2.1
|
||||
github.com/go-chi/cors v1.2.1
|
||||
github.com/go-sql-driver/mysql v1.9.2
|
||||
github.com/golang-jwt/jwt/v5 v5.2.2
|
||||
github.com/google/uuid v1.4.0
|
||||
github.com/jmoiron/sqlx v1.4.0
|
||||
github.com/spf13/viper v1.17.0
|
||||
go.uber.org/zap v1.27.0
|
||||
golang.org/x/crypto v0.14.0
|
||||
golang.org/x/oauth2 v0.13.0
|
||||
google.golang.org/api v0.149.0
|
||||
)
|
||||
@@ -13,30 +21,16 @@ require (
|
||||
require (
|
||||
cloud.google.com/go/compute v1.23.1 // indirect
|
||||
cloud.google.com/go/compute/metadata v0.2.3 // indirect
|
||||
github.com/bytedance/sonic v1.9.1 // indirect
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
|
||||
filippo.io/edwards25519 v1.1.0 // indirect
|
||||
github.com/fsnotify/fsnotify v1.6.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
|
||||
github.com/gin-contrib/sse v0.1.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.14.0 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
|
||||
github.com/golang/protobuf v1.5.3 // indirect
|
||||
github.com/google/s2a-go v0.1.7 // indirect
|
||||
github.com/google/uuid v1.4.0 // indirect
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.2 // indirect
|
||||
github.com/googleapis/gax-go/v2 v2.12.0 // indirect
|
||||
github.com/hashicorp/hcl v1.0.0 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
|
||||
github.com/leodido/go-urn v1.2.4 // indirect
|
||||
github.com/magiconair/properties v1.8.7 // indirect
|
||||
github.com/mattn/go-isatty v0.0.19 // indirect
|
||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.1.0 // indirect
|
||||
github.com/sagikazarmark/locafero v0.3.0 // indirect
|
||||
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
|
||||
@@ -45,12 +39,8 @@ require (
|
||||
github.com/spf13/cast v1.5.1 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.11 // indirect
|
||||
go.opencensus.io v0.24.0 // indirect
|
||||
go.uber.org/multierr v1.10.0 // indirect
|
||||
golang.org/x/arch v0.3.0 // indirect
|
||||
golang.org/x/crypto v0.14.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
|
||||
golang.org/x/net v0.17.0 // indirect
|
||||
golang.org/x/sys v0.13.0 // indirect
|
||||
|
||||
77
go.sum
77
go.sum
@@ -40,15 +40,11 @@ cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RX
|
||||
cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0=
|
||||
cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3fOKtUw0Xmo=
|
||||
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
|
||||
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
|
||||
github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
|
||||
github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s=
|
||||
github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U=
|
||||
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams=
|
||||
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=
|
||||
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
|
||||
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
|
||||
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
|
||||
@@ -59,6 +55,7 @@ github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnht
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
|
||||
@@ -66,26 +63,21 @@ github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5y
|
||||
github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk=
|
||||
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
|
||||
github.com/frankban/quicktest v1.14.4 h1:g2rn0vABPOOXmZUj+vbmUp0lPoXEMuhTpIluN0XL9UY=
|
||||
github.com/frankban/quicktest v1.14.4/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||
github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY=
|
||||
github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw=
|
||||
github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
|
||||
github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
|
||||
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
||||
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||
github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
|
||||
github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
|
||||
github.com/go-chi/chi/v5 v5.2.1 h1:KOIHODQj58PmL80G2Eak4WdvUzjSJSm0vG72crDCqb8=
|
||||
github.com/go-chi/chi/v5 v5.2.1/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops=
|
||||
github.com/go-chi/cors v1.2.1 h1:xEC8UT3Rlp2QuWNEr4Fs/c2EAGVKBwy/1vHx3bppil4=
|
||||
github.com/go-chi/cors v1.2.1/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=
|
||||
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
|
||||
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
|
||||
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.14.0 h1:vgvQWe3XCz3gIeFDm/HnTIbj6UGmg/+t63MyGU2n5js=
|
||||
github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
|
||||
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
||||
github.com/go-sql-driver/mysql v1.9.2 h1:4cNKDYQ1I84SXslGddlsrMhc8k4LeDVj6Ad6WRjiHuU=
|
||||
github.com/go-sql-driver/mysql v1.9.2/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
|
||||
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
||||
github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
|
||||
github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
|
||||
@@ -130,7 +122,7 @@ github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
|
||||
github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
|
||||
github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=
|
||||
github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0=
|
||||
@@ -163,42 +155,38 @@ github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
|
||||
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o=
|
||||
github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY=
|
||||
github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
|
||||
github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk=
|
||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk=
|
||||
github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY=
|
||||
github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
|
||||
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
|
||||
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
|
||||
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
|
||||
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
|
||||
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6/MHO4=
|
||||
github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qRg=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
||||
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
|
||||
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||
github.com/sagikazarmark/locafero v0.3.0 h1:zT7VEGWC2DTflmccN/5T1etyKvxSxpHsjb9cJvm4SvQ=
|
||||
github.com/sagikazarmark/locafero v0.3.0/go.mod h1:w+v7UsPNFwzF1cHuOajOOzoq4U7v/ig1mpRjqV+Bu1U=
|
||||
github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE=
|
||||
@@ -216,22 +204,16 @@ github.com/spf13/viper v1.17.0/go.mod h1:BmMMMLQXSbcHK6KAOiFLz0l5JHrU89OdIRHvsk0
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
|
||||
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=
|
||||
github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
@@ -245,13 +227,11 @@ go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk=
|
||||
go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
|
||||
go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
|
||||
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
|
||||
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
||||
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||
golang.org/x/arch v0.3.0 h1:02VY4/ZcO/gBOH6PUaoiptASxtXU10jazRCP865E97k=
|
||||
golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
@@ -353,6 +333,7 @@ golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJ
|
||||
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.4.0 h1:zxkM55ReGkDlKSM+Fu41A+zmbZuaPVbGMzvvdUPznYQ=
|
||||
golang.org/x/sync v0.4.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
|
||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
@@ -388,9 +369,7 @@ golang.org/x/sys v0.0.0-20210225134936-a50acf3fe073/go.mod h1:h1NjWce9XRLGQEsW7w
|
||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
|
||||
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
@@ -524,7 +503,9 @@ google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6D
|
||||
google.golang.org/genproto v0.0.0-20210108203827-ffc7fda8c3d7/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
|
||||
google.golang.org/genproto v0.0.0-20210226172003-ab064af71705/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
|
||||
google.golang.org/genproto v0.0.0-20231016165738-49dd2c1f3d0b h1:+YaDE2r2OG8t/z5qmsh7Y+XXwCbvadxxZ0YY6mTdrVA=
|
||||
google.golang.org/genproto v0.0.0-20231016165738-49dd2c1f3d0b/go.mod h1:CgAqfJo+Xmu0GwA0411Ht3OU3OntXwsGmrmjI8ioGXI=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20231016165738-49dd2c1f3d0b h1:CIC2YMXmIhYw6evmhPxBKJ4fmLbOFtXQN/GV3XOZR8k=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20231016165738-49dd2c1f3d0b/go.mod h1:IBQ646DjkDkvUIsVq/cc03FUFQ9wbZu7yE396YcL870=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20231016165738-49dd2c1f3d0b h1:ZlWIi1wSK56/8hn4QcBp/j9M7Gt3U/3hZw3mC7vDICo=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20231016165738-49dd2c1f3d0b/go.mod h1:swOH3j0KzcDDgGUWr+SNpyTen5YrXjS3eyPzFYKc6lc=
|
||||
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
|
||||
@@ -562,6 +543,7 @@ google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqw
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
||||
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
|
||||
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
|
||||
@@ -577,6 +559,5 @@ honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt
|
||||
honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=
|
||||
honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=
|
||||
rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8=
|
||||
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
|
||||
rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0=
|
||||
rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA=
|
||||
|
||||
@@ -1,32 +1,93 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"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-related requests
|
||||
// AuthHandler handles authentication requests
|
||||
type AuthHandler struct {
|
||||
logger *zap.Logger
|
||||
logger *zap.Logger
|
||||
authService *service.AuthService
|
||||
}
|
||||
|
||||
// NewAuthHandler creates a new AuthHandler
|
||||
func NewAuthHandler(logger *zap.Logger) *AuthHandler {
|
||||
// NewAuthHandler creates a new auth handler
|
||||
func NewAuthHandler(logger *zap.Logger, authService *service.AuthService) *AuthHandler {
|
||||
return &AuthHandler{
|
||||
logger: logger,
|
||||
logger: logger,
|
||||
authService: authService,
|
||||
}
|
||||
}
|
||||
|
||||
// Login handles user login
|
||||
func (h *AuthHandler) Login(c *gin.Context) {
|
||||
// TODO: Implement login logic
|
||||
h.logger.Info("Login endpoint hit")
|
||||
c.JSON(200, gin.H{"message": "Login not implemented"})
|
||||
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(c *gin.Context) {
|
||||
// TODO: Implement logout logic
|
||||
h.logger.Info("Logout endpoint hit")
|
||||
c.JSON(200, gin.H{"message": "Logout not implemented"})
|
||||
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",
|
||||
})
|
||||
}
|
||||
|
||||
@@ -4,9 +4,13 @@ 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/gin-gonic/gin"
|
||||
"github.com/go-chi/chi/v5"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
@@ -24,32 +28,195 @@ func NewDicomHandler(client *proxy.Client, logger *zap.Logger) *DicomHandler {
|
||||
}
|
||||
}
|
||||
|
||||
// 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(c *gin.Context) {
|
||||
path := c.Param("path")
|
||||
requestType := getRequestType(c.Request.URL.Path)
|
||||
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", path),
|
||||
zap.String("method", c.Request.Method),
|
||||
zap.String("type", requestType),
|
||||
)
|
||||
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 c.Request.Body != nil && c.Request.ContentLength > 0 {
|
||||
if r.Body != nil && r.ContentLength > 0 {
|
||||
var err error
|
||||
bodyBytes, err = io.ReadAll(c.Request.Body)
|
||||
bodyBytes, err = io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
h.logger.Error("Failed to read request body", zap.Error(err))
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to read request body"})
|
||||
http.Error(w, "Failed to read request body", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Get request headers
|
||||
headers := make(map[string]string)
|
||||
for k, v := range c.Request.Header {
|
||||
for k, v := range r.Header {
|
||||
if len(v) > 0 {
|
||||
headers[k] = v[0]
|
||||
}
|
||||
@@ -57,45 +224,24 @@ func (h *DicomHandler) ForwardRequest(c *gin.Context) {
|
||||
|
||||
// Forward the request to Healthcare API
|
||||
response, err := h.client.ForwardRequest(
|
||||
c.Request.Context(),
|
||||
c.Request.Method,
|
||||
requestType,
|
||||
path,
|
||||
r.Context(),
|
||||
r.Method,
|
||||
urlPath,
|
||||
headers,
|
||||
bodyBytes,
|
||||
)
|
||||
bodyBytes)
|
||||
|
||||
if err != nil {
|
||||
h.logger.Error("Request forwarding failed", zap.Error(err))
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("Request failed: %v", err)})
|
||||
http.Error(w, fmt.Sprintf("Request failed: %v", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Set response headers
|
||||
for k, v := range response.Headers {
|
||||
c.Header(k, v)
|
||||
w.Header().Set(k, v)
|
||||
}
|
||||
|
||||
// Set status and write response body
|
||||
c.Status(response.StatusCode)
|
||||
c.Writer.Write(response.Body)
|
||||
}
|
||||
|
||||
// getRequestType determines if the request is WADO, QIDO or STOW
|
||||
func getRequestType(path string) string {
|
||||
if len(path) < 9 {
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
pathComponent := path[9:] // Remove "/dicomWeb/"
|
||||
|
||||
if len(pathComponent) >= 4 && pathComponent[:4] == "wado" {
|
||||
return "wado"
|
||||
} else if len(pathComponent) >= 4 && pathComponent[:4] == "qido" {
|
||||
return "qido"
|
||||
} else if len(pathComponent) >= 4 && pathComponent[:4] == "stow" {
|
||||
return "stow"
|
||||
}
|
||||
|
||||
return "unknown"
|
||||
w.WriteHeader(response.StatusCode)
|
||||
w.Write(response.Body)
|
||||
}
|
||||
|
||||
@@ -1,12 +1,19 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"time"
|
||||
)
|
||||
|
||||
// HealthCheck is a simple health check handler
|
||||
func HealthCheck(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{"status": "ok"})
|
||||
// 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)
|
||||
}
|
||||
|
||||
158
internal/api/handlers/pydicom.go
Normal file
158
internal/api/handlers/pydicom.go
Normal file
@@ -0,0 +1,158 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"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"
|
||||
)
|
||||
|
||||
// PydicomHandler handles operations related to PYDICOM uploads
|
||||
type PydicomHandler struct {
|
||||
logger *zap.Logger
|
||||
shortLinkService *service.ShortLinkService
|
||||
registerService *service.RegisterService
|
||||
}
|
||||
|
||||
// NewPydicomHandler creates a new PydicomHandler
|
||||
func NewPydicomHandler(logger *zap.Logger, shortLinkService *service.ShortLinkService, registerService *service.RegisterService) *PydicomHandler {
|
||||
return &PydicomHandler{
|
||||
logger: logger,
|
||||
shortLinkService: shortLinkService,
|
||||
registerService: registerService,
|
||||
}
|
||||
}
|
||||
|
||||
// HandleUploadedDicom processes a request from the PYDICOM uploader service to register a patient and generate a shortlink
|
||||
func (h *PydicomHandler) HandleUploadedDicom(w http.ResponseWriter, r *http.Request) {
|
||||
// Parse the request body into a temporary struct that matches the expected JSON
|
||||
var reqData struct {
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
Name string `json:"name"`
|
||||
Role string `json:"role"`
|
||||
Patient struct {
|
||||
PatientID string `json:"patient_id"`
|
||||
PatientName string `json:"patient_name"`
|
||||
DateOfBirth string `json:"date_of_birth"`
|
||||
} `json:"patient"`
|
||||
Studies []struct {
|
||||
StudyInstanceUID string `json:"study_instance_uid"`
|
||||
AccessionNumber string `json:"accession_number"`
|
||||
StudyDate string `json:"study_date"`
|
||||
StudyDescription string `json:"study_description"`
|
||||
} `json:"studies"`
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(r.Body).Decode(&reqData); err != nil {
|
||||
h.logger.Error("Failed to parse uploaded DICOM request", zap.Error(err))
|
||||
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Validate the request
|
||||
if reqData.Email == "" || reqData.Password == "" || reqData.Name == "" {
|
||||
h.logger.Error("Missing required user fields in uploaded DICOM request")
|
||||
http.Error(w, "Missing required user fields", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if reqData.Patient.PatientID == "" || reqData.Patient.DateOfBirth == "" {
|
||||
h.logger.Error("Missing required patient fields in uploaded DICOM request")
|
||||
http.Error(w, "Missing required patient fields", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if len(reqData.Studies) == 0 || reqData.Studies[0].StudyInstanceUID == "" {
|
||||
h.logger.Error("Missing required study fields in uploaded DICOM request")
|
||||
http.Error(w, "Missing required study fields", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Convert to our internal models
|
||||
patientDetails := &models.PatientDetails{
|
||||
PatientID: reqData.Patient.PatientID,
|
||||
PatientName: reqData.Patient.PatientName,
|
||||
DateOfBirth: reqData.Patient.DateOfBirth,
|
||||
}
|
||||
|
||||
// Convert studies to our internal model
|
||||
studies := make([]models.Study, len(reqData.Studies))
|
||||
for i, s := range reqData.Studies {
|
||||
studies[i] = models.Study{
|
||||
StudyInstanceUID: s.StudyInstanceUID,
|
||||
AccessionNumber: s.AccessionNumber,
|
||||
StudyDate: s.StudyDate,
|
||||
StudyDescription: s.StudyDescription,
|
||||
}
|
||||
}
|
||||
|
||||
// Create registration request
|
||||
regRequest := &service.RegisterRequest{
|
||||
Email: reqData.Email,
|
||||
Password: reqData.Password,
|
||||
Name: reqData.Name,
|
||||
Role: "patient", // Force the role to be "patient" regardless of what was sent
|
||||
Patient: patientDetails,
|
||||
Studies: studies,
|
||||
}
|
||||
|
||||
// Register the patient (or confirm it exists) using the RegisterService
|
||||
user, err := h.registerService.Register(regRequest)
|
||||
if err != nil {
|
||||
// If the error is about duplicate email, we'll continue with generating a shortlink
|
||||
// Otherwise, return the error
|
||||
if err != service.ErrEmailExists {
|
||||
h.logger.Error("Failed to register patient", zap.Error(err))
|
||||
http.Error(w, fmt.Sprintf("Failed to register patient: %v", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
h.logger.Info("Patient already exists, continuing with shortlink generation",
|
||||
zap.String("email", reqData.Email),
|
||||
zap.String("patientID", reqData.Patient.PatientID))
|
||||
} else {
|
||||
h.logger.Info("Patient registered successfully",
|
||||
zap.String("userID", user.ID),
|
||||
zap.String("email", reqData.Email),
|
||||
zap.String("patientID", reqData.Patient.PatientID))
|
||||
}
|
||||
|
||||
// For each study, generate a shortlink
|
||||
// For simplicity, we'll just use the first study in the array
|
||||
study := reqData.Studies[0]
|
||||
|
||||
// Create a shortlink request
|
||||
shortLinkReq := &models.GenerateShortLinkRequest{
|
||||
PatientID: reqData.Patient.PatientID,
|
||||
StudyUID: study.StudyInstanceUID,
|
||||
DOB: reqData.Patient.DateOfBirth,
|
||||
ExpiresIn: 0, // Set to 0 to use the default expiry from config
|
||||
}
|
||||
|
||||
// Generate a shortlink
|
||||
// We set empty string as creatorID because you mentioned ShortlinkCreate_UserID is now nullable
|
||||
shortLinkResp, err := h.shortLinkService.GenerateShortLink(shortLinkReq, "")
|
||||
if err != nil {
|
||||
h.logger.Error("Failed to generate shortlink",
|
||||
zap.Error(err),
|
||||
zap.String("patientID", reqData.Patient.PatientID),
|
||||
zap.String("studyUID", study.StudyInstanceUID))
|
||||
http.Error(w, fmt.Sprintf("Failed to generate shortlink: %v", err), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Log successful shortlink generation
|
||||
h.logger.Info("Shortlink generated for uploaded DICOM",
|
||||
zap.String("patientID", reqData.Patient.PatientID),
|
||||
zap.String("studyUID", study.StudyInstanceUID),
|
||||
zap.String("shortToken", shortLinkResp.ShortToken))
|
||||
|
||||
// Return the shortlink response
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(shortLinkResp)
|
||||
}
|
||||
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)
|
||||
}
|
||||
164
internal/api/handlers/shortlink.go
Normal file
164
internal/api/handlers/shortlink.go
Normal file
@@ -0,0 +1,164 @@
|
||||
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)
|
||||
}
|
||||
|
||||
// RecycleShortcodes handles requests to recycle shortcodes from expired shortlinks
|
||||
func (h *ShortLinkHandler) RecycleShortcodes(w http.ResponseWriter, r *http.Request) {
|
||||
// Only allow admin role to recycle shortcodes
|
||||
userRole, ok := r.Context().Value(middleware.UserRoleKey).(string)
|
||||
if !ok || userRole != "admin" {
|
||||
h.logger.Warn("Unauthorized attempt to recycle shortcodes",
|
||||
zap.String("role", userRole))
|
||||
http.Error(w, "Only admin can recycle shortcodes", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
// Call the service to recycle shortcodes
|
||||
count, err := h.shortLinkService.CleanupExpiredShortcodes()
|
||||
if err != nil {
|
||||
h.logger.Error("Failed to recycle shortcodes", zap.Error(err))
|
||||
http.Error(w, "Failed to recycle shortcodes", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// Log successful recycling
|
||||
h.logger.Info("Shortcodes recycled successfully",
|
||||
zap.Int("count", count))
|
||||
|
||||
// Return response
|
||||
response := map[string]interface{}{
|
||||
"status": "success",
|
||||
"message": "Shortcodes recycled successfully",
|
||||
"count": count,
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
json.NewEncoder(w).Encode(response)
|
||||
}
|
||||
252
internal/api/middleware/auth.go
Normal file
252
internal/api/middleware/auth.go
Normal file
@@ -0,0 +1,252 @@
|
||||
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) {
|
||||
// Check if this is the /dicomWeb/studies POST request which should bypass auth
|
||||
if r.URL.Path == "/dicomWeb/studies" && r.Method == http.MethodPost {
|
||||
logger.Info("Bypassing authentication for DICOM upload endpoint",
|
||||
zap.String("path", r.URL.Path),
|
||||
zap.String("method", r.Method))
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
// 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) {
|
||||
// Check if this is the /dicomWeb/studies POST request which should bypass restrictions
|
||||
if r.URL.Path == "/dicomWeb/studies" && r.Method == http.MethodPost {
|
||||
logger.Info("Bypassing patient view restriction for DICOM upload endpoint",
|
||||
zap.String("path", r.URL.Path),
|
||||
zap.String("method", r.Method))
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
// 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})
|
||||
}
|
||||
@@ -1,94 +1,61 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// Logger middleware adds request logging
|
||||
func Logger(logger *zap.Logger) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
start := time.Now()
|
||||
path := c.Request.URL.Path
|
||||
query := c.Request.URL.RawQuery
|
||||
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()
|
||||
|
||||
// Process request
|
||||
c.Next()
|
||||
// Create a wrapped response writer to capture the status code
|
||||
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
||||
|
||||
// Calculate request time
|
||||
latency := time.Since(start)
|
||||
// Process request
|
||||
next.ServeHTTP(ww, r)
|
||||
|
||||
// Get status
|
||||
status := c.Writer.Status()
|
||||
// Calculate request time
|
||||
latency := time.Since(start)
|
||||
|
||||
// Log request details
|
||||
logger.Info("API Request",
|
||||
zap.String("method", c.Request.Method),
|
||||
zap.String("path", path),
|
||||
zap.String("query", query),
|
||||
zap.Int("status", status),
|
||||
zap.Duration("latency", latency),
|
||||
zap.String("ip", c.ClientIP()),
|
||||
zap.String("user-agent", c.Request.UserAgent()),
|
||||
)
|
||||
// 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) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// We'll extract user info here when auth is implemented
|
||||
userID := "anonymous"
|
||||
if id, exists := c.Get("userID"); exists {
|
||||
userID = id.(string)
|
||||
}
|
||||
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"
|
||||
|
||||
path := c.Request.URL.Path
|
||||
method := c.Request.Method
|
||||
// Process request
|
||||
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
||||
next.ServeHTTP(ww, r)
|
||||
|
||||
// Process request
|
||||
c.Next()
|
||||
|
||||
// Audit log after request completes
|
||||
logger.Info("DICOM Access",
|
||||
zap.String("userID", userID),
|
||||
zap.String("action", method),
|
||||
zap.String("resource", path),
|
||||
zap.Int("status", c.Writer.Status()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// CORS middleware to handle cross-origin requests
|
||||
func CORS(allowedOrigins []string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
origin := c.Request.Header.Get("Origin")
|
||||
|
||||
// Check if origin is allowed
|
||||
allowed := false
|
||||
for _, o := range allowedOrigins {
|
||||
if o == "*" || o == origin {
|
||||
allowed = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Set CORS headers if allowed
|
||||
if allowed {
|
||||
c.Header("Access-Control-Allow-Origin", origin)
|
||||
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
||||
c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, Authorization")
|
||||
c.Header("Access-Control-Allow-Credentials", "true")
|
||||
}
|
||||
|
||||
// Handle preflight requests
|
||||
if c.Request.Method == "OPTIONS" {
|
||||
c.AbortWithStatus(204)
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
// 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()),
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
32
internal/api/middleware/pydicom.go
Normal file
32
internal/api/middleware/pydicom.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// PydicomAPIKey validates requests to pydicom endpoints by checking the API key
|
||||
func PydicomAPIKey(apiKey string, 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) {
|
||||
// Check if the API key header is present
|
||||
providedKey := r.Header.Get("X-PYDICOM-API-KEY")
|
||||
if providedKey == "" {
|
||||
logger.Warn("API key missing from PYDICOM request")
|
||||
http.Error(w, "API key required", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// Validate the API key
|
||||
if providedKey != apiKey {
|
||||
logger.Warn("Invalid API key for PYDICOM request")
|
||||
http.Error(w, "Invalid API key", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
// API key is valid, proceed to the next handler
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
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"`
|
||||
}
|
||||
54
internal/api/models/shortlink.go
Normal file
54
internal/api/models/shortlink.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package models
|
||||
|
||||
// ShortLink represents a short URL token for patient access
|
||||
type ShortLink struct {
|
||||
ID string `db:"id" json:"id"`
|
||||
Shortcode string `db:"shortcode" json:"shortcode"` // 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"`
|
||||
URI string `json:"uri"` // The URI path and query without the base 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
|
||||
}
|
||||
218
internal/api/repository/shortcode.go
Normal file
218
internal/api/repository/shortcode.go
Normal file
@@ -0,0 +1,218 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"time"
|
||||
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/database"
|
||||
"github.com/jmoiron/sqlx"
|
||||
)
|
||||
|
||||
// DBShortCode represents a shortcode from the database
|
||||
type DBShortCode struct {
|
||||
ID int `db:"id"`
|
||||
Shortcode string `db:"Shortcode"`
|
||||
ShortcodeIsUsed string `db:"ShortcodeIsUsed"`
|
||||
ShortcodeIsUsedBy_ShortlinkID *int `db:"ShortcodeIsUsedBy_ShortlinkID"`
|
||||
ShortcodeCreatedAt time.Time `db:"ShortcodeCreatedAt"`
|
||||
ShortcodeUpdatedAt time.Time `db:"ShortcodeUpdatedAt"`
|
||||
}
|
||||
|
||||
// ShortCodeRepository handles database operations related to shortcodes
|
||||
type ShortCodeRepository struct {
|
||||
*Repository
|
||||
}
|
||||
|
||||
// NewShortCodeRepository creates a new shortcode repository
|
||||
func NewShortCodeRepository() *ShortCodeRepository {
|
||||
return &ShortCodeRepository{
|
||||
Repository: NewRepository(),
|
||||
}
|
||||
}
|
||||
|
||||
// GetUnusedShortCode retrieves an unused shortcode from the database
|
||||
func (r *ShortCodeRepository) GetUnusedShortCode() (*string, error) {
|
||||
var shortcode string
|
||||
|
||||
query := `SELECT Shortcode FROM shortcodes
|
||||
WHERE ShortcodeIsUsed = 'N'
|
||||
ORDER BY RAND()
|
||||
LIMIT 1`
|
||||
|
||||
err := database.DB.Get(&shortcode, query)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("database error getting unused shortcode: %w", err)
|
||||
}
|
||||
|
||||
return &shortcode, nil
|
||||
}
|
||||
|
||||
// MarkShortCodeAsUsed marks a shortcode as used by a specific shortlink
|
||||
func (r *ShortCodeRepository) MarkShortCodeAsUsed(tx *sqlx.Tx, shortcode string, shortlinkID int) error {
|
||||
query := `UPDATE shortcodes
|
||||
SET ShortcodeIsUsed = 'Y',
|
||||
ShortcodeIsUsedBy_ShortlinkID = ?
|
||||
WHERE Shortcode = ?`
|
||||
|
||||
_, err := tx.Exec(query, shortlinkID, shortcode)
|
||||
if err != nil {
|
||||
return fmt.Errorf("database error marking shortcode as used: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarkShortCodeAsUnused marks a shortcode as unused when shortlink expires or is deleted
|
||||
func (r *ShortCodeRepository) MarkShortCodeAsUnused(shortcode string) error {
|
||||
query := `UPDATE shortcodes
|
||||
SET ShortcodeIsUsed = 'N',
|
||||
ShortcodeIsUsedBy_ShortlinkID = NULL
|
||||
WHERE Shortcode = ?`
|
||||
|
||||
_, err := database.DB.Exec(query, shortcode)
|
||||
if err != nil {
|
||||
return fmt.Errorf("database error marking shortcode as unused: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarkShortCodeAsUnusedByShortlinkID marks a shortcode as unused by shortlink ID
|
||||
func (r *ShortCodeRepository) MarkShortCodeAsUnusedByShortlinkID(shortlinkID int) error {
|
||||
query := `UPDATE shortcodes
|
||||
SET ShortcodeIsUsed = 'N',
|
||||
ShortcodeIsUsedBy_ShortlinkID = NULL
|
||||
WHERE ShortcodeIsUsedBy_ShortlinkID = ?`
|
||||
|
||||
_, err := database.DB.Exec(query, shortlinkID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("database error marking shortcode as unused by shortlink ID: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarkExpiredShortlinkShortcodesAsUnused finds all shortcodes associated with expired shortlinks
|
||||
// and marks them as unused
|
||||
func (r *ShortCodeRepository) MarkExpiredShortlinkShortcodesAsUnused() (int, error) {
|
||||
query := `
|
||||
UPDATE shortcodes sc
|
||||
INNER JOIN shortlink sl ON sc.ShortcodeIsUsedBy_ShortlinkID = sl.ShortlinkID
|
||||
SET sc.ShortcodeIsUsed = 'N',
|
||||
sc.ShortcodeIsUsedBy_ShortlinkID = NULL
|
||||
WHERE (sl.ShortlinkExpiredAt < NOW() OR sl.ShortlinkIsRevoked = TRUE)
|
||||
AND sc.ShortcodeIsUsed = 'Y'
|
||||
`
|
||||
|
||||
result, err := database.DB.Exec(query)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("database error freeing expired shortlink shortcodes: %w", err)
|
||||
}
|
||||
|
||||
count, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("error getting affected rows count: %w", err)
|
||||
}
|
||||
|
||||
return int(count), nil
|
||||
}
|
||||
|
||||
// GenerateUniqueShortCode generates a unique 5-character capital letter shortcode
|
||||
func GenerateUniqueShortCode() string {
|
||||
const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
const codeLength = 5
|
||||
|
||||
code := make([]byte, codeLength)
|
||||
for i := range code {
|
||||
code[i] = charset[rand.Intn(len(charset))]
|
||||
}
|
||||
|
||||
return string(code)
|
||||
}
|
||||
|
||||
// SeedShortCodes seeds the shortcodes table with n unique 5-character codes
|
||||
func (r *ShortCodeRepository) SeedShortCodes(n int) error {
|
||||
// Initialize random seed
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
|
||||
// Use a transaction for better performance
|
||||
tx, err := database.DB.Beginx()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to start transaction: %w", err)
|
||||
}
|
||||
|
||||
// Set up deferred rollback that will be canceled if we commit
|
||||
defer func() {
|
||||
if tx != nil {
|
||||
tx.Rollback()
|
||||
}
|
||||
}()
|
||||
|
||||
// Check how many shortcodes already exist
|
||||
var count int
|
||||
err = tx.Get(&count, "SELECT COUNT(*) FROM shortcodes")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to count existing shortcodes: %w", err)
|
||||
}
|
||||
|
||||
fmt.Printf("Found %d existing shortcodes, generating %d more\n", count, n)
|
||||
|
||||
// Track already generated codes to avoid duplicates
|
||||
generatedCodes := make(map[string]bool)
|
||||
|
||||
// Get existing codes to avoid duplicates
|
||||
existingCodes := []string{}
|
||||
err = tx.Select(&existingCodes, "SELECT Shortcode FROM shortcodes")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to retrieve existing shortcodes: %w", err)
|
||||
}
|
||||
|
||||
// Add existing codes to the map
|
||||
for _, code := range existingCodes {
|
||||
generatedCodes[code] = true
|
||||
}
|
||||
|
||||
// Prepare the insert statement
|
||||
stmt, err := tx.Prepare("INSERT INTO shortcodes (Shortcode, ShortcodeIsUsed) VALUES (?, 'N')")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to prepare statement: %w", err)
|
||||
}
|
||||
defer stmt.Close()
|
||||
|
||||
// Generate and insert the shortcodes
|
||||
inserted := 0
|
||||
attempts := 0
|
||||
maxAttempts := n * 10 // Limiting attempts to avoid infinite loop
|
||||
|
||||
for inserted < n && attempts < maxAttempts {
|
||||
attempts++
|
||||
code := GenerateUniqueShortCode()
|
||||
|
||||
if !generatedCodes[code] {
|
||||
_, err := stmt.Exec(code)
|
||||
if err != nil {
|
||||
continue // Skip if insertion fails and try another code
|
||||
}
|
||||
|
||||
generatedCodes[code] = true
|
||||
inserted++
|
||||
|
||||
// Print progress every 100 codes
|
||||
if inserted%100 == 0 {
|
||||
fmt.Printf("Generated %d/%d codes\n", inserted, n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Commit the transaction
|
||||
if err = tx.Commit(); err != nil {
|
||||
return fmt.Errorf("failed to commit transaction: %w", err)
|
||||
}
|
||||
|
||||
// Clear the tx to prevent the deferred rollback
|
||||
tx = nil
|
||||
|
||||
fmt.Printf("Successfully generated %d unique shortcodes\n", inserted)
|
||||
return nil
|
||||
}
|
||||
184
internal/api/repository/shortlink.go
Normal file
184
internal/api/repository/shortlink.go
Normal file
@@ -0,0 +1,184 @@
|
||||
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 sql.NullInt64 `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 {
|
||||
var createdByID string
|
||||
if s.ShortlinkCreate_UserID.Valid {
|
||||
createdByID = fmt.Sprintf("%d", s.ShortlinkCreate_UserID.Int64)
|
||||
} else {
|
||||
createdByID = ""
|
||||
}
|
||||
|
||||
return &models.ShortLink{
|
||||
ID: fmt.Sprintf("%d", s.ShortlinkID),
|
||||
Shortcode: 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: createdByID,
|
||||
}
|
||||
}
|
||||
|
||||
// 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(), ?)`
|
||||
|
||||
var createdByID sql.NullInt64
|
||||
|
||||
// Handle empty CreatedByID
|
||||
if shortLink.CreatedByID != "" {
|
||||
id, err := strconv.Atoi(shortLink.CreatedByID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid created by ID: %w", err)
|
||||
}
|
||||
createdByID.Int64 = int64(id)
|
||||
createdByID.Valid = true
|
||||
} else {
|
||||
// If CreatedByID is empty, insert NULL
|
||||
createdByID.Valid = false
|
||||
}
|
||||
|
||||
expiresAt, err := time.Parse(time.RFC3339, shortLink.ExpiresAt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid expiration date: %w", err)
|
||||
}
|
||||
|
||||
_, err = tx.Exec(
|
||||
query,
|
||||
shortLink.Shortcode,
|
||||
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.Shortcode,
|
||||
)
|
||||
|
||||
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
|
||||
}
|
||||
@@ -1,38 +1,47 @@
|
||||
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"
|
||||
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/middleware"
|
||||
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/gin-gonic/gin"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/go-chi/cors"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// TODO: Refactor dari gin dengan chi
|
||||
|
||||
// SetupRouter configures and returns the API router
|
||||
func SetupRouter(cfg *config.Config, logger *zap.Logger) *gin.Engine {
|
||||
// Set Gin mode
|
||||
if cfg.LogLevel == "debug" {
|
||||
gin.SetMode(gin.DebugMode)
|
||||
} else {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
}
|
||||
func SetupRouter(cfg *config.Config, logger *zap.Logger) http.Handler {
|
||||
r := chi.NewRouter()
|
||||
|
||||
// Initialize the router
|
||||
r := gin.New()
|
||||
// Base middleware
|
||||
r.Use(middleware.RequestID)
|
||||
r.Use(middleware.RealIP)
|
||||
r.Use(middleware.Recoverer)
|
||||
r.Use(apiMiddleware.Logger(logger))
|
||||
|
||||
// Add middleware
|
||||
r.Use(gin.Recovery())
|
||||
r.Use(middleware.Logger(logger))
|
||||
r.Use(middleware.CORS(cfg.AllowedOrigins))
|
||||
// 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
|
||||
}))
|
||||
|
||||
// Setup health check
|
||||
r.GET("/health", handlers.HealthCheck)
|
||||
r.Options("/*", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
|
||||
// Initialize Google auth client
|
||||
// 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))
|
||||
@@ -41,32 +50,120 @@ func SetupRouter(cfg *config.Config, logger *zap.Logger) *gin.Engine {
|
||||
// Initialize Healthcare API client
|
||||
healthcareClient := proxy.NewClient(googleAuth, cfg.Google)
|
||||
|
||||
// DICOM Web routes
|
||||
dicomGroup := r.Group("/dicomWeb")
|
||||
{
|
||||
dicomHandler := handlers.NewDicomHandler(healthcareClient, logger)
|
||||
|
||||
// Add audit logging middleware to DICOM routes
|
||||
dicomGroup.Use(middleware.AuditLog(logger))
|
||||
|
||||
// WADO routes
|
||||
dicomGroup.Any("/wado/*path", dicomHandler.ForwardRequest)
|
||||
|
||||
// QIDO routes
|
||||
dicomGroup.Any("/qido/*path", dicomHandler.ForwardRequest)
|
||||
|
||||
// STOW routes
|
||||
dicomGroup.Any("/stow/*path", dicomHandler.ForwardRequest)
|
||||
// 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="
|
||||
}
|
||||
|
||||
// Future auth routes for doctors
|
||||
authGroup := r.Group("/auth")
|
||||
{
|
||||
// Auth handlers will be implemented later
|
||||
authHandler := handlers.NewAuthHandler(logger)
|
||||
authGroup.POST("/login", authHandler.Login)
|
||||
authGroup.POST("/logout", authHandler.Logout)
|
||||
}
|
||||
// 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)
|
||||
|
||||
// Shortcode recycling - only for admin role (role check is in the handler)
|
||||
r.Post("/recycle-shortcode", shortLinkHandler.RecycleShortcodes)
|
||||
|
||||
// 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
|
||||
|
||||
// DICOM upload endpoint - for pydicom-uploader service
|
||||
r.Post("/", dicomHandler.ForwardRequest) // Upload studies
|
||||
})
|
||||
|
||||
// Expertise doctors have full access to all DICOM endpoints
|
||||
r.With(apiMiddleware.RoleRequired("expertise_doctor")).HandleFunc("/*", dicomHandler.ForwardRequest)
|
||||
})
|
||||
})
|
||||
|
||||
// PYDICOM Uploader Service endpoint
|
||||
// This endpoint is protected by API key middleware
|
||||
r.Group(func(r chi.Router) {
|
||||
// Apply PYDICOM API key middleware
|
||||
r.Use(apiMiddleware.PydicomAPIKey(cfg.Auth.PydicomApiKey, logger))
|
||||
|
||||
// Create handler for PYDICOM uploads
|
||||
registerService := service.NewRegisterService(logger)
|
||||
shortLinkService := service.NewShortLinkService(
|
||||
jwtManager,
|
||||
logger,
|
||||
cfg.Shortlink.BaseURL,
|
||||
cfg.Shortlink.DefaultExpiryHours,
|
||||
cfg.Shortlink.MaxAttempts,
|
||||
)
|
||||
pydicomHandler := handlers.NewPydicomHandler(logger, shortLinkService, registerService)
|
||||
|
||||
// Add route for uploaded DICOM
|
||||
r.Post("/uploaded-dicom", pydicomHandler.HandleUploadedDicom)
|
||||
})
|
||||
|
||||
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
|
||||
}
|
||||
476
internal/api/service/shortlink_service.go
Normal file
476
internal/api/service/shortlink_service.go
Normal file
@@ -0,0 +1,476 @@
|
||||
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. 5 digit kapital semua
|
||||
ShortTokenLength = 5
|
||||
)
|
||||
|
||||
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")
|
||||
ErrNoShortcodes = errors.New("no unused shortcodes available")
|
||||
)
|
||||
|
||||
// ShortLinkService handles operations related to short links
|
||||
type ShortLinkService struct {
|
||||
jwtManager *auth.JWTManager
|
||||
logger *zap.Logger
|
||||
shortLinkRepo *repository.ShortLinkRepository
|
||||
shortCodeRepo *repository.ShortCodeRepository
|
||||
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(),
|
||||
shortCodeRepo: repository.NewShortCodeRepository(),
|
||||
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.Shortcode))
|
||||
|
||||
// Generate the full URL and URI
|
||||
uri := fmt.Sprintf("short-auth?short=%s", existingShortLink.Shortcode)
|
||||
fullURL := fmt.Sprintf("%s/%s", s.baseURL, uri)
|
||||
|
||||
return &models.GenerateShortLinkResponse{
|
||||
ShortToken: existingShortLink.Shortcode,
|
||||
FullURL: fullURL,
|
||||
URI: uri,
|
||||
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)
|
||||
|
||||
// Hash the DOB for secure storage
|
||||
hashedDOB := hashDOB(dob)
|
||||
|
||||
// Start a transaction for creating the shortlink and updating the shortcode
|
||||
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()
|
||||
}
|
||||
}()
|
||||
|
||||
// Get an unused shortcode from the bank
|
||||
unusedShortcode, err := s.shortCodeRepo.GetUnusedShortCode()
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to get unused shortcode", zap.Error(err))
|
||||
return nil, ErrNoShortcodes
|
||||
}
|
||||
|
||||
if unusedShortcode == nil {
|
||||
s.logger.Error("No unused shortcodes available in the bank")
|
||||
return nil, ErrNoShortcodes
|
||||
}
|
||||
|
||||
// Create the short link record
|
||||
shortLink := &models.ShortLink{
|
||||
Shortcode: *unusedShortcode,
|
||||
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,
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// Get the ID of the created shortlink
|
||||
var shortlinkID int
|
||||
err = tx.Get(&shortlinkID, "SELECT ShortlinkID FROM shortlink WHERE ShortlinkCode = ?", shortLink.Shortcode)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to get shortlink ID", zap.Error(err))
|
||||
return nil, ErrCreationFailed
|
||||
}
|
||||
|
||||
// Mark the shortcode as used
|
||||
err = s.shortCodeRepo.MarkShortCodeAsUsed(tx, shortLink.Shortcode, shortlinkID)
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to mark shortcode as used", 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 and URI
|
||||
uri := fmt.Sprintf("short-auth?short=%s", shortLink.Shortcode)
|
||||
fullURL := fmt.Sprintf("%s/%s", s.baseURL, uri)
|
||||
|
||||
return &models.GenerateShortLinkResponse{
|
||||
ShortToken: shortLink.Shortcode,
|
||||
FullURL: fullURL,
|
||||
URI: uri,
|
||||
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
|
||||
}
|
||||
|
||||
// CleanupExpiredShortcodes checks for expired shortlinks and frees their shortcodes
|
||||
func (s *ShortLinkService) CleanupExpiredShortcodes() (int, error) {
|
||||
count, err := s.shortCodeRepo.MarkExpiredShortlinkShortcodesAsUnused()
|
||||
if err != nil {
|
||||
s.logger.Error("Failed to clean up expired shortcodes", zap.Error(err))
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if count > 0 {
|
||||
s.logger.Info("Freed shortcodes from expired shortlinks", zap.Int("count", count))
|
||||
}
|
||||
|
||||
return count, 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
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package auth
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"golang.org/x/oauth2"
|
||||
@@ -11,12 +12,10 @@ import (
|
||||
"google.golang.org/api/option"
|
||||
)
|
||||
|
||||
// TODO: Ganti Auth dengan lib Goth
|
||||
|
||||
// GoogleClient handles authentication with Google APIs
|
||||
type GoogleClient struct {
|
||||
credentialsPath string
|
||||
tokenSource *google.Credentials
|
||||
tokenSource oauth2.TokenSource
|
||||
}
|
||||
|
||||
// NewGoogleClient creates a new Google authentication client
|
||||
@@ -26,24 +25,33 @@ func NewGoogleClient(credentialsPath string) (*GoogleClient, error) {
|
||||
}
|
||||
|
||||
// Initialize on creation to validate credentials
|
||||
if _, err := client.getToken(); err != nil {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Try reading the credentials file
|
||||
credBytes, err := os.ReadFile(credentialsPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read credentials file: %w", err)
|
||||
}
|
||||
|
||||
// Create credentials from the JSON key file
|
||||
creds, err := google.CredentialsFromJSON(ctx, credBytes, healthcare.CloudPlatformScope)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to initialize Google client: %w", err)
|
||||
}
|
||||
|
||||
client.tokenSource = creds.TokenSource
|
||||
return client, nil
|
||||
}
|
||||
|
||||
// GetAccessToken returns a valid access token for Google APIs
|
||||
func (c *GoogleClient) GetAccessToken() (string, error) {
|
||||
tokenSource, err := c.getToken()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
_, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Retrieve the token using the Token() method
|
||||
token, err := tokenSource.Token()
|
||||
token, err := c.tokenSource.Token()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to retrieve token: %w", err)
|
||||
return "", fmt.Errorf("failed to get access token: %w", err)
|
||||
}
|
||||
|
||||
return token.AccessToken, nil
|
||||
@@ -58,21 +66,3 @@ func (c *GoogleClient) GetHealthcareClient(ctx context.Context) (*healthcare.Ser
|
||||
|
||||
return healthcare.NewService(ctx, opts...)
|
||||
}
|
||||
|
||||
// getToken retrieves a token from the credentials file
|
||||
func (c *GoogleClient) getToken() (oauth2.TokenSource, error) { // Change return type to oauth2.TokenSource
|
||||
if c.tokenSource != nil {
|
||||
return c.tokenSource.TokenSource, nil // Access the TokenSource field
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
credentials, err := google.FindDefaultCredentials(ctx, healthcare.CloudPlatformScope)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get default credentials: %w", err)
|
||||
}
|
||||
|
||||
c.tokenSource = credentials
|
||||
return credentials.TokenSource, nil // Return the TokenSource field
|
||||
}
|
||||
|
||||
182
internal/auth/jwt.go
Normal file
182
internal/auth/jwt.go
Normal file
@@ -0,0 +1,182 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidToken = errors.New("invalid token")
|
||||
ErrExpiredToken = errors.New("token has expired")
|
||||
)
|
||||
|
||||
// JWTManager handles JWT token operations
|
||||
type JWTManager struct {
|
||||
secretKey string
|
||||
accessExpiry time.Duration
|
||||
refreshExpiry time.Duration
|
||||
}
|
||||
|
||||
// NewJWTManager creates a new JWT manager
|
||||
func NewJWTManager(secretKey string, accessExpiry, refreshExpiry time.Duration) *JWTManager {
|
||||
return &JWTManager{
|
||||
secretKey: secretKey,
|
||||
accessExpiry: accessExpiry,
|
||||
refreshExpiry: refreshExpiry,
|
||||
}
|
||||
}
|
||||
|
||||
// CustomClaims contains the claims we want in our tokens
|
||||
type CustomClaims struct {
|
||||
UserID string `json:"user_id"`
|
||||
Email string `json:"email"`
|
||||
Role string `json:"role"`
|
||||
UserName string `json:"user_name"`
|
||||
TokenType string `json:"token_type"` // access or refresh
|
||||
|
||||
// Patient-specific fields
|
||||
PatientID string `json:"patient_id,omitempty"`
|
||||
PatientName string `json:"patient_name,omitempty"`
|
||||
StudyIUIDs []string `json:"study_iuids,omitempty"`
|
||||
AccessionNumbers []string `json:"accession_numbers,omitempty"`
|
||||
|
||||
// Navigation and permissions
|
||||
HomeURL string `json:"home_url,omitempty"`
|
||||
StudyList string `json:"study_list,omitempty"` // enabled or disabled
|
||||
FilterURL string `json:"filter_url,omitempty"` // for ref_doctor filtering
|
||||
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
// GenerateAccessToken creates a new access token with role-specific claims
|
||||
func (m *JWTManager) GenerateAccessToken(userID, email, role, userName string, additionalClaims map[string]interface{}) (string, error) {
|
||||
claims := CustomClaims{
|
||||
UserID: userID,
|
||||
Email: email,
|
||||
Role: role,
|
||||
UserName: userName,
|
||||
TokenType: "access",
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(m.accessExpiry)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
}
|
||||
|
||||
// Add role-specific additional claims
|
||||
if additionalClaims != nil {
|
||||
// Handle string claims
|
||||
if val, ok := additionalClaims["patient_id"].(string); ok {
|
||||
claims.PatientID = val
|
||||
}
|
||||
if val, ok := additionalClaims["patient_name"].(string); ok {
|
||||
claims.PatientName = val
|
||||
}
|
||||
if val, ok := additionalClaims["home_url"].(string); ok {
|
||||
claims.HomeURL = val
|
||||
}
|
||||
if val, ok := additionalClaims["study_list"].(string); ok {
|
||||
claims.StudyList = val
|
||||
}
|
||||
if val, ok := additionalClaims["filter_url"].(string); ok {
|
||||
claims.FilterURL = val
|
||||
}
|
||||
|
||||
// Handle array claims
|
||||
if val, ok := additionalClaims["study_iuids"].([]string); ok {
|
||||
claims.StudyIUIDs = val
|
||||
}
|
||||
if val, ok := additionalClaims["accession_numbers"].([]string); ok {
|
||||
claims.AccessionNumbers = val
|
||||
}
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString([]byte(m.secretKey))
|
||||
}
|
||||
|
||||
// GenerateRefreshToken creates a new refresh token with the same claims as access token
|
||||
func (m *JWTManager) GenerateRefreshToken(userID, email, role, userName string, additionalClaims map[string]interface{}) (string, error) {
|
||||
claims := CustomClaims{
|
||||
UserID: userID,
|
||||
Email: email,
|
||||
Role: role,
|
||||
UserName: userName,
|
||||
TokenType: "refresh",
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(m.refreshExpiry)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
}
|
||||
|
||||
// Add role-specific additional claims
|
||||
if additionalClaims != nil {
|
||||
// Handle string claims
|
||||
if val, ok := additionalClaims["patient_id"].(string); ok {
|
||||
claims.PatientID = val
|
||||
}
|
||||
if val, ok := additionalClaims["patient_name"].(string); ok {
|
||||
claims.PatientName = val
|
||||
}
|
||||
if val, ok := additionalClaims["home_url"].(string); ok {
|
||||
claims.HomeURL = val
|
||||
}
|
||||
if val, ok := additionalClaims["study_list"].(string); ok {
|
||||
claims.StudyList = val
|
||||
}
|
||||
if val, ok := additionalClaims["filter_url"].(string); ok {
|
||||
claims.FilterURL = val
|
||||
}
|
||||
|
||||
// Handle array claims
|
||||
if val, ok := additionalClaims["study_iuids"].([]string); ok {
|
||||
claims.StudyIUIDs = val
|
||||
}
|
||||
if val, ok := additionalClaims["accession_numbers"].([]string); ok {
|
||||
claims.AccessionNumbers = val
|
||||
}
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString([]byte(m.secretKey))
|
||||
}
|
||||
|
||||
// ValidateToken validates a token and returns the claims
|
||||
func (m *JWTManager) ValidateToken(tokenString string) (*CustomClaims, error) {
|
||||
token, err := jwt.ParseWithClaims(
|
||||
tokenString,
|
||||
&CustomClaims{},
|
||||
func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return []byte(m.secretKey), nil
|
||||
},
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, jwt.ErrTokenExpired) {
|
||||
return nil, ErrExpiredToken
|
||||
}
|
||||
return nil, ErrInvalidToken
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(*CustomClaims)
|
||||
if !ok || !token.Valid {
|
||||
return nil, ErrInvalidToken
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
// GetAccessExpiry returns the configured access token expiry duration
|
||||
func (m *JWTManager) GetAccessExpiry() time.Duration {
|
||||
return m.accessExpiry
|
||||
}
|
||||
|
||||
// GetRefreshExpiry returns the configured refresh token expiry duration
|
||||
func (m *JWTManager) GetRefreshExpiry() time.Duration {
|
||||
return m.refreshExpiry
|
||||
}
|
||||
43
internal/database/database.go
Normal file
43
internal/database/database.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
"github.com/jmoiron/sqlx"
|
||||
)
|
||||
|
||||
// DB is the database instance
|
||||
var DB *sqlx.DB
|
||||
|
||||
// Initialize creates and configures the database connection
|
||||
func Initialize(dsn string, maxOpenConns, maxIdleConns int, connMaxLifetime time.Duration) error {
|
||||
var err error
|
||||
|
||||
// Connect to the database
|
||||
DB, err = sqlx.Connect("mysql", dsn)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to connect to database: %w", err)
|
||||
}
|
||||
|
||||
// Configure connection pool
|
||||
DB.SetMaxOpenConns(maxOpenConns)
|
||||
DB.SetMaxIdleConns(maxIdleConns)
|
||||
DB.SetConnMaxLifetime(connMaxLifetime)
|
||||
|
||||
// Check connection
|
||||
if err := DB.Ping(); err != nil {
|
||||
return fmt.Errorf("failed to ping database: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close closes the database connection
|
||||
func Close() error {
|
||||
if DB != nil {
|
||||
return DB.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -45,17 +45,25 @@ type Response struct {
|
||||
}
|
||||
|
||||
// ForwardRequest forwards a request to Google Healthcare API
|
||||
func (c *Client) ForwardRequest(ctx context.Context, method, requestType, path string, headers map[string]string, body []byte) (*Response, error) {
|
||||
// Get access token
|
||||
func (c *Client) ForwardRequest(ctx context.Context, method, path string, headers map[string]string, body []byte) (*Response, error) {
|
||||
token, err := c.googleAuth.GetAccessToken()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get access token: %w", err)
|
||||
}
|
||||
|
||||
// Build URL
|
||||
// Build URL - Simplified to exactly match OHIF's expected structure
|
||||
baseURL := fmt.Sprintf("https://healthcare.googleapis.com/v1/projects/%s/locations/%s/datasets/%s/dicomStores/%s/dicomWeb",
|
||||
c.projectID, c.location, c.dataset, c.dicomStore)
|
||||
fullURL := fmt.Sprintf("%s/%s%s", baseURL, requestType, path)
|
||||
|
||||
// Ensure path starts with /
|
||||
if len(path) > 0 && path[0] != '/' {
|
||||
path = "/" + path
|
||||
}
|
||||
|
||||
fullURL := baseURL + path
|
||||
|
||||
// Log the full URL for debugging
|
||||
fmt.Printf("Requesting URL: %s\n", fullURL)
|
||||
|
||||
// Create request
|
||||
req, err := http.NewRequestWithContext(ctx, method, fullURL, bytes.NewReader(body))
|
||||
|
||||
87
test/http/dicom-proxy.http
Normal file
87
test/http/dicom-proxy.http
Normal file
@@ -0,0 +1,87 @@
|
||||
### Local OHIF Proxy Test File
|
||||
@token = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiMSIsImVtYWlsIjoiYWRtaW5AZXhhbXBsZS5jb20iLCJyb2xlIjoiYWRtaW4iLCJ1c2VyX25hbWUiOiJBZG1pbiBVc2VyIiwidG9rZW5fdHlwZSI6ImFjY2VzcyIsImhvbWVfdXJsIjoiLyIsInN0dWR5X2xpc3QiOiJlbmFibGVkIiwiZXhwIjoxNzQ3NDcyMTE5LCJpYXQiOjE3NDczODU3MTl9.rLB8q2Wwt2aL813lf-GwuS14dO5WlJPPS3sP5OGJdO0
|
||||
@baseUrl = http://localhost:5555
|
||||
|
||||
# @baseUrl = http://devone.aplikasi.web.id:5555
|
||||
# @baseUrl = http://152.42.173.210:5555
|
||||
|
||||
### 1. Health Check
|
||||
# Verifies that the proxy server is running
|
||||
GET {{baseUrl}}/health
|
||||
Accept: application/json
|
||||
|
||||
### 2. QIDO-RS: Search for Studies
|
||||
# Returns all studies (should return a list of DICOM studies if any exist)
|
||||
GET {{baseUrl}}/dicomWeb/studies
|
||||
Accept: application/dicom+json
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### 3. QIDO-RS: Search for Studies with Patient Name
|
||||
# Returns studies matching patient name (replace SMITH with a name in your dataset)
|
||||
GET {{baseUrl}}/dicomWeb/studies?limit=10&offset=0&fuzzymatching=true&includefield=00081030%2C00080060%2C00080090&00080090=DR.%20HERWINDO%20RIDWAN%2C%20SP.OT
|
||||
Accept: application/dicom+json
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### 4. QIDO-RS: Search for Studies with Date Range
|
||||
# Returns studies within a date range
|
||||
GET {{baseUrl}}/dicomWeb/studies?StudyDate=20250301-20250415
|
||||
Accept: application/dicom+json
|
||||
Authorization: Bearer {{ token }}
|
||||
|
||||
### 5. QIDO-RS: Search for Series in a Study
|
||||
# Replace STUDY_INSTANCE_UID with an actual Study UID from your data
|
||||
# (Run test #2 first and copy a StudyInstanceUID from the response)
|
||||
GET {{baseUrl}}/dicomWeb/studies/STUDY_INSTANCE_UID/series
|
||||
Accept: application/dicom+json
|
||||
|
||||
### 6. QIDO-RS: Search for Instances in a Series
|
||||
# Replace STUDY_INSTANCE_UID and SERIES_INSTANCE_UID with actual values
|
||||
GET {{baseUrl}}/dicomWeb/studies/STUDY_INSTANCE_UID/series/SERIES_INSTANCE_UID/instances
|
||||
Accept: application/dicom+json
|
||||
|
||||
### 7. WADO-RS: Retrieve Study Metadata
|
||||
# Replace STUDY_INSTANCE_UID with an actual Study UID
|
||||
GET {{baseUrl}}/dicomWeb/studies/STUDY_INSTANCE_UID/metadata
|
||||
Accept: application/dicom+json
|
||||
|
||||
### 8. WADO-RS: Retrieve Series Metadata
|
||||
# Replace STUDY_INSTANCE_UID and SERIES_INSTANCE_UID with actual values
|
||||
GET {{baseUrl}}/dicomWeb/studies/STUDY_INSTANCE_UID/series/SERIES_INSTANCE_UID/metadata
|
||||
Accept: application/dicom+json
|
||||
|
||||
### 9. WADO-RS: Retrieve Instance Metadata
|
||||
# Replace STUDY_INSTANCE_UID, SERIES_INSTANCE_UID and SOP_INSTANCE_UID with actual values
|
||||
GET {{baseUrl}}/dicomWeb/studies/1.2.826.0.1.3680043.9.7307.1.202503196393.01/series/1.2.826.0.1.3680043.2.1545.1.2.1.7.20250319.100353.734.4/metadata
|
||||
Accept: */*
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### 10. WADO-RS: Retrieve Instance
|
||||
# Replace STUDY_INSTANCE_UID, SERIES_INSTANCE_UID and SOP_INSTANCE_UID with actual values
|
||||
GET {{baseUrl}}/dicomWeb/studies/STUDY_INSTANCE_UID/series/SERIES_INSTANCE_UID/instances/SOP_INSTANCE_UID
|
||||
Accept: application/dicom
|
||||
|
||||
### 11. WADO-RS: Retrieve Frame
|
||||
# Replace STUDY_INSTANCE_UID, SERIES_INSTANCE_UID, SOP_INSTANCE_UID with actual values
|
||||
# This retrieves frame #1 from a multiframe image
|
||||
GET {{baseUrl}}/dicomWeb/studies/1.2.826.0.1.3680043.9.7307.1.202503196393.01/series/1.2.826.0.1.3680043.2.1545.1.2.1.7.20250319.100353.734.4/instances/1.2.826.0.1.3680043.2.1545.1.2.1.7.20250319.100353.1.5/frames/1
|
||||
Accept: */*
|
||||
|
||||
### 12. WADO-RS: Retrieve Frame as JPEG
|
||||
# Replace STUDY_INSTANCE_UID, SERIES_INSTANCE_UID, SOP_INSTANCE_UID with actual values
|
||||
# This retrieves frame #1 as a rendered JPEG image
|
||||
GET {{baseUrl}}/dicomWeb/studies/1.2.826.0.1.3680043.9.7307.1.202503196393.01/series/1.2.826.0.1.3680043.2.1545.1.2.1.7.20250319.100353.734.4/instances/1.2.826.0.1.3680043.2.1545.1.2.1.7.20250319.100353.1.5/frames/1/rendered
|
||||
Accept: image/jpeg
|
||||
|
||||
|
||||
####
|
||||
GET {{baseUrl}}/dicomWeb/studies?limit=101&offset=0&fuzzymatching=true&includefield=00081030,00080060&StudyInstanceUID=1.2.826.0.1.3680043.9.7307.1.202503196393.01
|
||||
|
||||
### 13. DELETE Study
|
||||
# Deletes a specific study
|
||||
DELETE {{baseUrl}}/dicomWeb/studies/1.2.826.0.1.3680043.0.1252.1.20250516.144411.1639014.3
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
###
|
||||
curl -X DELETE \
|
||||
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
|
||||
"https://healthcare.googleapis.com/v1/projects/ohifproxy/locations/asia-southeast2/datasets/sas-storage/dicomStores/store-1/dicomWeb/studies/1.2.826.0.1.3680043.0.1252.1.20250516.144411.1639014.3"
|
||||
57
test/http/ohif-flow.http
Normal file
57
test/http/ohif-flow.http
Normal file
@@ -0,0 +1,57 @@
|
||||
@token = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiMSIsImVtYWlsIjoiYWRtaW5AZXhhbXBsZS5jb20iLCJyb2xlIjoiYWRtaW4iLCJ1c2VyX25hbWUiOiJBZG1pbiBVc2VyIiwidG9rZW5fdHlwZSI6ImFjY2VzcyIsImhvbWVfdXJsIjoiLyIsInN0dWR5X2xpc3QiOiJlbmFibGVkIiwiZXhwIjoxNzQ3Mzg0MDE2LCJpYXQiOjE3NDcyOTc2MTZ9.Ak1DECP1MXzQAPyU-AJM6Tsu6-sw04UtWYvY37-SaT4
|
||||
@token_exp_doctor = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiMSIsImVtYWlsIjoiYWRtaW4iLCJyb2xlIjoiZXhwZXJ0aXNlX2RvY3RvciIsInRva2VuX3R5cGUiOiJhY2Nlc3MiLCJleHAiOjE3NDY1MDQ1MTYsImlhdCI6MTc0NjQxODExNn0.vlDrns1oPFXHE5--TmWqwzvzxnfcCPcV2UW8_4GwDwE
|
||||
@baseUrl = http://localhost:5555
|
||||
|
||||
### Login Patient
|
||||
POST {{baseUrl}}/auth/login
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"email": "admin@example.com",
|
||||
"password": "password123"
|
||||
}
|
||||
|
||||
### Login Admin / Exp_doctor (ALL ACCESS)
|
||||
POST {{baseUrl}}/auth/login
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"email": "admin",
|
||||
"password": "admin"
|
||||
}
|
||||
|
||||
### * === PATIENT === *
|
||||
|
||||
# Destination URL / OHIF Viewer URL: http://152.42.173.210:3000/viewer?StudyInstanceUIDs=1.2.826.0.1.3680043.9.7307.1.202503196393.01
|
||||
|
||||
### Study where StudyIUID
|
||||
GET {{baseUrl}}/dicomWeb/studies?limit=101&offset=0&fuzzymatching=true&includefield=00081030,00080060&StudyInstanceUID=1.2.826.0.1.3680043.9.7307.1.20180530066
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Series List
|
||||
GET {{baseUrl}}/dicomWeb/studies/1.2.826.0.1.3680043.9.7307.1.20180530066/series?includefield=00080021,00080031,0008103E,00200011
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Semua Study dari Patient ID
|
||||
GET {{baseUrl}}/dicomWeb/studies?00100020=MR00000359&limit=101&offset=0&fuzzymatching=true&includefield=00081030,00080060
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Metadata
|
||||
GET {{baseUrl}}/dicomWeb/studies/1.2.826.0.1.3680043.9.7307.1.202503196393.01/series/1.2.826.0.1.3680043.2.1545.1.2.1.7.20250319.100353.734.4/metadata
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Modality and Study Description untuk Study Instance UID = ...
|
||||
GET {{baseUrl}}/dicomWeb/studies?limit=101&offset=0&fuzzymatching=true&includefield=00081030,00080060&StudyInstanceUID=1.2.826.0.1.3680043.9.7307.1.202503196393.01
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### DICOM Frames
|
||||
GET {{baseUrl}}/dicomWeb/studies/1.2.826.0.1.3680043.9.7307.1.202503196393.01/series/1.2.826.0.1.3680043.2.1545.1.2.1.7.20250319.100353.734.4/instances/1.2.826.0.1.3680043.2.1545.1.2.1.7.20250319.100353.1.5/frames/1
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Modality and Study Description untuk semua studies pada PatientID = ...
|
||||
GET {{baseUrl}}/dicomWeb/studies?00100020=MR00000359&limit=101&offset=0&fuzzymatching=true&includefield=00081030,00080060
|
||||
Authorization: Bearer {{token}}
|
||||
|
||||
### Accession, Deskripsi Studi, Umur, dan format nama pasien where StudyInstanceUID = ...
|
||||
GET {{baseUrl}}/dicomWeb/studies?limit=101&offset=0&fuzzymatching=false&includefield=00080050,00081030,00101010,0010004&StudyInstanceUID=1.2.826.0.1.3680043.9.7307.1.202503196393.01
|
||||
Authorization: Bearer {{token}}
|
||||
62
test/http/pydicom-upload.http
Normal file
62
test/http/pydicom-upload.http
Normal file
@@ -0,0 +1,62 @@
|
||||
# pydicom-upload.http
|
||||
# This file can be used with REST Client extension in VS Code to test the PYDICOM upload endpoint
|
||||
|
||||
@baseUrl = http://localhost:5555
|
||||
@pydicomApiKey=2f0ff447b2c3aeef2004e83a750ded97e29ba8c0ccc70053d5e26f5d715e42ff
|
||||
|
||||
### Test the PYDICOM upload endpoint
|
||||
POST {{baseUrl}}/uploaded-dicom
|
||||
X-PYDICOM-API-KEY: {{pydicomApiKey}}
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"email": "patient2@example.com",
|
||||
"password": "password123",
|
||||
"name": "Bobon Santoso",
|
||||
"role": "patient",
|
||||
"patient": {
|
||||
"patient_id": "MR00000359",
|
||||
"patient_name": "Bobon Santoso",
|
||||
"date_of_birth": "1985-01-01"
|
||||
},
|
||||
"studies": [
|
||||
{
|
||||
"study_instance_uid": "1.2.826.0.1.3680043.9.7307.1.202503196393.01",
|
||||
"accession_number": "CR.250319.6393.01",
|
||||
"study_date": "2025-03-19",
|
||||
"study_description": "MRI Scan"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
### Expected Response:
|
||||
# {
|
||||
# "short_token": "LDYZX",
|
||||
# "full_url": "http://localhost:3333/short-auth?short=LDYZX",
|
||||
# "expires_at": "2025-05-18T02:04:46Z",
|
||||
# "is_existing": true
|
||||
# }
|
||||
|
||||
POST {{baseUrl}}/uploaded_dicom
|
||||
X-PYDICOM-API-KEY: {{pydicomApiKey}}
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"email": "randomuser@example.com",
|
||||
"password": "securepassword456",
|
||||
"name": "John Doe",
|
||||
"role": "patient",
|
||||
"patient": {
|
||||
"patient_id": "MR00000789",
|
||||
"patient_name": "John Doe",
|
||||
"date_of_birth": "1990-07-15"
|
||||
},
|
||||
"studies": [
|
||||
{
|
||||
"study_instance_uid": "1.2.826.0.1.3680043.9.1234.1.202507151234.01",
|
||||
"accession_number": "CR.150720.1234.01",
|
||||
"study_date": "2025-07-15",
|
||||
"study_description": "CT Scan"
|
||||
}
|
||||
]
|
||||
}
|
||||
178
test/http/register-flow.http
Normal file
178
test/http/register-flow.http
Normal file
@@ -0,0 +1,178 @@
|
||||
### Register new user, patient, and doctor tests
|
||||
|
||||
# Base URL for the API
|
||||
@baseUrl = http://localhost:5555
|
||||
|
||||
|
||||
### Register an admin user
|
||||
POST {{baseUrl}}/auth/register
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"email": "admin@example.com",
|
||||
"password": "password123",
|
||||
"name": "Admin User",
|
||||
"role": "admin"
|
||||
}
|
||||
|
||||
### Register a new patient with multiple studies
|
||||
POST {{baseUrl}}/auth/register
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"email": "patient1@example.com",
|
||||
"password": "password123",
|
||||
"name": "DIDIT SUYATNA^R.10049.18",
|
||||
"role": "patient",
|
||||
"patient": {
|
||||
"patient_id": "00211622",
|
||||
"patient_name": "DIDIT SUYATNA^R.10049.18",
|
||||
"date_of_birth": "1980-01-01"
|
||||
},
|
||||
"studies": [
|
||||
{
|
||||
"study_instance_uid": "1.2.826.0.1.3680043.9.7307.1.20180530066",
|
||||
"accession_number": "CR.180530.066",
|
||||
"study_date": "2018-05-30",
|
||||
"study_description": "Chest X-Ray"
|
||||
}
|
||||
]
|
||||
}
|
||||
###
|
||||
POST {{baseUrl}}/auth/register
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"email": "patient1@example.com",
|
||||
"password": "password123",
|
||||
"name": "DIDIT SUYATNA^R.10049.18",
|
||||
"role": "patient",
|
||||
"patient": {
|
||||
"patient_id": "00211622",
|
||||
"patient_name": "DIDIT SUYATNA^R.10049.18",
|
||||
"date_of_birth": "1980-01-01"
|
||||
},
|
||||
"studies": [
|
||||
{
|
||||
"study_instance_uid": "1.2.826.0.1.3680043.9.7307.1.20180713036",
|
||||
"accession_number": "CR.180713.036",
|
||||
"study_date": "2018-07-13",
|
||||
"study_description": "Follow-up X-Ray"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
### Register another patient with one study
|
||||
POST {{baseUrl}}/auth/register
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"email": "patient2@example.com",
|
||||
"password": "password123",
|
||||
"name": "Bobon Santoso",
|
||||
"role": "patient",
|
||||
"patient": {
|
||||
"patient_id": "MR00000359",
|
||||
"patient_name": "Bobon Santoso",
|
||||
"date_of_birth": "1985-01-01"
|
||||
},
|
||||
"studies": [
|
||||
{
|
||||
"study_instance_uid": "1.2.826.0.1.3680043.9.7307.1.202503196393.01",
|
||||
"accession_number": "CR.250319.6393.01",
|
||||
"study_date": "2025-03-19",
|
||||
"study_description": "MRI Scan"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
### Register another referring doctor
|
||||
POST {{baseUrl}}/auth/register
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"email": "doctor@example.com",
|
||||
"password": "password123",
|
||||
"name": "DR. HERWINDO RIDWAN, SP.OT",
|
||||
"role": "ref_doctor",
|
||||
"doctor": {
|
||||
"doctor_id": "DOC002",
|
||||
"doctor_name": "DR. HERWINDO RIDWAN, SP.OT"
|
||||
}
|
||||
}
|
||||
|
||||
### Register another referring doctor
|
||||
POST {{baseUrl}}/auth/register
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"email": "doctor2@example.com",
|
||||
"password": "password123",
|
||||
"name": "Referring^Physician",
|
||||
"role": "ref_doctor",
|
||||
"doctor": {
|
||||
"doctor_id": "DOC003",
|
||||
"doctor_name": "Referring^Physician"
|
||||
}
|
||||
}
|
||||
|
||||
### Register a new expertise doctor
|
||||
POST {{baseUrl}}/auth/register
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"email": "expert@example.com",
|
||||
"password": "password123",
|
||||
"name": "Dr. Expertise",
|
||||
"role": "expertise_doctor",
|
||||
"doctor": {
|
||||
"doctor_id": "EX456",
|
||||
"doctor_name": "Dr. Expertise"
|
||||
}
|
||||
}
|
||||
|
||||
### Login with registered user
|
||||
POST {{baseUrl}}/auth/login
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"email": "patient1@example.com",
|
||||
"password": "password123"
|
||||
}
|
||||
|
||||
### Login with admin user
|
||||
POST {{baseUrl}}/auth/login
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"email": "admin@example.com",
|
||||
"password": "password123"
|
||||
}
|
||||
|
||||
### Login with patient user
|
||||
POST {{baseUrl}}/auth/login
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"email": "patient2@example.com",
|
||||
"password": "password123"
|
||||
}
|
||||
|
||||
### Login with doctor user
|
||||
POST {{baseUrl}}/auth/login
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"email": "doctor@example.com",
|
||||
"password": "password123"
|
||||
}
|
||||
|
||||
@refresh_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiNCIsImVtYWlsIjoiZG9jdG9yQGV4YW1wbGUuY29tIiwicm9sZSI6InJlZl9kb2N0b3IiLCJ1c2VyX25hbWUiOiJEUi4gSEVSV0lORE8gUklEV0FOLCBTUC5PVCIsInRva2VuX3R5cGUiOiJyZWZyZXNoIiwiaG9tZV91cmwiOiIvIiwic3R1ZHlfbGlzdCI6ImVuYWJsZWQiLCJmaWx0ZXJfdXJsIjoic3R1ZGllcz9saW1pdD0xMDFcdTAwMjZvZmZzZXQ9MFx1MDAyNmZ1enp5bWF0Y2hpbmc9ZmFsc2VcdTAwMjZpbmNsdWRlZmllbGQ9MDAwODEwMzAsMDAwODAwNjAsMDAwODAwOTBcdTAwMjYwMDA4MDA5MD1EUi4rSEVSV0lORE8rUklEV0FOJTJDK1NQLk9UIiwiZXhwIjoxNzQ3OTAxMzI5LCJpYXQiOjE3NDcyOTY1Mjl9.M7khgg8eZHk20qGsdPDmUojdBvItXOE-834R6t_AF9Q"
|
||||
|
||||
### Refresh TOken
|
||||
POST {{baseUrl}}/auth/refresh
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"refresh_token" : {{refresh_token}}
|
||||
}
|
||||
67
test/http/shortlink-flow.http
Normal file
67
test/http/shortlink-flow.http
Normal file
@@ -0,0 +1,67 @@
|
||||
### Shortlink Authentication Test File
|
||||
@baseUrl = http://localhost:5555
|
||||
@adminToken = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiNiIsImVtYWlsIjoiYWRtaW5AZXhhbXBsZS5jb20iLCJyb2xlIjoiYWRtaW4iLCJ1c2VyX25hbWUiOiJBZG1pbiBVc2VyIiwidG9rZW5fdHlwZSI6ImFjY2VzcyIsImhvbWVfdXJsIjoiLyIsInN0dWR5X2xpc3QiOiJlbmFibGVkIiwiZXhwIjoxNzQ3MzY0NjgxLCJpYXQiOjE3NDcyNzgyODF9.bkzxV8f26wN_r6uI5T6o58TNX4U0z-Wel1hCAl5-8ag
|
||||
|
||||
### 1. Generate Short Link Single Study (Tidak ganti untuk 1 patient sampai expired)
|
||||
POST {{baseUrl}}/generate-link
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{adminToken}}
|
||||
|
||||
{
|
||||
"patient_id": "MR00000359",
|
||||
"study_uid": "1.2.826.0.1.3680043.9.7307.1.202503196393.01",
|
||||
"dob": "2001-10-07",
|
||||
"expires_in": 48
|
||||
}
|
||||
|
||||
### 2. Generate Short Link Multiple Studies
|
||||
POST {{baseUrl}}/generate-link
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{adminToken}}
|
||||
|
||||
{
|
||||
"patient_id": "00211622",
|
||||
"study_uid": "1.2.826.0.1.3680043.9.7307.1.20180713036",
|
||||
"dob": "1980-01-01",
|
||||
"expires_in": 48
|
||||
}
|
||||
|
||||
###
|
||||
POST {{baseUrl}}/generate-link
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer {{adminToken}}
|
||||
|
||||
{
|
||||
"patient_id": "00211622",
|
||||
"study_uid": "1.2.826.0.1.3680043.9.7307.1.20180530066",
|
||||
"dob": "1980-01-01",
|
||||
"expires_in": 48
|
||||
}
|
||||
|
||||
### Authenticate correct
|
||||
POST {{baseUrl}}/auth/shortlink
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"short_token": "DZDWF",
|
||||
"dob": "2001-10-07"
|
||||
}
|
||||
|
||||
### Authenticate with Incorrect DOB
|
||||
POST {{baseUrl}}/auth/shortlink
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"short_token": "HNHh_zem",
|
||||
"dob": "2001-10-00"
|
||||
}
|
||||
|
||||
### Recycle shortcode from expired or revoked token
|
||||
POST {{baseUrl}}/recycle-shortcode
|
||||
Authorization: Bearer {{adminToken}}
|
||||
Content-Type: application/json
|
||||
### Check the response from recycling
|
||||
# The response should include:
|
||||
# - status: "success"
|
||||
# - message: "Shortcodes recycled successfully"
|
||||
# - count: number of recycled shortcodes (integer)
|
||||
Reference in New Issue
Block a user