-
Notifications
You must be signed in to change notification settings - Fork 0
/
cookies.go
61 lines (52 loc) · 1.45 KB
/
cookies.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
// Copyright (C) 2021 Creditor Corp. Group.
// See LICENSE for copying information.
package goauth
import (
"net/http"
"time"
)
// 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 (cookieAuth *CookieAuth) GetToken(r *http.Request) (string, error) {
cookie, err := r.Cookie(cookieAuth.settings.Name)
if err != nil {
return "", err
}
return cookie.Value, nil
}
// SetTokenCookie sets parametrized token cookie that is not accessible from js.
func (cookieAuth *CookieAuth) SetTokenCookie(w http.ResponseWriter, token string) {
http.SetCookie(w, &http.Cookie{
Name: cookieAuth.settings.Name,
Value: token,
Path: cookieAuth.settings.Path,
Expires: time.Now().Add(time.Hour * 24),
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
})
}
// RemoveTokenCookie removes auth cookie that is not accessible from js.
func (cookieAuth *CookieAuth) RemoveTokenCookie(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{
Name: cookieAuth.settings.Name,
Value: "",
Path: "/",
Expires: time.Unix(0, 0),
HttpOnly: true,
SameSite: http.SameSiteStrictMode,
})
}