Debian Codegraph @

store_legacy.go

raw
1 //go:build !go1.11
2 // +build !go1.11
3
4 // file for compatibility with go versions prior to 1.11
5
6 package csrf
7
8 import (
9 "net/http"
10 "time"
11
12 "github.com/gorilla/securecookie"
13 )
14
15 // store represents the session storage used for CSRF tokens.
16 type store interface {
17 // Get returns the real CSRF token from the store.
18 Get(*http.Request) ([]byte, error)
19 // Save stores the real CSRF token in the store and writes a
20 // cookie to the http.ResponseWriter.
21 // For non-cookie stores, the cookie should contain a unique (256 bit) ID
22 // or key that references the token in the backend store.
23 // csrf.GenerateRandomBytes is a helper function for generating secure IDs.
24 Save(token []byte, w http.ResponseWriter) error
25 }
26
27 // cookieStore is a signed cookie session store for CSRF tokens.
28 type cookieStore struct {
29 name string
30 maxAge int
31 secure bool
32 httpOnly bool
33 path string
34 domain string
35 sc *securecookie.SecureCookie
36 sameSite SameSiteMode
37 }
38
39 // Get retrieves a CSRF token from the session cookie. It returns an empty token
40 // if decoding fails (e.g. HMAC validation fails or the named cookie doesn't exist).
41 func (cs *cookieStore) Get(r *http.Request) ([]byte, error) {
42 // Retrieve the cookie from the request
43 cookie, err := r.Cookie(cs.name)
44 if err != nil {
45 return nil, err
46 }
47
48 token := make([]byte, tokenLength)
49 // Decode the HMAC authenticated cookie.
50 err = cs.sc.Decode(cs.name, cookie.Value, &token)
51 if err != nil {
52 return nil, err
53 }
54
55 return token, nil
56 }
57
58 // Save stores the CSRF token in the session cookie.
59 func (cs *cookieStore) Save(token []byte, w http.ResponseWriter) error {
60 // Generate an encoded cookie value with the CSRF token.
61 encoded, err := cs.sc.Encode(cs.name, token)
62 if err != nil {
63 return err
64 }
65
66 cookie := &http.Cookie{
67 Name: cs.name,
68 Value: encoded,
69 MaxAge: cs.maxAge,
70 HttpOnly: cs.httpOnly,
71 Secure: cs.secure,
72 Path: cs.path,
73 Domain: cs.domain,
74 }
75
76 // Set the Expires field on the cookie based on the MaxAge
77 // If MaxAge <= 0, we don't set the Expires attribute, making the cookie
78 // session-only.
79 if cs.maxAge > 0 {
80 cookie.Expires = time.Now().Add(
81 time.Duration(cs.maxAge) * time.Second)
82 }
83
84 // Write the authenticated cookie to the response.
85 http.SetCookie(w, cookie)
86
87 return nil
88 }