Skip to content

Commit

Permalink
add state cookie methods
Browse files Browse the repository at this point in the history
  • Loading branch information
alvinsj committed Jun 8, 2024
1 parent 4f121a4 commit 88d1b49
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/lib/__tests__/stateCookie.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { describe, test, expect } from "vitest"
import { getStateCookie, setStateCookie } from "../stateCookie"

describe("setStateCookie", () => {
test("throws errors on empty string", () => {
expect(() => setStateCookie(""))
.toThrow("state value is required")
})
test("sets cookie with prefix app.txs", () => {
const state = setStateCookie("code_verifier_secret")
expect(document.cookie)
.toMatch(`app.txs.${state}=code_verifier_secret`)
})
test("sets cookie with latest value", () => {
const state = setStateCookie("code_verifier_secret")
expect(document.cookie)
.toMatch(`app.txs.${state}=code_verifier_secret`)
})
test("returns state", () => {
const state = setStateCookie("code_verifier_secret")
expect(state).toMatch(/[\w-]+/)
})
})

describe("getStateCookie", () => {
test("gets cookie", () => {
const state = crypto.randomUUID()
const random = Math.random().toString(36).substring(7)
document.cookie = `app.txs.${state}=${random}`
expect(getStateCookie(state)).toBe(random)
})

test("gets none", () => {
expect(getStateCookie('nothere')).toBeUndefined()
})
})
15 changes: 15 additions & 0 deletions src/lib/stateCookie.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@

import { saveCookie, getCookie } from './cookie'

export const setStateCookie = (value: string) => {
if (!value) throw new Error('state value is required')

const state = crypto.randomUUID()
saveCookie(`app.txs.${state}`, value, 30)

return state
}

export const getStateCookie = (state: string) => {
return getCookie(`app.txs.${state}`)
}

0 comments on commit 88d1b49

Please sign in to comment.