-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
134 lines (111 loc) · 4 KB
/
main.go
File metadata and controls
134 lines (111 loc) · 4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package main
import (
"encoding/json"
"fintech-auth/config"
"fintech-auth/database"
"fintech-auth/handlers"
"fintech-auth/middleware"
"fintech-auth/models"
"log"
"net/http"
"github.com/gorilla/mux"
)
func main() {
// Initialize configuration
cfg := config.Load()
// Initialize database
db, err := database.Initialize(cfg.DatabaseURL)
if err != nil {
log.Fatal("Failed to initialize database:", err)
}
defer db.Close()
// Initialize handlers
authHandler := handlers.NewAuthHandler(db, cfg)
adminHandler := handlers.NewAdminHandler(db, cfg)
// Initialize middleware
authMiddleware := middleware.NewAuthMiddleware(cfg.JWTSecret)
adminMiddleware := middleware.NewAdminMiddleware(cfg.JWTSecret)
// Setup routes
r := mux.NewRouter()
// Public routes
r.HandleFunc("/api/register", authHandler.Register).Methods("POST")
r.HandleFunc("/api/login", authHandler.Login).Methods("POST")
r.HandleFunc("/api/refresh", authHandler.RefreshToken).Methods("POST")
r.HandleFunc("/api/health", healthCheck).Methods("GET")
r.HandleFunc("/api/debug/user/{email}", debugUserStatus).Methods("GET") // Debug endpoint
// Protected routes
protected := r.PathPrefix("/api/protected").Subrouter()
protected.Use(authMiddleware.ValidateToken)
protected.HandleFunc("/profile", authHandler.GetProfile).Methods("GET")
protected.HandleFunc("/change-password", authHandler.ChangePassword).Methods("POST")
// Admin routes
admin := r.PathPrefix("/api/admin").Subrouter()
admin.Use(authMiddleware.ValidateToken)
admin.Use(adminMiddleware.ValidateAdmin)
admin.HandleFunc("/users", adminHandler.GetAllUsers).Methods("GET")
admin.HandleFunc("/revoke-token", adminHandler.RevokeRefreshToken).Methods("POST")
admin.HandleFunc("/user/{id}/status", adminHandler.UpdateUserStatus).Methods("PUT")
admin.HandleFunc("/user/{id}/reactivate", adminHandler.ReactivateUser).Methods("POST")
admin.HandleFunc("/test-route/{id}", testRoute).Methods("POST") // Debug route
admin.HandleFunc("/audit-logs", adminHandler.GetAuditLogs).Methods("GET")
// Log registered routes
log.Println("Registered admin routes:")
log.Println(" POST /api/admin/user/{id}/reactivate")
log.Println(" POST /api/admin/test-route/{id}")
log.Println(" PUT /api/admin/user/{id}/status")
// Security middleware
r.Use(middleware.SecurityHeaders)
r.Use(middleware.RateLimiter)
r.Use(middleware.CORS)
log.Printf("Server starting on port %s", cfg.Port)
log.Fatal(http.ListenAndServe(":"+cfg.Port, r))
}
func healthCheck(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"status":"healthy","service":"fintech-auth"}`))
}
func debugUserStatus(w http.ResponseWriter, r *http.Request) {
// Get email from URL path
vars := mux.Vars(r)
email := vars["email"]
// This is a debug endpoint - in production, remove this or add proper auth
cfg := config.Load()
db, err := database.Initialize(cfg.DatabaseURL)
if err != nil {
http.Error(w, "Database error", http.StatusInternalServerError)
return
}
defer db.Close()
userRepo := models.NewUserRepository(db)
user, err := userRepo.GetByEmail(email)
if err != nil {
http.Error(w, "User not found", http.StatusNotFound)
return
}
response := map[string]interface{}{
"id": user.ID,
"email": user.Email,
"role": user.Role,
"status": user.Status,
"created_at": user.CreatedAt,
"updated_at": user.UpdatedAt,
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
func testRoute(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
userID := vars["id"]
log.Printf("DEBUG TEST ROUTE: Received request for user ID: %s", userID)
log.Printf("DEBUG TEST ROUTE: Request method: %s", r.Method)
log.Printf("DEBUG TEST ROUTE: Request URL: %s", r.URL.Path)
response := map[string]interface{}{
"message": "Test route working",
"user_id": userID,
"method": r.Method,
"path": r.URL.Path,
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}