-
Notifications
You must be signed in to change notification settings - Fork 0
/
webutils.go
78 lines (62 loc) · 1.64 KB
/
webutils.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
package goscreenmonit
import (
"encoding/json"
"io/ioutil"
"net/http"
"os"
"strings"
"github.com/gorilla/mux"
)
// An http basic auth middleware
func basicAuth(credentials map[string]string) mux.MiddlewareFunc {
// Middleware function
return func(h http.Handler) http.Handler {
// Http handler
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
// Check for authorization header existence
s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
if len(s) != 2 {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
// Get basic auth user and pass
sentUser, sentPass, ok := r.BasicAuth()
if !ok {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
// Check for credential set
userPass, ok := credentials[sentUser]
if !ok {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
// Validate user password
if sentPass != userPass {
http.Error(w, "Not authorized", http.StatusUnauthorized)
return
}
h.ServeHTTP(w, r)
})
}
}
// Read a credentials json file and return the resulting credentials map
func parseCredsFile(file string) (map[string]string, error) {
// Open file from fs
credsFile, rerr := os.Open(file)
if rerr != nil {
return nil, rerr
}
// Read bytes into byte slice
credsBytes, rferr := ioutil.ReadAll(credsFile)
if rferr != nil {
return nil, rferr
}
// Parse json data from bytes
creds := map[string]string{}
if perr := json.Unmarshal(credsBytes, &creds); perr != nil {
return nil, perr
}
return creds, nil
}