cookie#serialize TypeScript Examples

The following examples show how to use cookie#serialize. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: get-cart-cookie.ts    From storefront-data-hooks with MIT License 7 votes vote down vote up
export default function getCartCookie(
  name: string,
  cartId?: string,
  maxAge?: number
) {
  const options: CookieSerializeOptions =
    cartId && maxAge
      ? {
          maxAge,
          expires: new Date(Date.now() + maxAge * 1000),
          secure: process.env.NODE_ENV === 'production',
          path: '/',
          sameSite: 'lax',
        }
      : { maxAge: -1, path: '/' } // Removes the cookie

  return serialize(name, cartId || '', options)
}
Example #2
Source File: login.ts    From test with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
login = async (req, res, next) => {
  const { adminApi: kratos }: { adminApi: AdminApi } = req.kratos
  const { flow }: { flow: string } = req.query

  flowIdGuard(flow, res, 'login')

  kratos
    .getSelfServiceLoginFlow(flow)
    .then(({ status, data }) => {
      if (status !== 200) Promise.reject(flow)
      const csrfToken = data.methods.password.config.fields
        .filter(field => field.name === 'csrf_toke')[0]
        .value.toString()
      res.setHeader('Set-Cookie', serialize('csrf_token', csrfToken), {
        expires: new Date(Date.now() + 10000),
      })
      next()
    })
    .catch(() => null)
}
Example #3
Source File: registration.ts    From test with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
registration = async (req, res, next) => {
  const { adminApi: kratos }: { adminApi: AdminApi } = req.kratos
  const { flow }: { flow: string } = req.query

  flowIdGuard(flow, res, 'registration')

  kratos
    .getSelfServiceRegistrationFlow(flow)
    .then(({ status, data }) => {
      if (status !== 200) Promise.reject(flow)
      const csrfToken = data.methods.password.config.fields
        .filter(field => field.name === 'csrf_token')[0]
        .value.toString()
      res.setHeader('Set-Cookie', serialize('csrf_token', csrfToken), {
        expires: new Date(Date.now() + 10000),
      })
      next()
    })
    .catch(() => null)
}
Example #4
Source File: settings.ts    From test with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
settings = async (req, res, next) => {
  const { adminApi: kratos }: { adminApi: AdminApi } = req.kratos
  const { flow }: { flow: string } = req.query

  flowIdGuard(flow, res, 'settings')

  kratos
    .getSelfServiceSettingsFlow(flow)
    .then(({ status, data }) => {
      if (status !== 200) Promise.reject(flow)
      const csrfToken = data.methods.password.config.fields
        .filter(field => field.name === 'csrf_token')[0]
        .value.toString()
      res.setHeader('Set-Cookie', serialize('csrf_token', csrfToken), {
        expires: new Date(Date.now() + 10000),
      })
      next()
    })
    .catch(() => null)
}
Example #5
Source File: logout.ts    From storefront-data-hooks with MIT License 6 votes vote down vote up
logoutHandler: LogoutHandlers['logout'] = async ({
  req: request,
  res,
  body: { redirectTo },
  config,
}) => {
  const { host } = request.headers
  // Remove the cookie
  res.setHeader(
    'Set-Cookie',
    serialize(config.customerCookie, '', { maxAge: -1, path: '/', domain: host?.includes(':') ? host?.slice(0, host.indexOf(':')) : host })
  )

  // Only allow redirects to a relative URL
  if (redirectTo?.startsWith('/')) {
    res.redirect(redirectTo)
  } else {
    res.status(200).json({ data: null })
  }
}
Example #6
Source File: passport.ts    From hakka with MIT License 6 votes vote down vote up
export async function handleSuccessfulLogin(
  req: NextApiRequest,
  res: NextApiResponse,
) {
  const user = (req as $TsFixMe).user as { id: number }
  const authToken = await createSecureToken({
    userId: user.id,
  })
  const maxAge = 60 * 60 * 24 * 90 // 3 month
  const authCookie = serialize(AUTH_COOKIE_NAME, authToken, {
    path: '/',
    httpOnly: true,
    sameSite: 'lax',
    maxAge,
    domain: process.env.NODE_ENV === 'production' ? '.hakka.dev' : undefined,
  })
  res.setHeader('Set-Cookie', [authCookie])
  res.redirect('/')
}
Example #7
Source File: logout.tsx    From hakka with MIT License 6 votes vote down vote up
handler: NextApiHandler = (req, res) => {
  const authCookie = serialize(AUTH_COOKIE_NAME, '', {
    path: '/',
    httpOnly: true,
    sameSite: 'lax',
    maxAge: 0,
  })
  res.setHeader('Set-Cookie', [authCookie])
  res.redirect('/login')
}
Example #8
Source File: cookie.ts    From farrow with MIT License 6 votes vote down vote up
set = (name: string, value: string, options?: CookieSerializeOptions, res?: ServerResponse) => {
  const opts: CookieSerializeOptions = { ...options }
  const val = typeof value === 'object' ? `j:${JSON.stringify(value)}` : String(value)

  if (typeof opts.maxAge === 'number') {
    opts.expires = new Date(Date.now() + opts.maxAge)
    opts.maxAge /= 1000
  }

  if (!opts.path) {
    opts.path = '/'
  }

  if (!res) {
    return JSCookie.set(name, value, {
      ...opts,
      sameSite: getSameSite(opts),
    })
  }

  res.setHeader('Set-Cookie', serialize(name, String(val), opts))
}
Example #9
Source File: logout.ts    From core with GNU Affero General Public License v3.0 6 votes vote down vote up
Logout = RequestHandler().get(async (req, res) => {
	res.setHeader('Cache-control', 'no-cache')
	res.setHeader(
		'set-cookie',
		serialize('token', '', {
			maxAge: -1,
			path: '/',
		})
	)
	res.redirect(301, '/')
})
Example #10
Source File: Csrf.ts    From core with GNU Affero General Public License v3.0 6 votes vote down vote up
getToken = (req: IncomingMessage, res: ServerResponse) => {
	const parsed = parse(req.headers.cookie || '')
	let key: string = parsed[csrfKey]
	if (!key || !tokenVerify(key)) {
		key = tokenCreate()
		res.setHeader(
			'set-cookie',
			serialize(csrfKey, key, {
				httpOnly: true,
				sameSite: 'lax',
				path: '/'
			})
		)
	}

	return key
}
Example #11
Source File: Cookie.ts    From ZenTS with MIT License 6 votes vote down vote up
public serialize(): string {
    const cookies = []

    for (const [key, cookie] of this.data) {
      if (!this.modifiedKeys.has(key)) {
        continue
      }

      const options: CookieOptions & {
        expires?: Date
      } = cookie.options

      if (typeof cookie.options.expire === 'number') {
        options.expires = dayjs().add(cookie.options.expire, 'millisecond').toDate()
        delete cookie.options.expire
      } else if (typeof cookie.options.expire === 'string') {
        options.expires = dayjs().add(ms(cookie.options.expire), 'millisecond').toDate()
        delete cookie.options.expire
      }

      try {
        cookies.push(serialize(key, JSON.stringify(cookie.value), options))
      } catch (e) {
        // silent
      }
    }

    return cookies.length ? cookies.join('; ') : ''
  }
Example #12
Source File: logout.ts    From nextjs-bigcommerce-starter with MIT License 6 votes vote down vote up
logoutHandler: LogoutHandlers['logout'] = async ({
  res,
  body: { redirectTo },
  config,
}) => {
  // Remove the cookie
  res.setHeader(
    'Set-Cookie',
    serialize(config.customerCookie, '', { maxAge: -1, path: '/' })
  )

  // Only allow redirects to a relative URL
  if (redirectTo?.startsWith('/')) {
    res.redirect(redirectTo)
  } else {
    res.status(200).json({ data: null })
  }
}
Example #13
Source File: setCookie.ts    From next-password-protect with MIT License 6 votes vote down vote up
setCookie = (
  res: Response,
  name: string,
  value: string,
  options,
) => {
  if ('maxAge' in options) {
    options.expires = new Date(Date.now() + options.maxAge);
    options.maxAge /= 1000;
  }

  res.setHeader('Set-Cookie', serialize(name, value, options));
}
Example #14
Source File: callback.ts    From core with GNU Affero General Public License v3.0 5 votes vote down vote up
Callback = RequestHandler().get(async (req: ApiRequest, res) => {
	const validate = await OauthCallbackSchema.validate(req.query)
		.then(r => r)
		.catch(e => {
			ResponseWrapper(res, { code: 400, errors: e.errors })
			return null
		})

	if (!validate) return

	res.statusCode = 200
	const token: DiscordTokenInfo = await fetch(DiscordEnpoints.Token, {
		method: 'POST',
		body: formData({
			client_id: process.env.DISCORD_CLIENT_ID,
			redirect_uri: process.env.KOREANBOTS_URL + '/api/auth/discord/callback',
			client_secret: process.env.DISCORD_CLIENT_SECRET,
			scope: process.env.DISCORD_SCOPE,
			grant_type: 'authorization_code',
			code: req.query.code,
		}),
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
		},
	}).then(r => r.json())
	if (token.error) return ResponseWrapper(res, { code: 400, errors: ['올바르지 않은 코드입니다.'] })

	const user: DiscordUserInfo = await fetch(DiscordEnpoints.Me, {
		method: 'GET',
		headers: {
			Authorization: `${token.token_type} ${token.access_token}`,
		},
	}).then(r => r.json())

	const userToken = await update.assignToken({
		id: user.id,
		access_token: token.access_token,
		expires_in: token.expires_in,
		refresh_token: token.refresh_token,
		email: user.email,
		username: user.username,
		discriminator: user.discriminator,
		verified: user.verified
	})

	if(userToken === 1) return res.redirect(301, 'https://docs.koreanbots.dev/bots/account/unverified')
	else if(userToken === 2) return res.redirect(301, 'https://docs.koreanbots.dev/bots/account/blocked')
	const info = verify(userToken)
	res.setHeader(
		'set-cookie',
		serialize('token', userToken, {
			expires: new Date(info.exp * 1000),
			secure: process.env.NODE_ENV === 'production',
			httpOnly: true,
			sameSite: 'lax',
			path: '/',
		})
	)
	res.redirect(301, '/callback/discord')
})