-
Notifications
You must be signed in to change notification settings - Fork 77
/
auth.go
60 lines (47 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package main
import (
"crypto/rand"
"encoding/base64"
"fmt"
"log"
"net/http"
"strings"
)
// authMiddleware checks basic auth
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
auth := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
if len(auth) != 2 || auth[0] != "Basic" {
http.Error(w, "authorization failed", http.StatusUnauthorized)
return
}
payload, _ := base64.StdEncoding.DecodeString(auth[1])
pair := strings.SplitN(string(payload), ":", 2)
if strings.Compare(pair[0], username) != 0 || strings.Compare(pair[1], password) != 0 {
http.Error(w, "authorization failed", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
func parseAuth(auth string) {
identity := strings.Split(*setBasicAuth, ":")
if len(identity) != 2 {
log.Fatalln("basic auth must be like this: user:password")
}
username = identity[0]
password = identity[1]
}
func generateRandomAuth() {
username = *defaultUsernameBasicAuth
password = generateRandomString()
log.Printf("User generated for basic auth. User:'%v', password:'%v'\n", username, password)
}
func generateRandomString() string {
b := make([]byte, *sizeRandom)
if _, err := rand.Read(b); err != nil {
panic(err)
}
return fmt.Sprintf("%X", b)
}