forked from go-macaron/auth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bearer.go
44 lines (38 loc) · 1.12 KB
/
bearer.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
package auth
import (
"net/http"
"gopkg.in/macaron.v1"
)
var bearerPrefix = "Bearer "
// Bearer returns a Handler that authenticates via Bearer Auth. Writes a http.StatusUnauthorized
// if authentication fails.
func Bearer(token string) macaron.Handler {
return func(res http.ResponseWriter, req *http.Request, c *macaron.Context) {
auth := req.Header.Get("Authorization")
if !SecureCompare(auth, bearerPrefix+token) {
bearerUnauthorized(res)
return
}
c.Map(User(""))
}
}
// BearerFunc returns a Handler that authenticates via Bearer Auth using the provided function.
// The function should return true for a valid bearer token.
func BearerFunc(authfn func(string) bool) macaron.Handler {
return func(res http.ResponseWriter, req *http.Request, c *macaron.Context) {
auth := req.Header.Get("Authorization")
n := len(bearerPrefix)
if len(auth) < n || auth[:n] != bearerPrefix {
bearerUnauthorized(res)
return
}
if !authfn(auth[n:]) {
bearerUnauthorized(res)
return
}
c.Map(User(""))
}
}
func bearerUnauthorized(res http.ResponseWriter) {
http.Error(res, "Not Authorized", http.StatusUnauthorized)
}