-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
45 lines (40 loc) · 1.37 KB
/
auth.go
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
42
43
44
45
package main
import (
"encoding/base64"
"log"
"net/http"
"strconv"
"strings"
"github.com/gin-gonic/gin"
)
// BasicAuth is a variation of the gin.BasicAuth middleware allowing for a
// callback function, rather than preloading credentials.
func BasicAuth(afunc func(string, string) bool, realm string) gin.HandlerFunc {
if realm == "" {
realm = "Authorization Required"
}
realm = "Basic realm=" + strconv.Quote(realm)
return func(c *gin.Context) {
// Search user in the slice of allowed credentials
auth := strings.SplitN(c.Request.Header.Get("Authorization"), " ", 2)
if len(auth) != 2 || auth[0] != "Basic" {
log.Printf("BasicAuth(): found %v", auth)
c.Header("WWW-Authenticate", realm)
c.AbortWithStatus(http.StatusUnauthorized)
return
}
payload, _ := base64.StdEncoding.DecodeString(auth[1])
pair := strings.SplitN(string(payload), ":", 2)
if !afunc(pair[0], pair[1]) {
// Credentials doesn't match, we return 401 and abort handlers chain.
log.Printf("BasicAuth(): Credentials for %s do not match", pair[0])
c.Header("WWW-Authenticate", realm)
c.AbortWithStatus(401)
} else {
// The user credentials was found, set user's id to key AuthUserKey in this context, the userId can be read later using
// c.MustGet(gin.AuthUserKey)
log.Printf("BasicAuth() [%s]: Authenticated user", pair[0])
c.Set(gin.AuthUserKey, pair[0])
}
}
}