-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.go
More file actions
208 lines (176 loc) · 4.92 KB
/
auth.go
File metadata and controls
208 lines (176 loc) · 4.92 KB
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
package auth
import (
"context"
"fmt"
"net/http"
"time"
"github.com/go-modulus/auth/locales"
"github.com/go-modulus/modulus/errors"
"github.com/go-modulus/modulus/errors/erruser"
"github.com/go-modulus/modulus/translation"
"github.com/gofrs/uuid"
"github.com/sethvargo/go-envconfig"
"github.com/vorlif/spreak/localize"
)
const TagUnauthenticated = "unauthenticated"
const TagUnauthorized = "unauthorized"
var ErrInvalidToken = translation.WithDomain(
erruser.New("invalid access token", "Please provide a valid access token"),
locales.Domain,
)
var ErrUnauthenticated = translation.WithDomain(
errors.WithAddedTags(
erruser.New("unauthenticated", localize.Singular("Please authenticate to get access to this resource")),
TagUnauthenticated,
), locales.Domain,
)
var ErrUnauthorized = translation.WithDomain(
errors.WithAddedTags(
erruser.New("unauthorized", "You are not authorized to access this resource"),
TagUnauthorized,
),
locales.Domain,
)
type Performer struct {
ID uuid.UUID
SessionID uuid.UUID
Roles []string
IdentityID uuid.UUID
}
type Authenticator interface {
// Authenticate authenticates the user with the given token.
// It returns the performer of the authenticated user.
//
// Errors:
// * github.com/go-modulus/auth.ErrTokenIsRevoked - if the token is revoked.
// * github.com/go-modulus/auth.ErrTokenIsExpired - if the token is expired.
Authenticate(ctx context.Context, token string) (Performer, error)
}
type contextKey string
var performerKey = contextKey("Performer")
func WithPerformer(ctx context.Context, performer Performer) context.Context {
return context.WithValue(ctx, performerKey, performer)
}
func GetPerformer(ctx context.Context) Performer {
if value := ctx.Value(performerKey); value != nil {
performer, ok := value.(Performer)
if ok {
return performer
}
}
return Performer{}
}
func GetPerformerID(ctx context.Context) uuid.UUID {
if value := ctx.Value(performerKey); value != nil {
performer, ok := value.(Performer)
if ok {
return performer.ID
}
}
return uuid.Nil
}
var refreshTokenKey = contextKey("RefreshToken")
type refreshTokenContainer struct {
value string
wrote bool
}
func WithRefreshToken(ctx context.Context, refreshToken string) context.Context {
return context.WithValue(ctx, refreshTokenKey, &refreshTokenContainer{value: refreshToken})
}
func SendRefreshToken(ctx context.Context, token string) {
if value := ctx.Value(refreshTokenKey); value != nil {
refreshToken, ok := value.(*refreshTokenContainer)
if ok {
refreshToken.value = token
refreshToken.wrote = true
}
}
}
func RemoveRefreshToken(ctx context.Context) {
SendRefreshToken(ctx, "")
}
func GetRefreshToken(ctx context.Context) string {
if value := ctx.Value(refreshTokenKey); value != nil {
refreshToken, ok := value.(*refreshTokenContainer)
if ok {
return refreshToken.value
}
}
return ""
}
type refreshTokenResponseWriter struct {
http.ResponseWriter
ctx context.Context
written bool
config RefreshTokenConfig
}
func (rw *refreshTokenResponseWriter) Flush() {
if f, ok := rw.ResponseWriter.(http.Flusher); ok {
f.Flush()
} else {
panic(fmt.Errorf("ResponseWriter does not implement http.Flusher"))
}
}
func (rw *refreshTokenResponseWriter) Write(b []byte) (int, error) {
rw.writeCookie()
return rw.ResponseWriter.Write(b)
}
func (rw *refreshTokenResponseWriter) WriteHeader(code int) {
rw.writeCookie()
rw.ResponseWriter.WriteHeader(code)
}
func (rw *refreshTokenResponseWriter) writeCookie() {
if rw.written {
return
}
rw.written = true
value := rw.ctx.Value(refreshTokenKey)
if value == nil {
return
}
rfc, ok := value.(*refreshTokenContainer)
if !ok {
return
}
refreshToken := rfc.value
if !rfc.wrote {
return
}
cookie := http.Cookie{
Name: rw.config.CookieName,
Value: "",
HttpOnly: true,
Secure: false,
Path: "/",
Domain: rw.config.CookieDomain,
}
if rw.config.CookieSecure {
cookie.Secure = true
cookie.SameSite = http.SameSiteNoneMode
}
if refreshToken == "" {
cookie.Expires = time.Unix(1, 0)
cookie.MaxAge = -1
} else {
cookie.Value = refreshToken
cookie.Expires = time.Now().Add(rw.config.TTL)
}
rw.ResponseWriter.Header().Add("Set-Cookie", cookie.String())
rw.ResponseWriter.Header().Add("Cache-Control", `no-cache="Set-Cookie"`)
}
func (rw *refreshTokenResponseWriter) Unwrap() http.ResponseWriter {
return rw.ResponseWriter
}
type RefreshTokenConfig struct {
CookieName string `env:"REFRESH_TOKEN_COOKIE_NAME, default=art"`
CookieDomain string `env:"REFRESH_TOKEN_COOKIE_DOMAIN, default=localhost"`
CookieSecure bool `env:"REFRESH_TOKEN_COOKIE_SECURE, default=false"`
TTL time.Duration `env:"AUTH_REFRESH_TOKEN_TTL, default=8760h"`
}
type MiddlewareConfig struct {
RefreshTokenConfig
}
func NewMiddlewareConfig() (*MiddlewareConfig, error) {
config := MiddlewareConfig{}
return &config, envconfig.Process(context.Background(), &config)
}