-
Notifications
You must be signed in to change notification settings - Fork 390
/
auth.go
77 lines (65 loc) · 1.89 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
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package consolewebauth
import (
"net/http"
"time"
"storj.io/storj/satellite/console"
"storj.io/storj/satellite/console/consoleauth"
)
// CookieSettings variable cookie settings.
type CookieSettings struct {
Name string
Path string
}
// CookieAuth handles cookie authorization.
type CookieAuth struct {
settings CookieSettings
}
// NewCookieAuth create new cookie authorization with provided settings.
func NewCookieAuth(settings CookieSettings) *CookieAuth {
return &CookieAuth{
settings: settings,
}
}
// GetToken retrieves token from request.
func (auth *CookieAuth) GetToken(r *http.Request) (console.TokenInfo, error) {
cookie, err := r.Cookie(auth.settings.Name)
if err != nil {
return console.TokenInfo{}, err
}
token, err := consoleauth.FromBase64URLString(cookie.Value)
if err != nil {
return console.TokenInfo{}, err
}
return console.TokenInfo{
Token: token,
ExpiresAt: cookie.Expires,
}, nil
}
// SetTokenCookie sets parametrized token cookie that is not accessible from js.
func (auth *CookieAuth) SetTokenCookie(w http.ResponseWriter, tokenInfo console.TokenInfo) {
http.SetCookie(w, &http.Cookie{
Name: auth.settings.Name,
Value: tokenInfo.Token.String(),
Path: auth.settings.Path,
Expires: tokenInfo.ExpiresAt,
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
})
}
// RemoveTokenCookie removes auth cookie that is not accessible from js.
func (auth *CookieAuth) RemoveTokenCookie(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{
Name: auth.settings.Name,
Value: "",
Path: auth.settings.Path,
Expires: time.Unix(0, 0),
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
})
}
// GetTokenCookieName returns the name of the cookie storing the session token.
func (auth *CookieAuth) GetTokenCookieName() string {
return auth.settings.Name
}