First setup of a go server

This commit is contained in:
2026-01-23 20:05:23 +01:00
parent 6202b585e7
commit 3f11bad8f6
8 changed files with 412 additions and 0 deletions

50
middleware/auth.go Normal file
View File

@@ -0,0 +1,50 @@
package middleware
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
var jwtSecret = []byte("your-secret-key") // Should match the one in handlers/auth.go
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header required"})
c.Abort()
return
}
// Extract token from "Bearer <token>" format
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
if tokenString == authHeader {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token format"})
c.Abort()
return
}
// Parse and validate token
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return jwtSecret, nil
})
if err != nil || !token.Valid {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
c.Abort()
return
}
// Extract claims
if claims, ok := token.Claims.(jwt.MapClaims); ok {
if userID, ok := claims["user_id"].(float64); ok {
c.Set("user_id", uint(userID))
}
}
c.Next()
}
}