-
Notifications
You must be signed in to change notification settings - Fork 1
/
bearer.go
55 lines (46 loc) · 1.55 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
45
46
47
48
49
50
51
52
53
54
55
// Copyright 2021 Flamego. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package auth
import (
"net/http"
"github.com/flamego/flamego"
)
var bearerPrefix = "Bearer "
// Token is the authenticated token that was extracted from the request.
type Token string
// Bearer returns a middleware handler that injects auth.Token
// into the request context upon successful bearer authentication. The handler
// responds http.StatusUnauthorized when authentication fails.
func Bearer(token string) flamego.Handler {
return flamego.ContextInvoker(func(c flamego.Context) {
got := c.Request().Header.Get("Authorization")
if !SecureCompare(bearerPrefix+token, got) {
bearerUnauthorized(c.ResponseWriter())
return
}
c.Map(Token(token))
})
}
// BearerFunc returns a middleware handler that injects auth.Token
// into the request context upon successful bearer authentication with the given
// function. The function should return true for a valid bearer token.
func BearerFunc(fn func(token string) bool) flamego.Handler {
return flamego.ContextInvoker(func(c flamego.Context) {
auth := c.Request().Header.Get("Authorization")
n := len(bearerPrefix)
if len(auth) < n || auth[:n] != bearerPrefix {
bearerUnauthorized(c.ResponseWriter())
return
}
token := auth[n:]
if !fn(token) {
bearerUnauthorized(c.ResponseWriter())
return
}
c.Map(Token(token))
})
}
func bearerUnauthorized(res http.ResponseWriter) {
http.Error(res, "Unauthorized", http.StatusUnauthorized)
}