-
Notifications
You must be signed in to change notification settings - Fork 5
/
cookie.go
62 lines (56 loc) · 1.76 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
package api
import (
"net/http"
"os"
"time"
"github.com/gorilla/securecookie"
"github.com/joho/godotenv"
)
const (
// CookieName is the name of the cookie where we store the user's JWT token.
CookieName = "skynet-jwt"
// envCookieDomain holds the name of the environment variable for the
// domain name of the portal
envCookieDomain = "COOKIE_DOMAIN"
// envCookieHashKey holds the name of the env var which holds the key we use
// to hash cookies.
envCookieHashKey = "COOKIE_HASH_KEY"
// envCookieEncKey holds the name of the env var which holds the key we use
// to encrypt cookies.
envCookieEncKey = "COOKIE_ENC_KEY"
)
var (
secureCookie = func() *securecookie.SecureCookie {
_ = godotenv.Load()
// These keys need to be *exactly* 16 or 32 bytes long.
var hashKey = []byte(os.Getenv(envCookieHashKey))[:32]
var blockKey = []byte(os.Getenv(envCookieEncKey))[:32]
return securecookie.New(hashKey, blockKey)
}()
)
// writeCookie is a helper function that writes the given JWT token as a
// secure cookie.
// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
func writeCookie(w http.ResponseWriter, token string, exp int64) error {
encodedValue, err := secureCookie.Encode(CookieName, token)
if err != nil {
return err
}
// Allow this cookie to be used on all subdomains of this domain.
domain, ok := os.LookupEnv(envCookieDomain)
if !ok {
domain = "127.0.0.1"
}
cookie := &http.Cookie{
Name: CookieName,
Value: encodedValue,
HttpOnly: true,
Path: "/",
Domain: domain,
MaxAge: int(exp - time.Now().UTC().Unix()),
Secure: true, // do not send over insecure channels, e.g. HTTP
SameSite: 1, // https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00
}
http.SetCookie(w, cookie)
return nil
}