-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbasic-auth.go
100 lines (77 loc) · 1.65 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
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
92
93
94
95
96
97
98
99
100
package artichoke
import (
"bytes"
"encoding/base64"
"net/http"
"strings"
)
type Auth struct {
User string
Pass string
Authenticated bool
}
func NewAuth(u string, p string, a bool) *Auth {
auth := new(Auth)
auth.User = u
auth.Pass = p
auth.Authenticated = a
return auth
}
type AuthError struct {
err string
}
func NewError(msg string) *AuthError {
e := new(AuthError)
e.err = msg
return e
}
func (e *AuthError) String() string {
return e.err
}
func GetAuth(d Data) *Auth {
if a, ok := d.Get("auth"); ok {
return a.(*Auth)
}
return nil
}
func Authenticated(d Data) bool {
if auth := GetAuth(d); auth != nil {
return auth.Authenticated
}
return false
}
func BasicAuth(auth map[string]string, required bool) Middleware {
return func(w http.ResponseWriter, r *http.Request, m Data) bool {
buf := bytes.Buffer{}
str := r.Header.Get("authorization")
if len(str) == 0 {
if required {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Authorization required"))
w.Write([]byte(""))
}
return required
}
// just get the auth part
str = strings.Split(str, " ")[1]
i := len(str)/4*3 - strings.Count(str, "=")
outBuf := make([]byte, len(str)/4*3)
dec := base64.NewDecoder(base64.StdEncoding, &buf)
buf.WriteString(str)
dec.Read(outBuf)
cAuth := strings.Split(string(outBuf[:i]), ":")
user := cAuth[0]
pass := cAuth[1]
success := auth[user] == pass
m.Set("auth", NewAuth(user, pass, success))
if success {
if required {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Not authorized"))
w.Write([]byte(""))
}
return required
}
return false
}
}