Skip to content
This repository has been archived by the owner on Aug 20, 2023. It is now read-only.

Commit

Permalink
feat: add getCookie function
Browse files Browse the repository at this point in the history
  • Loading branch information
InkoHX committed Jun 29, 2023
1 parent 6d498e9 commit 30c8c50
Showing 1 changed file with 37 additions and 3 deletions.
40 changes: 37 additions & 3 deletions src/functions.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Context as HonoContext } from 'hono'
import { setCookie } from 'hono/cookie'
import { setCookie, getCookie as _getCookie } from 'hono/cookie'
import type { CookieOptions } from 'hono/utils/cookie'
import { sign } from './signature'
import { sign, verify } from './signature'
import { encodeBase64Url } from './utils/base64url'
import { getContextKey } from './utils/context'
import { concatCookieValue } from './utils/cookie'
import { concatCookieValue, splitCookieValue } from './utils/cookie'

/**
* Function to set a signed cookie in the Set-Cookie header
Expand Down Expand Up @@ -48,10 +48,44 @@ export const setCookieWithSignature =
* @param context - The Hono context object.
* @param name - The name of the cookie to retrieve.
* @returns The verified cookie value, or undefined if the cookie is not found or is invalid.
*
* **WARN: Use this function only when using the `cookieSignature` middleware.**
*/
export const getVerifiedCookie = (context: HonoContext, name: string) => {
const value = context.get(getContextKey(name))

if (typeof value !== 'string') return
else return value
}

/**
* Retrieves and verifies a cookie value
*
* @param context - The Hono context object.
* @param key - The key used for signing the cookie.
* @param name - The name of the cookie to retrieve.
* @returns The verified cookie value, or undefined if the cookie is not found or is invalid.
*
* **If you are using the `cookieSignature` middleware, it is recommended to use `getVerifiedCookie`.**
*/
export const getCookie = async (
context: HonoContext,
key: CryptoKey,
name: string
) => {
const rawCookieValue = _getCookie(context, name)
if (!rawCookieValue) return

const { signature, value } = splitCookieValue(rawCookieValue)
if (!signature || !value) return

const encoder = new TextEncoder()
const verified = await verify(
key,
encoder.encode(signature),
encoder.encode(value)
)
if (!verified) return

return value
}

0 comments on commit 30c8c50

Please sign in to comment.