hensei-web/utils/localId.tsx
Justin Edmund ab4b563754
Implement rudimentary Bahamut Mode (#381)
Bahamut Mode lets me make sure people aren't doing naughty things behind
closed doors.
2023-09-09 02:29:30 -07:00

45 lines
1.1 KiB
TypeScript

import { retrieveCookie } from './userToken'
import { v4 as uuidv4 } from 'uuid'
import { setCookie } from 'cookies-next'
import type { NextApiRequest, NextApiResponse } from 'next'
export const createLocalId = (
req: NextApiRequest | undefined = undefined,
res: NextApiResponse | undefined = undefined
) => {
// If there is no account entry in cookies, create a UUID and store it
if (!retrieveCookie('account', req, res)) {
const uuid = uuidv4()
const expiresAt = new Date()
expiresAt.setDate(expiresAt.getDate() + 60)
const cookieObj = {
userId: uuid,
username: undefined,
role: 1,
token: undefined,
}
const options = req && res ? { req, res } : {}
setCookie('account', cookieObj, {
path: '/',
expires: expiresAt,
...options,
})
return uuid
}
}
export const getLocalId = () => {
const cookie = retrieveCookie('account')
if (cookie) {
const parsed = JSON.parse(cookie as string)
if (parsed && !parsed.token)
// Return the existing account cookie
return parsed.userId
} else {
// Create a new account cookie and return
return createLocalId()
}
}