feat(authentication): Added authentication controller & JWTMiddleware

This commit is contained in:
2026-05-28 17:58:20 +03:30
parent bdb2fcc68f
commit 0b4cb868e7
9 changed files with 603 additions and 64 deletions
+24 -12
View File
@@ -14,6 +14,7 @@ import (
"github.com/go-chi/cors"
"medad.fun/internal/api"
"medad.fun/internal/api/v1/middleware"
"medad.fun/internal/config"
"medad.fun/internal/database"
"medad.fun/internal/frontend"
@@ -26,7 +27,6 @@ func main() {
if err != nil {
log.Fatalln("error loading configuration:", err)
}
log.Printf("Starting medad.fun server version '%s'\n", version.Version)
if cfg.CPUProfilePath != "" {
@@ -45,14 +45,29 @@ func main() {
AllowedOrigins: cfg.CORS.AllowedOrigins,
AllowCredentials: cfg.CORS.AllowCredentials,
})
register := func(method, path string, handler http.HandlerFunc) {
// Each path needs to start with a slash anyway, so this is convenient.
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
log.Printf("Registering route: %s %s\n", method, path)
router.HandleFunc(fmt.Sprintf("%s %s", method, path), corsWrapper(handler).ServeHTTP)
// 1. Create a basic register function for public routes
register := func(method, p string, handler http.HandlerFunc) {
if !strings.HasPrefix(p, "/") {
p = "/" + p
}
log.Printf("Registering route: %s %s\n", method, p)
// Wrap with CORS
router.HandleFunc(fmt.Sprintf("%s %s", method, p), corsWrapper(handler).ServeHTTP)
}
// 2. Create a protected register function for authenticated routes
// This wraps the handler in JWT middleware BEFORE CORS
protectedRegister := func(method, p string, handler http.HandlerFunc) {
if !strings.HasPrefix(p, "/") {
p = "/" + p
}
log.Printf("Registering PROTECTED route: %s %s\n", method, p)
// Chain: JWT Middleware -> CORS Wrapper -> Actual Handler
// Note: JWT checks auth first. If valid, it passes to CORS, then handler.
protectedHandler := middleware.JWTMiddleware([]byte(cfg.JWTSecret))(http.HandlerFunc(handler))
router.HandleFunc(fmt.Sprintf("%s %s", method, p), corsWrapper(protectedHandler).ServeHTTP)
}
// Healthcheck for deployments with monitoring if required.
@@ -60,7 +75,7 @@ func main() {
writer.WriteHeader(http.StatusOK)
})
api.NewHandler(cfg).SetupRoutes(cfg.RootPath, register)
api.NewHandler(cfg).SetupRoutes(cfg.RootPath, register, protectedRegister)
frontendHandler, err := frontend.NewHandler(cfg)
if err != nil {
@@ -76,9 +91,7 @@ func main() {
signal.Notify(signalChan, syscall.SIGTERM, syscall.SIGINT)
go func() {
defer os.Exit(0)
log.Printf("Received %s, gracefully shutting down.\n", <-signalChan)
state.ShutdownLobbiesGracefully()
if cfg.CPUProfilePath != "" {
pprof.StopCPUProfile()
@@ -97,7 +110,6 @@ func main() {
if r.URL.Path != "/" && r.URL.Path[len(r.URL.Path)-1] == '/' {
r.URL.Path = r.URL.Path[:len(r.URL.Path)-1]
}
router.ServeHTTP(w, r)
}),
ReadHeaderTimeout: 10 * time.Second,