-
Notifications
You must be signed in to change notification settings - Fork 0
/
basicauth.go
87 lines (69 loc) · 1.98 KB
/
basicauth.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
package basicauth
import (
"bytes"
"encoding/base64"
"github.com/valyala/fasthttp"
"golang.org/x/crypto/bcrypt"
"strings"
)
type Credential struct {
Username string
Password string
Uris []string
}
type Provider struct {
Credentials []Credential
}
var ProviderName = "basicauth"
func New(credentials ...Credential) *Provider {
return &Provider{Credentials: credentials}
}
func (p Provider) GetProviderName() string {
return ProviderName
}
func (p Provider) GetUniqueIdentifier(ctx *fasthttp.RequestCtx) string {
user, _ := p.getCredentials(ctx)
return user
}
func (p Provider) IsAuthenticated(ctx *fasthttp.RequestCtx) bool {
user, pass := p.getCredentials(ctx)
for _, credential := range p.Credentials {
if credential.Username == user && bcrypt.CompareHashAndPassword([]byte(credential.Password), []byte(pass)) == nil {
for _, uri := range credential.Uris {
if uri == "*" {
return true
}
if strings.HasSuffix(uri, "*") && strings.HasPrefix(string(ctx.URI().Path()), uri[:len(uri)-1]) {
return true
}
}
}
}
ctx.Response.Header.Set("WWW-Authenticate", "Basic realm=Restricted")
ctx.SetStatusCode(fasthttp.StatusUnauthorized)
return false
}
func (p Provider) Login(ctx *fasthttp.RequestCtx) (bool, []error) {
return true, []error{}
}
func (p Provider) Logout(ctx *fasthttp.RequestCtx) bool {
ctx.Response.Header.Set("WWW-Authenticate", "Basic realm=Restricted")
ctx.SetStatusCode(fasthttp.StatusUnauthorized)
return false
}
func (p Provider) Register(ctx *fasthttp.RequestCtx) (bool, []error) {
return true, []error{}
}
func (p Provider) getCredentials(ctx *fasthttp.RequestCtx) (string, string) {
auth := ctx.Request.Header.Peek("Authorization")
if bytes.HasPrefix(auth, []byte("Basic ")) {
payload, err := base64.StdEncoding.DecodeString(string(auth[len([]byte("Basic ")):]))
if err == nil {
pair := bytes.SplitN(payload, []byte(":"), 2)
if len(pair) == 2 {
return string(pair[0]), string(pair[1])
}
}
}
return "", ""
}