78 lines
1.9 KiB
Go
78 lines
1.9 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"git.cialloo.com/CiallooWeb/Blog/app/internal/config"
|
|
"github.com/golang-jwt/jwt/v4"
|
|
)
|
|
|
|
type SuperAdminAuthMiddleware struct {
|
|
Config config.Config
|
|
}
|
|
|
|
func NewSuperAdminAuthMiddleware(c config.Config) *SuperAdminAuthMiddleware {
|
|
return &SuperAdminAuthMiddleware{Config: c}
|
|
}
|
|
|
|
type Claims struct {
|
|
SteamID string `json:"steamId"`
|
|
jwt.RegisteredClaims
|
|
}
|
|
|
|
func (m *SuperAdminAuthMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
// Get Authorization header
|
|
authHeader := r.Header.Get("Authorization")
|
|
if authHeader == "" {
|
|
http.Error(w, "Missing authorization header", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
// Check Bearer token format
|
|
parts := strings.SplitN(authHeader, " ", 2)
|
|
if len(parts) != 2 || parts[0] != "Bearer" {
|
|
http.Error(w, "Invalid authorization header format", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
tokenString := parts[1]
|
|
|
|
// Parse and validate JWT token
|
|
claims := &Claims{}
|
|
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
|
|
// Validate signing method
|
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
return nil, jwt.ErrSignatureInvalid
|
|
}
|
|
return []byte(m.Config.JWT.Secret), nil
|
|
})
|
|
|
|
if err != nil {
|
|
http.Error(w, "Invalid token: "+err.Error(), http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
if !token.Valid {
|
|
http.Error(w, "Invalid token", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
// Validate issuer
|
|
if claims.Issuer != m.Config.JWT.Issuer {
|
|
http.Error(w, "Invalid token issuer", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
// Check if user is super admin (steamId must be "1234567")
|
|
if claims.SteamID != "1234567" {
|
|
http.Error(w, "Forbidden: Super admin access required", http.StatusForbidden)
|
|
return
|
|
}
|
|
|
|
// Passthrough to next handler if authenticated and authorized
|
|
next(w, r)
|
|
}
|
|
}
|