-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauth_middleware.go
84 lines (66 loc) · 1.35 KB
/
auth_middleware.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
package main
import (
"bufio"
"crypto/sha1"
"fmt"
"log"
"net/http"
"os"
"strings"
"github.com/gin-gonic/gin"
)
const (
envAuthFile = "AUTH_FILE"
defaultAuthFile = "access"
)
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
username, password, ok := c.Request.BasicAuth()
if !ok {
c.AbortWithStatus(http.StatusForbidden)
return
}
if !validateAuth(username, password) {
c.AbortWithStatus(http.StatusForbidden)
return
}
c.Next()
}
}
func validateAuth(username, password string) bool {
// Password sha1
password = fmt.Sprintf("%x", sha1.Sum([]byte(password)))
authFile := defaultAuthFile
if e := os.Getenv(envAuthFile); e != "" {
authFile = e
}
// Re-open auth file each time, to avoid reloading it
file, err := os.Open(authFile)
if err != nil {
panic(err)
}
defer file.Close()
// Scan line by line
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if line[0] == '#' {
continue
}
// Split format: username:sha1_password
splited := strings.SplitN(line, `:`, 2)
if len(splited) != 2 {
continue
}
log.Println(splited, username, password)
// Check credentials
if splited[0] == username && splited[1] == password {
return true
}
}
if err := scanner.Err(); err != nil {
panic(err)
}
log.Println("Bad password")
return false
}