/
auth.go
91 lines (76 loc) · 1.93 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package middleware
import (
"encoding/csv"
"fmt"
httpAuth "github.com/abbot/go-http-auth"
"github.com/gin-gonic/gin"
"net/http"
"os"
)
const BasicAuthUserKey = "bu"
func GetBasicAuthUserFromCtx(ctx *gin.Context) (string, bool) {
bu, ok := ctx.Get(BasicAuthUserKey)
if !ok {
return "", false
}
var username string
username, ok = bu.(string)
if !ok {
return "", false
}
return username, true
}
func loadBasicAuthCredentials(htpasswdPath string) (map[string]string, error) {
// Adopted from here: https://github.com/abbot/go-http-auth/blob/master/users.go
var err error
var f *os.File
f, err = os.Open(htpasswdPath) //#nosec G304
if err != nil {
return nil, err
}
defer f.Close()
reader := csv.NewReader(f)
reader.Comma = ':'
reader.Comment = '#'
reader.TrimLeadingSpace = true
var records [][]string
records, err = reader.ReadAll()
if err != nil {
return nil, err
}
users := make(map[string]string)
for _, record := range records {
users[record[0]] = record[1]
}
return users, nil
}
func validateUserPass(users map[string]string, username, password string) bool {
storedHash, ok := users[username]
if !ok {
// invalid user
return false
}
if !httpAuth.CheckSecret(password, storedHash) {
// invalid password
return false
}
return true
}
func BasicAuthMiddleware(htpasswdPath, realm string) gin.HandlerFunc {
users, err := loadBasicAuthCredentials(htpasswdPath)
if err != nil {
panic(err)
}
wwwAuthenticateHeader := fmt.Sprintf(`Basic realm="%s", charset="UTF-8"`, realm)
return func(ctx *gin.Context) {
username, password, ok := ctx.Request.BasicAuth()
if !ok || !validateUserPass(users, username, password) {
// no credentials provided, or the provided credentials are bad
ctx.Header("WWW-Authenticate", wwwAuthenticateHeader)
ctx.AbortWithStatus(http.StatusUnauthorized)
return
}
// everything is cool and good, set the context value
ctx.Set(BasicAuthUserKey, username)
}
}