-
Notifications
You must be signed in to change notification settings - Fork 0
/
basic_auth.go
61 lines (52 loc) · 1.18 KB
/
basic_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
package main
import (
"encoding/base64"
"io/ioutil"
"net/http"
"strings"
"golang.org/x/crypto/bcrypt"
)
func checkAuth(w http.ResponseWriter, r *http.Request, role string) bool {
s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
if len(s) != 2 {
return false
}
b, err := base64.StdEncoding.DecodeString(s[1])
if err != nil {
return false
}
pair := strings.SplitN(string(b), ":", 2)
if len(pair) != 2 {
return false
}
// Get informations from file
data, err := ioutil.ReadFile("./data/" + role + "_" + pair[0])
if err != nil {
return false
} else {
fields := strings.Split(string(data), ":")
storedPassword := strings.Replace(fields[1], "\n", "", 1)
err = bcrypt.CompareHashAndPassword([]byte(storedPassword), []byte(pair[1]))
if err != nil {
return false
} else {
// Return user
return true
}
}
}
func getUserFromAuth(w http.ResponseWriter, r *http.Request) string {
s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
if len(s) != 2 {
return ""
}
b, err := base64.StdEncoding.DecodeString(s[1])
if err != nil {
return ""
}
pair := strings.SplitN(string(b), ":", 2)
if len(pair) != 2 {
return ""
}
return pair[0]
}