MCPcopy Create free account
hub / github.com/devaccuracy/ledgerforge / Authenticate

Method Authenticate

api/middleware/auth.go:181–276  ·  view source on GitHub ↗

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

()

Source from the content-addressed store, hash-verified

179// - 401 Unauthorized: When the API key is missing or invalid.
180// - 403 Forbidden: When the API key lacks sufficient permissions.
181func (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

Callers 2

RouterMethod · 0.80

Calls 10

FetchFunction · 0.92
extractKeyFunction · 0.85
getResourceFromPathFunction · 0.85
HasPermissionFunction · 0.85
injectAPIKeyToMetadataFunction · 0.85
GetAPIKeyByKeyMethod · 0.80
IsValidMethod · 0.80
SetMethod · 0.65
UpdateLastUsedMethod · 0.65
ErrorMethod · 0.45

Tested by 1