Authenticate returns a middleware function that handles authentication and authorization for all routes. It checks for the X-LedgerForge-Key header and validates it against either the master key or API keys. For API keys, it verifies the key's validity and checks permissions based on the resource an
()
| 179 | // - 401 Unauthorized: When the API key is missing or invalid. |
| 180 | // - 403 Forbidden: When the API key lacks sufficient permissions. |
| 181 | func (m *AuthMiddleware) Authenticate() gin.HandlerFunc { |
| 182 | return func(c *gin.Context) { |
| 183 | // Skip auth for root path |
| 184 | if c.Request != nil && c.Request.URL != nil && c.Request.URL.Path == "/" { |
| 185 | c.Next() |
| 186 | return |
| 187 | } |
| 188 | |
| 189 | // Skip auth for health endpoint (server health check only) |
| 190 | if c.Request != nil && c.Request.URL != nil && c.Request.URL.Path == "/health" { |
| 191 | c.Next() |
| 192 | return |
| 193 | } |
| 194 | |
| 195 | // Skip X-LedgerForge-Key auth for metrics endpoint, it uses its own bearer token auth |
| 196 | if c.Request != nil && c.Request.URL != nil && c.Request.URL.Path == "/metrics" { |
| 197 | c.Next() |
| 198 | return |
| 199 | } |
| 200 | |
| 201 | // Check if secure mode is enabled |
| 202 | conf, err := config.Fetch() |
| 203 | if err == nil && conf != nil && !conf.Server.Secure { |
| 204 | // Skip authentication when secure mode is disabled |
| 205 | c.Next() |
| 206 | return |
| 207 | } |
| 208 | |
| 209 | key := extractKey(c) |
| 210 | if key == "" { |
| 211 | c.JSON(401, gin.H{"error": "Authentication required. Use X-LedgerForge-Key header"}) |
| 212 | c.Abort() |
| 213 | return |
| 214 | } |
| 215 | |
| 216 | // First check if it's the master key |
| 217 | if err == nil && conf != nil && conf.Server.SecretKey == key { |
| 218 | // Master key has all permissions |
| 219 | c.Set("isMasterKey", true) |
| 220 | c.Next() |
| 221 | return |
| 222 | } |
| 223 | |
| 224 | // If not master key, try API key authentication |
| 225 | apiKey, err := m.service.GetAPIKeyByKey(c.Request.Context(), key) |
| 226 | if err != nil { |
| 227 | c.JSON(401, gin.H{"error": "Invalid API key"}) |
| 228 | c.Abort() |
| 229 | return |
| 230 | } |
| 231 | |
| 232 | if !apiKey.IsValid() { |
| 233 | c.JSON(401, gin.H{"error": "API key is expired or revoked"}) |
| 234 | c.Abort() |
| 235 | return |
| 236 | } |
| 237 | |
| 238 | // Determine required resource from path |