This commit is contained in:
mario
2025-04-07 11:14:18 +07:00
commit f340bc5916
17 changed files with 1424 additions and 0 deletions

View File

@@ -0,0 +1,32 @@
package handlers
import (
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
// AuthHandler handles authentication-related requests
type AuthHandler struct {
logger *zap.Logger
}
// NewAuthHandler creates a new AuthHandler
func NewAuthHandler(logger *zap.Logger) *AuthHandler {
return &AuthHandler{
logger: logger,
}
}
// 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"})
}
// 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"})
}

View File

@@ -0,0 +1,101 @@
package handlers
import (
"fmt"
"io"
"net/http"
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/proxy"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
// DicomHandler handles DICOM Web requests
type DicomHandler struct {
client *proxy.Client
logger *zap.Logger
}
// NewDicomHandler creates a new DICOM handler
func NewDicomHandler(client *proxy.Client, logger *zap.Logger) *DicomHandler {
return &DicomHandler{
client: client,
logger: logger,
}
}
// 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)
h.logger.Debug("Forwarding request",
zap.String("path", path),
zap.String("method", c.Request.Method),
zap.String("type", requestType),
)
// Read request body if present
var bodyBytes []byte
if c.Request.Body != nil && c.Request.ContentLength > 0 {
var err error
bodyBytes, err = io.ReadAll(c.Request.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"})
return
}
}
// Get request headers
headers := make(map[string]string)
for k, v := range c.Request.Header {
if len(v) > 0 {
headers[k] = v[0]
}
}
// Forward the request to Healthcare API
response, err := h.client.ForwardRequest(
c.Request.Context(),
c.Request.Method,
requestType,
path,
headers,
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)})
return
}
// Set response headers
for k, v := range response.Headers {
c.Header(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"
}

View File

@@ -0,0 +1,12 @@
package handlers
import (
"net/http"
"github.com/gin-gonic/gin"
)
// HealthCheck is a simple health check handler
func HealthCheck(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "ok"})
}

View File

@@ -0,0 +1,94 @@
package middleware
import (
"time"
"github.com/gin-gonic/gin"
"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
// Process request
c.Next()
// Calculate request time
latency := time.Since(start)
// Get status
status := c.Writer.Status()
// 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()),
)
}
}
// 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)
}
path := c.Request.URL.Path
method := c.Request.Method
// 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()
}
}

72
internal/api/routes.go Normal file
View File

@@ -0,0 +1,72 @@
package api
import (
"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"
"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"
"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)
}
// Initialize the router
r := gin.New()
// Add middleware
r.Use(gin.Recovery())
r.Use(middleware.Logger(logger))
r.Use(middleware.CORS(cfg.AllowedOrigins))
// Setup health check
r.GET("/health", handlers.HealthCheck)
// Initialize Google auth client
googleAuth, err := auth.NewGoogleClient(cfg.Google.CredentialsPath)
if err != nil {
logger.Fatal("Failed to initialize Google auth client", zap.Error(err))
}
// Initialize Healthcare API client
healthcareClient := proxy.NewClient(googleAuth, cfg.Google)
// 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)
}
// 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)
}
return r
}

78
internal/auth/google.go Normal file
View File

@@ -0,0 +1,78 @@
package auth
import (
"context"
"fmt"
"time"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/healthcare/v1"
"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
}
// NewGoogleClient creates a new Google authentication client
func NewGoogleClient(credentialsPath string) (*GoogleClient, error) {
client := &GoogleClient{
credentialsPath: credentialsPath,
}
// Initialize on creation to validate credentials
if _, err := client.getToken(); err != nil {
return nil, fmt.Errorf("failed to initialize Google client: %w", err)
}
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
}
// Retrieve the token using the Token() method
token, err := tokenSource.Token()
if err != nil {
return "", fmt.Errorf("failed to retrieve token: %w", err)
}
return token.AccessToken, nil
}
// GetHealthcareClient returns a configured Healthcare API client
func (c *GoogleClient) GetHealthcareClient(ctx context.Context) (*healthcare.Service, error) {
opts := []option.ClientOption{
option.WithCredentialsFile(c.credentialsPath),
option.WithScopes(healthcare.CloudPlatformScope),
}
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
}

44
internal/logger/logger.go Normal file
View File

@@ -0,0 +1,44 @@
package logger
import (
"os"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// New creates a new configured logger
func New(logLevel string) *zap.Logger {
// Parse log level
var level zapcore.Level
err := level.UnmarshalText([]byte(logLevel))
if err != nil {
// Default to info level if parsing fails
level = zapcore.InfoLevel
}
// Create encoder config
encoderConfig := zapcore.EncoderConfig{
TimeKey: "time",
LevelKey: "level",
NameKey: "logger",
CallerKey: "caller",
MessageKey: "msg",
StacktraceKey: "stacktrace",
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.LowercaseLevelEncoder,
EncodeTime: zapcore.ISO8601TimeEncoder,
EncodeDuration: zapcore.MillisDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder,
}
// Create core
core := zapcore.NewCore(
zapcore.NewJSONEncoder(encoderConfig),
zapcore.AddSync(os.Stdout),
level,
)
// Create logger with caller information
return zap.New(core, zap.AddCaller(), zap.AddStacktrace(zapcore.ErrorLevel))
}

105
internal/proxy/client.go Normal file
View File

@@ -0,0 +1,105 @@
package proxy
import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"devone.aplikasi.web.id/gitea/mario/go-ohif-proxy/internal/auth"
)
// Client is responsible for making requests to the Healthcare API
type Client struct {
googleAuth *auth.GoogleClient
projectID string
location string
dataset string
dicomStore string
}
// NewClient creates a new Healthcare API client
// Hanya menerima cfg.Google struct instead of all cfg.Config
func NewClient(googleAuth *auth.GoogleClient, googleConfig struct {
ProjectID string `mapstructure:"project_id"`
Location string `mapstructure:"location"`
Dataset string `mapstructure:"dataset"`
DicomStore string `mapstructure:"dicom_store"`
CredentialsPath string `mapstructure:"credentials_path"`
}) *Client {
return &Client{
googleAuth: googleAuth,
projectID: googleConfig.ProjectID,
location: googleConfig.Location,
dataset: googleConfig.Dataset,
dicomStore: googleConfig.DicomStore,
}
}
// Response represents the HTTP response from the Healthcare API
type Response struct {
StatusCode int
Headers map[string]string
Body []byte
}
// 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
token, err := c.googleAuth.GetAccessToken()
if err != nil {
return nil, fmt.Errorf("failed to get access token: %w", err)
}
// Build URL
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)
// Create request
req, err := http.NewRequestWithContext(ctx, method, fullURL, bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
// Set headers
for k, v := range headers {
// Skip setting certain headers that might cause issues
if k == "Host" || k == "Content-Length" {
continue
}
req.Header.Set(k, v)
}
// Set auth header
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
// Make request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to execute request: %w", err)
}
defer resp.Body.Close()
// Read response body
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
// Collect response headers
respHeaders := make(map[string]string)
for k, v := range resp.Header {
if len(v) > 0 {
respHeaders[k] = v[0]
}
}
return &Response{
StatusCode: resp.StatusCode,
Headers: respHeaders,
Body: respBody,
}, nil
}