-
-
Notifications
You must be signed in to change notification settings - Fork 64
/
auth.go
145 lines (120 loc) · 2.48 KB
/
auth.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package irt
import (
"encoding/base64"
"fmt"
"net/http"
"strings"
)
type AuthCustom struct {
Value string
}
func NewAuthCustom(value string) *AuthCustom {
return &AuthCustom{
Value: value,
}
}
type AuthApiKey struct {
ApiKey string
}
func NewAuthApiKey(apiKey string) *AuthApiKey {
return &AuthApiKey{
ApiKey: apiKey,
}
}
type AuthToken struct {
Token string
}
func NewAuthToken(token string) *AuthToken {
return &AuthToken{
Token: token,
}
}
type AuthBasic struct {
User string
Pass string
}
func (a *AuthBasic) GetPass() (string, error) {
pass, err := base64.StdEncoding.DecodeString(a.Pass)
if err != nil {
return "", err
}
return string(pass), nil
}
func NewAuthBasic(user string, pass string) *AuthBasic {
return &AuthBasic{
User: user,
Pass: base64.StdEncoding.EncodeToString([]byte(pass)),
}
}
type Authorization struct {
ApiKey *AuthApiKey
Token *AuthToken
Basic *AuthBasic
Custom *AuthCustom
}
func (c *Authorization) Reset() {
c.ApiKey = nil
c.Token = nil
c.Basic = nil
c.Custom = nil
}
func (c *Authorization) UpdateFromRequest(r http.Request) error {
return c.UpdateFromHeaders(r.Header)
}
func (c *Authorization) UpdateFromHeaders(h http.Header) error {
header := h.Get("Authorization")
if header == "" {
return nil
}
return c.UpdateFromValue(header)
}
func (c *Authorization) UpdateFromValue(auth string) error {
pieces := strings.Split(auth, " ")
if len(pieces) != 2 {
if len(auth) != 0 {
c.Custom = NewAuthCustom(auth)
return nil
}
return fmt.Errorf("authorization update expects 'Type Value' format, got '%s'", auth)
}
switch strings.ToLower(pieces[0]) {
case "bearer":
c.Token = &AuthToken{
Token: pieces[1],
}
// There are a few variations exist, Apikey, ApiKey, Api-Key, covering all there.
case "apikey":
fallthrough
case "api-key":
c.ApiKey = &AuthApiKey{
ApiKey: pieces[1],
}
case "basic":
basicPieces := strings.Split(pieces[1], ":")
if len(pieces) != 2 {
return fmt.Errorf("basic authorization expects 'user:pass' format, got '%s'", pieces[1])
}
c.Basic = &AuthBasic{
User: basicPieces[0],
Pass: basicPieces[1],
}
default:
c.Custom = NewAuthCustom(auth)
}
return nil
}
func (c *Authorization) ToValue() string {
if c.Token != nil {
return "Bearer " + c.Token.Token
}
if c.ApiKey != nil {
return "Api-Key " + c.ApiKey.ApiKey
}
if c.Basic != nil {
return "Basic " + c.Basic.User + ":" + c.Basic.Pass
}
if c.Custom != nil {
return c.Custom.Value
}
return ""
}