10 Commits

Author SHA1 Message Date
mario
8289881df3 edit: rm debug route 2025-05-13 16:49:07 +07:00
mario
dd784da232 add: implement shortlink 2025-05-13 15:44:11 +07:00
mario
2687a761cc add new dummy doctor user 2025-05-13 11:47:19 +07:00
mario
eb67eaca46 add: ref_doctor studylist filter 2025-05-13 11:46:28 +07:00
mario
0d4825d152 edit study_iuids & accNum in patient jwt to array 2025-05-13 10:07:16 +07:00
mario
2d1f135fda patient see their multiple studies 2025-05-13 09:52:45 +07:00
mario
13bb380f51 add: cors handler route and readme 2025-05-09 16:19:49 +07:00
mario
6c9ab574ce add: login & token validation tapi belum connect ke DB 2025-05-05 11:50:36 +07:00
mario
297c9a6a01 add readme.md 2025-04-28 15:37:02 +07:00
mario
9b8e0260f3 connected-to-google 2025-04-07 15:46:07 +07:00
27 changed files with 2546 additions and 301 deletions

3
.gitignore vendored
View File

@@ -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

View File

@@ -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"]

393
README.md Normal file
View File

@@ -0,0 +1,393 @@
# 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
```
## 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
```

View File

@@ -12,7 +12,6 @@ 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"
"go.uber.org/zap"
)
@@ -24,7 +23,16 @@ 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()
// Setup router

View File

@@ -26,6 +26,27 @@ 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"`
} `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"`
} `mapstructure:"database"`
AllowedOrigins []string `mapstructure:"allowed_origins"`
}

View File

@@ -1,5 +1,5 @@
server:
port: 8080
port: 5555
read_timeout_seconds: 30
write_timeout_seconds: 30
idle_timeout_seconds: 60
@@ -7,12 +7,29 @@ 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: false # Set to true when ready to use database
shortlink:
base_url: "http://localhost:3333" # The base URL for generated OHIF Auth shortlinks
default_expiry_hours: 24 # Default expiry time for shortlinks (1 day)
max_attempts: 5 # Maximum number of failed login attempts
database:
host: "localhost"
port: 3306
user: "dbuser"
password: "dbpassword" # Consider using environment variables for sensitive data
name: "ohif_proxy"
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
View 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
View File

@@ -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
View File

@@ -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=

View File

@@ -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",
})
}

View File

@@ -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", strings.Join(claims.StudyIUIDs, ","))
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)
}

View File

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

View File

@@ -0,0 +1,129 @@
package handlers
import (
"encoding/json"
"net/http"
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/middleware"
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/models"
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/service"
"go.uber.org/zap"
)
// ShortLinkHandler handles shortlink operations
type ShortLinkHandler struct {
logger *zap.Logger
shortLinkService *service.ShortLinkService
}
// NewShortLinkHandler creates a new shortlink handler
func NewShortLinkHandler(logger *zap.Logger, shortLinkService *service.ShortLinkService) *ShortLinkHandler {
return &ShortLinkHandler{
logger: logger,
shortLinkService: shortLinkService,
}
}
// GenerateShortLink handles shortlink generation requests
func (h *ShortLinkHandler) GenerateShortLink(w http.ResponseWriter, r *http.Request) {
// Only allow admin or expertise_doctor roles to generate shortlinks
userRole, ok := r.Context().Value(middleware.UserRoleKey).(string)
if !ok || (userRole != "admin" && userRole != "expertise_doctor") {
h.logger.Warn("Unauthorized attempt to generate shortlink",
zap.String("role", userRole))
http.Error(w, "Only admin or expertise doctor can generate short links", http.StatusForbidden)
return
}
// Parse request body
var req models.GenerateShortLinkRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
h.logger.Error("Failed to parse shortlink generation request", zap.Error(err))
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
// Get user ID from context
userID, ok := r.Context().Value(middleware.UserIDKey).(string)
if !ok {
h.logger.Error("User ID not found in context")
http.Error(w, "User context not found", http.StatusInternalServerError)
return
}
// Generate shortlink using configured baseURL from service
response, err := h.shortLinkService.GenerateShortLink(&req, userID)
if err != nil {
h.logger.Error("Failed to generate shortlink",
zap.Error(err),
zap.String("patientID", req.PatientID),
zap.String("studyUID", req.StudyUID))
statusCode := http.StatusInternalServerError
message := "Failed to generate shortlink"
if err == service.ErrInvalidStudyUID {
statusCode = http.StatusBadRequest
message = "Invalid StudyInstanceUID"
}
http.Error(w, message, statusCode)
return
}
// Log successful shortlink generation
h.logger.Info("Shortlink generated successfully",
zap.String("token", response.ShortToken),
zap.String("patientID", req.PatientID),
zap.String("studyUID", req.StudyUID),
zap.String("createdBy", userID))
// Return response
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(response)
}
// ShortLinkAuth handles authentication requests using shortlinks
func (h *ShortLinkHandler) ShortLinkAuth(w http.ResponseWriter, r *http.Request) {
// Parse request body
var req models.ShortLinkAuthRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
h.logger.Error("Failed to parse shortlink auth request", zap.Error(err))
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
// Validate and authenticate
response, err := h.shortLinkService.AuthenticateWithShortLink(&req)
if err != nil {
h.logger.Warn("Shortlink authentication failed",
zap.Error(err),
zap.String("token", req.ShortToken))
statusCode := http.StatusUnauthorized
message := "Authentication failed"
switch err {
case service.ErrShortLinkNotFound, service.ErrShortLinkExpired:
message = "Short link not found or expired"
case service.ErrInvalidDOB:
message = "Invalid date of birth"
case service.ErrTooManyAttempts:
message = "Too many failed attempts"
}
http.Error(w, message, statusCode)
return
}
// Log successful authentication
h.logger.Info("Shortlink authentication successful",
zap.String("token", req.ShortToken))
// Return response
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(response)
}

View File

@@ -0,0 +1,234 @@
package middleware
import (
"context"
"encoding/json"
"fmt"
"net/http"
"regexp"
"strings"
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/service"
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/auth"
"go.uber.org/zap"
)
type contextKey string
const (
UserIDKey contextKey = "user_id"
UserRoleKey contextKey = "user_role"
UserEmailKey contextKey = "user_email"
ClaimsKey contextKey = "auth_claims" // Use this same key everywhere
)
// WhitelistedEndpoints contains paths that can be accessed without authentication
var WhitelistedEndpoints = []*regexp.Regexp{
// Study by UID
regexp.MustCompile(`^/dicomWeb/studies\?.*StudyInstanceUID=.+`),
// Frame endpoint
regexp.MustCompile(`^/dicomWeb/studies/[^/]+/series/[^/]+/instances/[^/]+/frames/\d+$`),
}
// Auth middleware authenticates requests using JWT tokens
func Auth(authService *service.AuthService, logger *zap.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Get authorization header
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
logger.Warn("Missing Authorization header", zap.String("path", r.URL.Path))
respondWithError(w, http.StatusUnauthorized, "missing authorization header")
return
}
// Extract token from Bearer token
bearerToken := strings.Split(authHeader, " ")
if len(bearerToken) != 2 || strings.ToLower(bearerToken[0]) != "bearer" {
logger.Warn("Invalid Authorization header format", zap.String("header", authHeader))
respondWithError(w, http.StatusUnauthorized, "invalid authorization format")
return
}
token := bearerToken[1]
// Validate token
claims, err := authService.ValidateToken(token)
if err != nil {
logger.Warn("Invalid or expired token", zap.Error(err))
respondWithError(w, http.StatusUnauthorized, "invalid or expired token")
return
}
// Check token type
if claims.TokenType != "access" {
logger.Warn("Invalid token type", zap.String("tokenType", claims.TokenType))
respondWithError(w, http.StatusUnauthorized, "invalid token type")
return
}
// Add user info to request context
ctx := context.WithValue(r.Context(), UserIDKey, claims.UserID)
ctx = context.WithValue(ctx, UserRoleKey, claims.Role)
ctx = context.WithValue(ctx, UserEmailKey, claims.Email)
// Store the claims with the defined context key
ctx = context.WithValue(ctx, ClaimsKey, claims)
// Log successful authentication
logger.Debug("Auth middleware: Token validated",
zap.String("userID", claims.UserID),
zap.String("role", claims.Role))
// Continue with the request
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// RoleRequired middleware checks if user has the required role
func RoleRequired(roles ...string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check if the request path is whitelisted first
path := r.URL.Path
if r.URL.RawQuery != "" {
path = path + "?" + r.URL.RawQuery
}
for _, pattern := range WhitelistedEndpoints {
if pattern.MatchString(path) {
// Path is whitelisted, skip role check
next.ServeHTTP(w, r)
return
}
}
// Get user role from context
userRole, ok := r.Context().Value(UserRoleKey).(string)
if !ok {
respondWithError(w, http.StatusUnauthorized, "user context not found")
return
}
// Check if user has one of the required roles
hasRole := false
for _, role := range roles {
if userRole == role {
hasRole = true
break
}
}
if !hasRole {
respondWithError(w, http.StatusForbidden, "insufficient permissions")
return
}
// Continue with the request
next.ServeHTTP(w, r)
})
}
}
// PatientViewRestriction ensures patients can only access their own studies
func PatientViewRestriction(logger *zap.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Get claims from context using the defined key
claimsValue := r.Context().Value(ClaimsKey)
if claimsValue == nil {
logger.Error("Missing claims in context - PatientViewRestriction middleware",
zap.String("path", r.URL.Path),
zap.String("method", r.Method))
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
claims, ok := claimsValue.(*auth.CustomClaims)
if !ok {
logger.Error("Invalid claims type in context",
zap.String("type", fmt.Sprintf("%T", claimsValue)))
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
logger.Debug("PatientViewRestriction: Got claims from context",
zap.String("userID", claims.UserID),
zap.String("role", claims.Role))
// Only apply restrictions to patient role
if claims.Role != "patient" {
// For non-patient roles, continue with the request
next.ServeHTTP(w, r)
return
}
// Parse the path to extract StudyInstanceUID if present
path := r.URL.Path
parts := strings.Split(path, "/")
// Check if this is a study-specific request
var requestedStudyUID string
for i, part := range parts {
if part == "studies" && i+1 < len(parts) {
requestedStudyUID = parts[i+1]
break
}
}
// If there's no study UID in the path, check query parameters
if requestedStudyUID == "" {
queryStudyUID := r.URL.Query().Get("StudyInstanceUID")
if queryStudyUID != "" {
requestedStudyUID = queryStudyUID
}
}
// If a study is being requested, verify patient has access
if requestedStudyUID != "" && len(claims.StudyIUIDs) > 0 {
// Check if the requested study is authorized
isAuthorized := false
for _, studyUID := range claims.StudyIUIDs {
if studyUID == requestedStudyUID {
isAuthorized = true
logger.Debug("Patient authorized to access study",
zap.String("userID", claims.UserID),
zap.String("requestedStudy", requestedStudyUID))
break
}
}
// If not authorized, return 403 Forbidden
if !isAuthorized {
logger.Warn("Patient attempted to access unauthorized study",
zap.String("userID", claims.UserID),
zap.String("role", claims.Role),
zap.String("requestedStudy", requestedStudyUID),
zap.Strings("authorizedStudies", claims.StudyIUIDs))
// Return 403 Forbidden with a clear message
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusForbidden)
json.NewEncoder(w).Encode(map[string]string{
"error": "Access denied: You do not have permission to view this study",
"code": "forbidden_study_access",
})
return
}
}
// Patient has access or is requesting a list (which will be filtered)
next.ServeHTTP(w, r)
})
}
}
// Helper function to respond with an error
func respondWithError(w http.ResponseWriter, statusCode int, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
json.NewEncoder(w).Encode(map[string]string{"error": message})
}

View File

@@ -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()),
)
})
}
}

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

112
internal/api/models/user.go Normal file
View File

@@ -0,0 +1,112 @@
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"`
}
// PatientDetails contains patient-specific data
type PatientDetails struct {
PatientID string `json:"patient_id"`
PatientName string `json:"patient_name"`
StudyInstanceUIDs []string `json:"study_instance_uids,omitempty"`
AccessionNumbers []string `json:"accession_numbers,omitempty"`
}
// 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"
}
// 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"`
}
// ShortLink represents a short URL token for patient access
type ShortLink struct {
ID string `db:"id" json:"id"`
Token string `db:"token" json:"token"` // The short token used in the URL
PatientID string `db:"patient_id" json:"patient_id"`
StudyUID string `db:"study_uid" json:"study_uid"` // The StudyInstanceUID this token grants access to
HashedDOB string `db:"hashed_dob" json:"-"` // Hashed Date of Birth for verification
ExpiresAt string `db:"expires_at" json:"expires_at"`
IsRevoked bool `db:"is_revoked" json:"is_revoked"`
CreatedAt string `db:"created_at" json:"created_at"`
CreatedByID string `db:"created_by_id" json:"created_by_id"` // ID of admin who created this
RemainingTries int `db:"remaining_tries" json:"-"` // Number of failed attempts allowed
}
// GenerateShortLinkRequest represents request to create a short URL
type GenerateShortLinkRequest struct {
PatientID string `json:"patient_id"`
StudyUID string `json:"study_uid"`
DOB string `json:"dob"` // Date of birth in YYYY-MM-DD format
ExpiresIn int `json:"expires_in"` // Expiry in hours (optional, defaults to 72)
}
// GenerateShortLinkResponse is the response for a generated short link
type GenerateShortLinkResponse struct {
ShortToken string `json:"short_token"`
FullURL string `json:"full_url"`
ExpiresAt string `json:"expires_at"`
}
// 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"`
}

View File

@@ -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,85 @@ 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")
}
// 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)
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)
// ShortLink authentication - no auth required
shortLinkHandler := handlers.NewShortLinkHandler(logger, shortLinkService)
r.Post("/shortlink", shortLinkHandler.ShortLinkAuth)
})
})
// Protected routes that require authentication
r.Group(func(r chi.Router) {
// Apply authentication middleware
r.Use(apiMiddleware.Auth(authService, logger))
// Shortlink generation - only for admin and expertise_doctor roles
shortLinkHandler := handlers.NewShortLinkHandler(logger, shortLinkService)
r.Post("/generate-link", shortLinkHandler.GenerateShortLink)
// DICOM Web routes
r.Route("/dicomWeb", func(r chi.Router) {
// Add audit logging middleware to DICOM routes
r.Use(apiMiddleware.AuditLog(logger))
// Add patient view restriction for patient role
r.Use(apiMiddleware.PatientViewRestriction(logger))
// Create handler for all DICOM requests
dicomHandler := handlers.NewDicomHandler(healthcareClient, logger)
// Common routes for studies with role-specific handling
r.Route("/studies", func(r chi.Router) {
// StudyInstanceUID parameter routes - accessible by all roles
r.Get("/{studyInstanceUID}", dicomHandler.ForwardRequest) // Study details
r.Get("/{studyInstanceUID}/series", dicomHandler.ForwardRequest) // Series list for study
// Deep hierarchy routes - accessible by patients and all doctors
r.Get("/{studyInstanceUID}/series/{seriesUID}/metadata", dicomHandler.ForwardRequest)
r.Get("/{studyInstanceUID}/series/{seriesUID}/instances/{instanceUID}/frames/{frame}", dicomHandler.ForwardRequest)
// Query routes - accessible by all roles
r.Get("/", dicomHandler.ForwardRequest) // Study list with filters
})
// Expertise doctors have full access to all DICOM endpoints
r.With(apiMiddleware.RoleRequired("expertise_doctor")).HandleFunc("/*", dicomHandler.ForwardRequest)
})
})
return r
}

View File

@@ -0,0 +1,190 @@
package service
import (
"errors"
"fmt"
"net/url"
"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/auth"
)
var (
ErrInvalidCredentials = errors.New("invalid credentials")
ErrUserNotFound = errors.New("user not found")
)
// AuthService handles authentication operations
type AuthService struct {
jwtManager *auth.JWTManager
// When you implement database connection, add a db client here
// db *sqlx.DB
}
// NewAuthService creates a new authentication service
func NewAuthService(jwtManager *auth.JWTManager) *AuthService {
return &AuthService{
jwtManager: jwtManager,
}
}
// Login authenticates a user and generates tokens
func (s *AuthService) Login(email, password string) (*models.LoginResponse, error) {
// Find user in mock data
user := models.FindUserByCredentials(email, password)
if user == 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 := models.FindPatientDataByUserID(user.ID)
if patientData == nil {
return nil, ErrUserNotFound
}
// Set patient-specific claims
additionalClaims["patient_id"] = patientData.PatientID
additionalClaims["patient_name"] = patientData.PatientName
additionalClaims["study_iuids"] = patientData.StudyIUIDs
additionalClaims["accession_numbers"] = patientData.AccessionNumbers
// For redirectURL and home_url, use first study for simplicity
if len(patientData.StudyIUIDs) > 0 {
additionalClaims["home_url"] = fmt.Sprintf("viewer?StudyInstanceUIDs=%s", patientData.StudyIUIDs[0])
redirectURL = fmt.Sprintf("/viewer?StudyInstanceUIDs=%s", patientData.StudyIUIDs[0])
} else {
// Fallback for empty studies array (shouldn't happen)
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":
// Expertise doctors have full access
additionalClaims["home_url"] = "/"
additionalClaims["study_list"] = "enabled"
redirectURL = "/"
}
// 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
}
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) {
// 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)
}
// 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))
}
// Below functions would be implemented when connecting to a real database
// storeRefreshToken stores a refresh token in the database
func (s *AuthService) storeRefreshToken(userID, token string) error {
// TODO: In a real implementation, this would insert a record in the database
return nil
}
// revokeRefreshToken marks a refresh token as revoked
func (s *AuthService) revokeRefreshToken(token string) error {
// TODO: In a real implementation, this would update a record in the database
return nil
}

View File

@@ -0,0 +1,130 @@
package service
import (
"database/sql"
"fmt"
"time"
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/api/models"
_ "github.com/go-sql-driver/mysql" // Hanya menjalankan side-effectsnya saja dahulu
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
)
// Repository provides an interface to the database
type Repository struct {
db *sqlx.DB
}
// NewRepository creates a new database repository
func NewRepository(dsn string) (*Repository, error) {
db, err := sqlx.Connect("mysql", dsn)
if err != nil {
return nil, fmt.Errorf("failed to connect to database: %w", err)
}
// Set connection pool settings
db.SetMaxOpenConns(10)
db.SetMaxIdleConns(5)
db.SetConnMaxLifetime(time.Hour)
return &Repository{
db: db,
}, nil
}
// GetUserByEmail retrieves a user by email
func (r *Repository) GetUserByEmail(email string) (*models.User, error) {
var user models.User
err := r.db.Get(&user, "SELECT * FROM users WHERE email = ?", email)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, err
}
return &user, nil
}
// GetUserByID retrieves a user by ID
func (r *Repository) GetUserByID(id string) (*models.User, error) {
var user models.User
err := r.db.Get(&user, "SELECT * FROM users WHERE id = ?", id)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, err
}
return &user, nil
}
// StoreRefreshToken saves a refresh token to the database
func (r *Repository) StoreRefreshToken(userID, token string, expiresAt time.Time) error {
refreshToken := models.RefreshToken{
ID: uuid.New().String(),
UserID: userID,
Token: token,
ExpiresAt: expiresAt.Format(time.RFC3339),
IsRevoked: false,
CreatedAt: time.Now().Format(time.RFC3339),
}
_, err := r.db.NamedExec(
`INSERT INTO refresh_tokens (id, user_id, token, expires_at, is_revoked, created_at)
VALUES (:id, :user_id, :token, :expires_at, :is_revoked, :created_at)`,
refreshToken,
)
return err
}
// GetRefreshToken retrieves a refresh token from the database
func (r *Repository) GetRefreshToken(token string) (*models.RefreshToken, error) {
var refreshToken models.RefreshToken
err := r.db.Get(&refreshToken, "SELECT * FROM refresh_tokens WHERE token = ?", token)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, err
}
return &refreshToken, nil
}
// RevokeRefreshToken marks a refresh token as revoked
func (r *Repository) RevokeRefreshToken(token string) error {
_, err := r.db.Exec("UPDATE refresh_tokens SET is_revoked = true WHERE token = ?", token)
return err
}
// GetPatientDetails retrieves patient details for a user
func (r *Repository) GetPatientDetails(userID string) (*models.PatientDetails, error) {
var patientDetails models.PatientDetails
err := r.db.Get(&patientDetails, "SELECT * FROM patient_details WHERE user_id = ?", userID)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, err
}
return &patientDetails, nil
}
// GetDoctorDetails retrieves doctor details for a user
func (r *Repository) GetDoctorDetails(userID string) (*models.DoctorDetails, error) {
var doctorDetails models.DoctorDetails
err := r.db.Get(&doctorDetails, "SELECT * FROM doctor_details WHERE user_id = ?", userID)
if err != nil {
if err == sql.ErrNoRows {
return nil, nil
}
return nil, err
}
return &doctorDetails, nil
}
// Close closes the database connection
func (r *Repository) Close() error {
return r.db.Close()
}

View File

@@ -0,0 +1,296 @@
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/auth"
"go.uber.org/zap"
)
const (
// DefaultShortLinkExpiry is the default expiration time for short links (72 hours)
DefaultShortLinkExpiry = 72 * time.Hour
// DefaultMaxTries is the default number of login attempts allowed for a shortlink
DefaultMaxTries = 5
// ShortTokenLength is the length of the generated short token
ShortTokenLength = 8
)
var (
ErrShortLinkNotFound = errors.New("short link not found or expired")
ErrInvalidDOB = errors.New("invalid date of birth")
ErrShortLinkExpired = errors.New("short link has expired")
ErrTooManyAttempts = errors.New("too many failed attempts")
ErrCreationFailed = errors.New("failed to create short link")
ErrInvalidStudyUID = errors.New("invalid or missing StudyInstanceUID")
ErrAdminRoleRequired = errors.New("admin role required to generate shortlinks")
)
// ShortLinkService handles operations related to short links
type ShortLinkService struct {
jwtManager *auth.JWTManager
logger *zap.Logger
// Configuration settings
baseURL string
defaultExpiryTime time.Duration
maxAttempts int
// Mock in-memory storage for now, would use a database in production
shortLinks map[string]*models.ShortLink
}
// 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,
baseURL: baseURL,
defaultExpiryTime: time.Duration(defaultExpiryHours) * time.Hour,
maxAttempts: maxAttempts,
shortLinks: make(map[string]*models.ShortLink),
}
}
// 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")
}
// Set expiration if not provided
expiresIn := s.defaultExpiryTime
if req.ExpiresIn > 0 {
expiresIn = time.Duration(req.ExpiresIn) * time.Hour
}
expiresAt := time.Now().Add(expiresIn)
// Generate a secure random token
token, err := generateSecureToken(ShortTokenLength)
if err != nil {
s.logger.Error("Failed to generate secure token", zap.Error(err))
return nil, ErrCreationFailed
}
// Hash the DOB for secure storage
hashedDOB := hashDOB(dob)
// Create the short link record
shortLink := &models.ShortLink{
ID: generateID(),
Token: token,
PatientID: req.PatientID,
StudyUID: req.StudyUID,
HashedDOB: hashedDOB,
ExpiresAt: expiresAt.Format(time.RFC3339),
IsRevoked: false,
CreatedAt: time.Now().Format(time.RFC3339),
CreatedByID: creatorID,
RemainingTries: s.maxAttempts,
}
// Store the short link (in production, this would be in a database)
s.shortLinks[token] = shortLink
// Generate the full URL using the configured base URL
fullURL := fmt.Sprintf("%s/short-auth?short=%s", s.baseURL, token)
return &models.GenerateShortLinkResponse{
ShortToken: token,
FullURL: fullURL,
ExpiresAt: shortLink.ExpiresAt,
}, 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
shortLink, exists := s.shortLinks[token]
if !exists {
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) {
// Decrement remaining tries on invalid format
shortLink.RemainingTries--
return nil, errors.New("invalid date of birth format, expected YYYY-MM-DD")
}
hashedDOB := hashDOB(dob)
// Verify the DOB
if hashedDOB != shortLink.HashedDOB {
// Decrement remaining tries on failed verification
shortLink.RemainingTries--
return nil, ErrInvalidDOB
}
// DOB verified, reset tries count as successful login
shortLink.RemainingTries = s.maxAttempts
return shortLink, nil
}
// AuthenticateWithShortLink authenticates a user using a short link and DOB
func (s *ShortLinkService) AuthenticateWithShortLink(req *models.ShortLinkAuthRequest) (*models.ShortLinkAuthResponse, error) {
// Validate the short link
shortLink, err := s.ValidateShortLink(req)
if err != nil {
return nil, err
}
// Determine patient name (could be fetched from a database)
patientName := "Patient" // Placeholder, in production get real name
// Create additional claims for the JWT
additionalClaims := make(map[string]interface{})
additionalClaims["patient_id"] = shortLink.PatientID
additionalClaims["patient_name"] = patientName
additionalClaims["study_iuids"] = []string{shortLink.StudyUID}
additionalClaims["home_url"] = fmt.Sprintf("viewer?StudyInstanceUIDs=%s", shortLink.StudyUID)
additionalClaims["study_list"] = "disabled"
// Generate JWT
// Using a virtual "user" for the patient with a patient role
userID := fmt.Sprintf("shortlink_%s", shortLink.ID)
email := fmt.Sprintf("patient_%s@shortlink.local", shortLink.ID) // Virtual email for JWT
role := "patient" // Always patient role for shortlinks
// Generate access token (24-hour validity for patient access)
accessToken, err := s.jwtManager.GenerateAccessToken(userID, email, role, patientName, additionalClaims)
if err != nil {
s.logger.Error("Failed to generate JWT for shortlink auth", zap.Error(err))
return nil, errors.New("authentication error")
}
// Create response
redirectURL := fmt.Sprintf("/viewer?StudyInstanceUIDs=%s", shortLink.StudyUID)
return &models.ShortLinkAuthResponse{
AccessToken: accessToken,
ExpiresIn: int(s.jwtManager.GetAccessExpiry().Seconds()),
RedirectURL: redirectURL,
}, nil
}
// Helper functions
// hashDOB creates a secure hash of a date of birth
func hashDOB(dob string) string {
hash := sha256.Sum256([]byte(dob))
return hex.EncodeToString(hash[:])
}
// generateSecureToken generates a secure random token for short links
func generateSecureToken(length int) (string, error) {
b := make([]byte, length)
_, err := rand.Read(b)
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(b)[:length], nil
}
// generateID generates a unique ID for a shortlink
func generateID() string {
b := make([]byte, 6)
rand.Read(b)
return fmt.Sprintf("sl_%s", hex.EncodeToString(b))
}
// normalizeDOB normalizes date of birth to YYYY-MM-DD format
func normalizeDOB(dob string) string {
// Remove any non-alphanumeric characters except dash
dob = strings.Map(func(r rune) rune {
if (r >= '0' && r <= '9') || r == '-' {
return r
}
return -1
}, dob)
return dob
}
// isValidDOBFormat checks if the DOB is in YYYY-MM-DD format
func isValidDOBFormat(dob string) bool {
// Check basic format
if len(dob) != 10 {
return false
}
// Check dashes
if dob[4] != '-' || dob[7] != '-' {
return false
}
// Parse year, month, day
yearStr := dob[0:4]
monthStr := dob[5:7]
dayStr := dob[8:10]
// Check if all are numeric
for _, ch := range yearStr + monthStr + dayStr {
if ch < '0' || ch > '9' {
return false
}
}
// Could add more validation here (leap years, month/day ranges)
return true
}

View File

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

View File

@@ -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))

57
test/http/ohif-flow.http Normal file
View File

@@ -0,0 +1,57 @@
@token = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiMiIsImVtYWlsIjoicGF0aWVudCIsInJvbGUiOiJwYXRpZW50IiwidXNlcl9uYW1lIjoiUGF0aWVudCBVc2VyIiwidG9rZW5fdHlwZSI6ImFjY2VzcyIsInBhdGllbnRfaWQiOiIwMDIxMTYyMiIsInBhdGllbnRfbmFtZSI6IkRJRElUIFNVWUFUTkFeUi4xMDA0OS4xOCIsImFjY2Vzc2lvbl9udW1iZXIiOiJDUi4xODA3MTMuMDM2Iiwic3R1ZHlfaXVpZCI6IjEuMi44MjYuMC4xLjM2ODAwNDMuOS43MzA3LjEuMjAxODA3MTMwMzYiLCJob21lX3VybCI6InZpZXdlcj9TdHVkeUluc3RhbmNlVUlEcz0xLjIuODI2LjAuMS4zNjgwMDQzLjkuNzMwNy4xLjIwMTgwNzEzMDM2Iiwic3R1ZHlfbGlzdCI6ImRpc2FibGVkIiwiZXhwIjoxNzQ2ODUyMDU2LCJpYXQiOjE3NDY3NjU2NTZ9.wGKCU77toQ5D27DRcNJE_XQjoJmxxzqoPbmf5N7D0cw
@token_exp_doctor = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiMSIsImVtYWlsIjoiYWRtaW4iLCJyb2xlIjoiZXhwZXJ0aXNlX2RvY3RvciIsInRva2VuX3R5cGUiOiJhY2Nlc3MiLCJleHAiOjE3NDY1MDQ1MTYsImlhdCI6MTc0NjQxODExNn0.vlDrns1oPFXHE5--TmWqwzvzxnfcCPcV2UW8_4GwDwE
@baseUrl = http://localhost:5555
### Login Patient
POST {{baseUrl}}/auth/login
Content-Type: application/json
{
"email": "patient",
"password": "patient"
}
### 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.20180713036
Authorization: Bearer {{token}}
### Series List
GET {{baseUrl}}/dicomWeb/studies/1.2.826.0.1.3680043.9.7307.1.202503196393.01/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}}

View File

@@ -0,0 +1,50 @@
### Shortlink Authentication Test File
@baseUrl = http://localhost:5555
@adminToken = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiMSIsImVtYWlsIjoiYWRtaW4iLCJyb2xlIjoiZXhwZXJ0aXNlX2RvY3RvciIsInVzZXJfbmFtZSI6IkFkbWluIFVzZXIiLCJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiaG9tZV91cmwiOiIvIiwic3R1ZHlfbGlzdCI6ImVuYWJsZWQiLCJleHAiOjE3NDcyMDY5NTAsImlhdCI6MTc0NzEyMDU1MH0.M3fhlKB8MX-NxGdEgnaA9-AhMXnXjUjRsWYOBXntJe4
### 0. Login as Admin and take the token
POST http://localhost:5555/auth/login
Content-Type: application/json
{
"email": "admin",
"password": "admin"
}
### 1. Generate Short Link (Admin/Expertise Doctor Only)
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. Authenticate with Short Link and DOB
# Use the short_token from the response of request #1
POST {{baseUrl}}/auth/shortlink
Content-Type: application/json
{
"short_token": "oP-tLWeu",
"dob": "2001-10-07"
}
### 3. Try authentication with incorrect DOB
POST {{baseUrl}}/auth/shortlink
Content-Type: application/json
{
"short_token": "erB5xT5S",
"dob": "1985-04-16"
}
### 4. Access DICOM data with the JWT from successful shortlink auth
# Replace with token from successful auth in request #2
GET {{baseUrl}}/dicomWeb/studies/1.2.826.0.1.3680043.9.7307.1.202503196393.01
Content-Type: application/json
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoic2hvcnRsaW5rX3NsXzgzZGNmNzQ1NGYwZiIsImVtYWlsIjoicGF0aWVudF9zbF84M2RjZjc0NTRmMGZAc2hvcnRsaW5rLmxvY2FsIiwicm9sZSI6InBhdGllbnQiLCJ1c2VyX25hbWUiOiJQYXRpZW50IiwidG9rZW5fdHlwZSI6ImFjY2VzcyIsInBhdGllbnRfaWQiOiJNUjAwMDAwMzU5IiwicGF0aWVudF9uYW1lIjoiUGF0aWVudCIsInN0dWR5X2l1aWRzIjpbIjEuMi44MjYuMC4xLjM2ODAwNDMuOS43MzA3LjEuMjAyNTAzMTk2MzkzLjAxIl0sImhvbWVfdXJsIjoidmlld2VyP1N0dWR5SW5zdGFuY2VVSURzPTEuMi44MjYuMC4xLjM2ODAwNDMuOS43MzA3LjEuMjAyNTAzMTk2MzkzLjAxIiwic3R1ZHlfbGlzdCI6ImRpc2FibGVkIiwiZXhwIjoxNzQ3MjA3MDI4LCJpYXQiOjE3NDcxMjA2Mjh9.RMGF9ParYAmOXbJqd0DP2kl0X6O0n8j_LI6FF9el4qM

94
test/http/test.http Normal file
View File

@@ -0,0 +1,94 @@
### Local OHIF Proxy Test File
@token = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiMiIsImVtYWlsIjoicGF0aWVudCIsInJvbGUiOiJwYXRpZW50IiwidG9rZW5fdHlwZSI6ImFjY2VzcyIsImV4cCI6MTc0NjM2NDczMiwiaWF0IjoxNzQ2MzYyOTMyfQ.4IGGV77jnewQVXOCuFWmcx4X7EMMxx341j6DeNKYcFY
@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
### Login Success
POST {{baseUrl}}/auth/login
Content-Type: application/json
{
"email": "patient",
"password": "patient"
}
### Refresh TOken
POST {{baseUrl}}/auth/refresh
Content-Type: application/json
{
"refresh"
}
### 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
### 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
### 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