forked from aaron-lebo/auth
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic.go
More file actions
59 lines (54 loc) · 1.74 KB
/
basic.go
File metadata and controls
59 lines (54 loc) · 1.74 KB
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
package auth
import (
"encoding/base64"
"github.com/urfave/negroni"
"net/http"
"strings"
)
// BasicRealm is used when setting the WWW-Authenticate response header.
var BasicRealm = "Authorization Required"
// Basic returns a Handler that authenticates via Basic Auth. Writes a http.StatusUnauthorized
// if authentication fails.
func Basic(username string, password string) negroni.HandlerFunc {
var siteAuth = base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
return func(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
auth := req.Header.Get("Authorization")
if !SecureCompare(auth, "Basic "+siteAuth) {
unauthorized(res)
return
}
r := res.(negroni.ResponseWriter)
if r.Status() != http.StatusUnauthorized {
next(res, req)
}
}
}
// BasicFunc returns a Handler that authenticates via Basic Auth using the provided function.
// The function should return true for a valid username/password combination.
func BasicFunc(authfn func(string, string) bool) negroni.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
auth := req.Header.Get("Authorization")
if len(auth) < 6 || auth[:6] != "Basic " {
unauthorized(res)
return
}
b, err := base64.StdEncoding.DecodeString(auth[6:])
if err != nil {
unauthorized(res)
return
}
tokens := strings.SplitN(string(b), ":", 2)
if len(tokens) != 2 || !authfn(tokens[0], tokens[1]) {
unauthorized(res)
return
}
r := res.(negroni.ResponseWriter)
if r.Status() != http.StatusUnauthorized {
next(res, req)
}
}
}
func unauthorized(res http.ResponseWriter) {
res.Header().Set("WWW-Authenticate", "Basic realm=\""+BasicRealm+"\"")
http.Error(res, "Not Authorized", http.StatusUnauthorized)
}