-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbasic.go
64 lines (56 loc) · 1.94 KB
/
basic.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
// 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 (
"encoding/base64"
"net/http"
"strings"
"github.com/flamego/flamego"
)
const basicPrefix = "Basic "
// User is the authenticated username that was extracted from the request.
type User string
// Basic returns a middleware handler that injects auth.User into the request
// context upon successful basic authentication. The handler responds
// http.StatusUnauthorized when authentication fails.
func Basic(username, password string) flamego.Handler {
want := base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
return flamego.ContextInvoker(func(c flamego.Context) {
got := c.Request().Header.Get("Authorization")
if !SecureCompare(basicPrefix+want, got) {
basicUnauthorized(c.ResponseWriter())
return
}
c.Map(User(username))
})
}
// BasicFunc returns a middleware handler that injects auth.User into the
// request context upon successful basic authentication with the given function.
// The function should return true for a valid username and password
// combination.
func BasicFunc(fn func(username, password string) bool) flamego.Handler {
return flamego.ContextInvoker(func(c flamego.Context) {
auth := c.Request().Header.Get("Authorization")
n := len(basicPrefix)
if len(auth) < n || auth[:n] != basicPrefix {
basicUnauthorized(c.ResponseWriter())
return
}
b, err := base64.StdEncoding.DecodeString(auth[n:])
if err != nil {
basicUnauthorized(c.ResponseWriter())
return
}
tokens := strings.SplitN(string(b), ":", 2)
if len(tokens) != 2 || !fn(tokens[0], tokens[1]) {
basicUnauthorized(c.ResponseWriter())
return
}
c.Map(User(tokens[0]))
})
}
func basicUnauthorized(w http.ResponseWriter) {
w.Header().Set("WWW-Authenticate", `Basic realm="Authorization Required"`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
}