-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcookie.go
74 lines (67 loc) · 2 KB
/
cookie.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
package vcago
import (
"net/http"
"github.com/golang-jwt/jwt"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
//CookieConfig represents the cookie parameters
type CookieConfig struct {
SameSite http.SameSite
Secure bool
HttpOnly bool
}
//NewCookieConfig loads the cookie parameters from the .env file and return a new CookieConfig.
func NewCookieConfig() *CookieConfig {
cookieSameSite := Settings.String("COOKIE_SAME_SITE", "w", "strict")
sameSite := http.SameSiteStrictMode
if cookieSameSite == "lax" {
sameSite = http.SameSiteLaxMode
}
if cookieSameSite == "strict" {
sameSite = http.SameSiteStrictMode
}
if cookieSameSite == "none" {
sameSite = http.SameSiteNoneMode
}
return &CookieConfig{
SameSite: sameSite,
Secure: Settings.Bool("COOKIE_SECURE", "w", true),
HttpOnly: Settings.Bool("COOKIE_HTTP_ONLY", "w", true),
}
}
//Cookie returns an http.Cookie using the CookieConfig parameters.
// @param name cookie name
// @param value cookie value
func (i *CookieConfig) Cookie(name string, value string) *http.Cookie {
return &http.Cookie{
SameSite: i.SameSite,
Secure: i.Secure,
HttpOnly: i.HttpOnly,
Path: "/",
Name: name,
Value: value,
}
}
//AccessCookieConfig can with echo for middleware.JWTWithConfig(vmod.AccessConfig) to handling access controll
//The token is reachable with c.Get("token")
func AccessCookieMiddleware(i jwt.Claims) echo.MiddlewareFunc {
return middleware.JWTWithConfig(
middleware.JWTConfig{
Claims: i,
ContextKey: "token",
TokenLookup: "cookie:access_token",
SigningKey: []byte(jwtSecret),
})
}
//RefreshCookieConfig can with echo for middleware.JWTWithConfig(vmod.AccessConfig) to handling access controll
//The token is reachable with c.Get("token")
func RefreshCookieMiddleware() echo.MiddlewareFunc {
return middleware.JWTWithConfig(
middleware.JWTConfig{
Claims: &RefreshToken{},
ContextKey: "token",
TokenLookup: "cookie:refresh_token",
SigningKey: []byte(jwtSecret),
})
}