diff options
| author | mo khan <mo@mokhan.ca> | 2025-04-15 17:46:34 -0600 |
|---|---|---|
| committer | mo khan <mo@mokhan.ca> | 2025-04-15 17:46:34 -0600 |
| commit | 655fb6c4cc180dfcbc13c1b85e0fbf47019caec0 (patch) | |
| tree | 50aaf25e5c70697ed2c5f8c539bd331fdf11d721 /pkg | |
| parent | 58276879a5505f8e37aa8f81d577b477b5497a53 (diff) | |
feat: create session cookie tied to access token
Diffstat (limited to 'pkg')
| -rw-r--r-- | pkg/web/cookie/cookie_test.go | 29 | ||||
| -rw-r--r-- | pkg/web/cookie/new.go | 22 | ||||
| -rw-r--r-- | pkg/web/cookie/reset.go | 36 |
3 files changed, 87 insertions, 0 deletions
diff --git a/pkg/web/cookie/cookie_test.go b/pkg/web/cookie/cookie_test.go new file mode 100644 index 0000000..17e3d88 --- /dev/null +++ b/pkg/web/cookie/cookie_test.go @@ -0,0 +1,29 @@ +package cookie + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/xlgmokha/x/pkg/env" +) + +func TestCookie(t *testing.T) { + t.Run("New", func(t *testing.T) { + t.Run("returns a cookie pinned to the HOST", func(t *testing.T) { + env.With(env.Vars{"HOST": "sparkle.example.com"}, func() { + cookie := New("name", "value", time.Now().Add(1*time.Minute)) + assert.Equal(t, cookie.Domain, "sparkle.example.com") + }) + }) + }) + + t.Run("Reset", func(t *testing.T) { + t.Run("returns an expired cookie", func(t *testing.T) { + result := Reset("example") + + assert.Equal(t, -1, result.MaxAge) + assert.Equal(t, time.Unix(0, 0), result.Expires) + }) + }) +} diff --git a/pkg/web/cookie/new.go b/pkg/web/cookie/new.go new file mode 100644 index 0000000..2809640 --- /dev/null +++ b/pkg/web/cookie/new.go @@ -0,0 +1,22 @@ +package cookie + +import ( + "net/http" + "time" + + "github.com/xlgmokha/x/pkg/env" +) + +func New(name, value string, expires time.Time) *http.Cookie { + return &http.Cookie{ + Name: name, + Value: value, // TODO:: digitally sign the value + Expires: expires, + MaxAge: int(time.Until(expires).Seconds()), + Path: "/", + // HttpOnly: true, + // Secure: true, + SameSite: http.SameSiteDefaultMode, + Domain: env.Fetch("HOST", "localhost"), + } +} diff --git a/pkg/web/cookie/reset.go b/pkg/web/cookie/reset.go new file mode 100644 index 0000000..1686343 --- /dev/null +++ b/pkg/web/cookie/reset.go @@ -0,0 +1,36 @@ +package cookie + +import ( + "net/http" + "time" + + "github.com/xlgmokha/x/pkg/env" +) + +func Reset(name string) *http.Cookie { + return Clear(&http.Cookie{ + Name: name, + }) +} + +func Expire(w http.ResponseWriter, r *http.Request, name string) { + cookie, err := r.Cookie(name) + if err != nil { + http.SetCookie(w, Reset(name)) + } else { + Clear(cookie) + http.SetCookie(w, cookie) + } +} + +func Clear(cookie *http.Cookie) *http.Cookie { + cookie.Value = "" + cookie.Expires = time.Unix(0, 0) + cookie.MaxAge = -1 + cookie.Path = "/" + cookie.HttpOnly = true + cookie.Secure = true + cookie.SameSite = http.SameSiteNoneMode + cookie.Domain = env.Fetch("HOST", "localhost") + return cookie +} |
