-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.go
More file actions
41 lines (33 loc) · 1.05 KB
/
auth.go
File metadata and controls
41 lines (33 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package middleware
import (
"crypto/subtle"
"net/http"
"github.com/gin-gonic/gin"
"github.com/kevingruber/gradle-cache/internal/config"
)
// CacheAuth creates a middleware that validates HTTP Basic Authentication
func CacheAuth(auth config.AuthConfig, requireWriter bool) gin.HandlerFunc {
return func(c *gin.Context) {
username, password, ok := c.Request.BasicAuth()
if !ok {
c.Header("WWW-Authenticate", `Basic realm="Gradle Build Cache"`)
c.AbortWithStatus(http.StatusUnauthorized)
return
}
// Check credentials
isReader := username == auth.Reader.Username &&
subtle.ConstantTimeCompare([]byte(password), []byte(auth.Reader.Password)) == 1
isWriter := username == auth.Writer.Username &&
subtle.ConstantTimeCompare([]byte(password), []byte(auth.Writer.Password)) == 1
if !isReader && !isWriter {
c.Header("WWW-Authenticate", `Basic realm="Gradle Build Cache"`)
c.AbortWithStatus(http.StatusUnauthorized)
return
}
if requireWriter && !isWriter {
c.AbortWithStatus(http.StatusForbidden)
return
}
c.Next()
}
}