cookie#parse TypeScript Examples

The following examples show how to use cookie#parse. 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: 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 #2
Source File: makeContextObject.ts    From next-page-tester with MIT License 6 votes vote down vote up
export function makeGetServerSidePropsContext({
  pageObject,
  options,
}: {
  pageObject: FoundPageObject;
  options: ExtendedOptions;
}): GetServerSidePropsContext<typeof pageObject.params> {
  const { req: reqMocker, res: resMocker, previousRoute } = options;
  const { params, query, resolvedUrl } = pageObject;
  const { req, res } = makeHttpObjects({
    pageObject,
    reqMocker,
    resMocker,
    refererRoute: previousRoute,
  });
  const { locale, locales, defaultLocale } = getLocales({ pageObject });

  // parsed "cookies" are only available in "getServerSideProps" data fetching method
  // https://github.com/vercel/next.js/pull/19724/files#diff-f1cccfe490138be7dae0d63562f6a2834af92d21130e0ff10d6de7ad30613f6bR132
  if (req.headers.cookie) {
    req.cookies = parse(req.headers.cookie);
  }

  // @TODO complete ctx object
  // https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering
  return {
    params: { ...params },
    query: { ...query },
    resolvedUrl,
    req,
    res,
    locale,
    locales,
    defaultLocale,
  };
}
Example #3
Source File: Cookie.ts    From ZenTS with MIT License 6 votes vote down vote up
constructor(headers: IncomingHttpHeaders) {
    const cookies = parse(headers.cookie ?? '')

    for (const [key, value] of Object.entries(cookies)) {
      try {
        const cookieValue = JSON.parse(value) as JsonValue

        this.data.set(key, {
          value: cookieValue,
          options: this.getCookieOptions(),
        })
      } catch (e) {
        // silent
      }
    }
  }
Example #4
Source File: cookie.ts    From farrow with MIT License 5 votes vote down vote up
get = (name: string, req?: IncomingMessage) => {
  if (!req) return JSCookie.get(name)
  const cookies = parse(req.headers.cookie || '') || {}
  return cookies[name]
}
Example #5
Source File: index.ts    From glenstack with MIT License 5 votes vote down vote up
extractJWTFromRequest = (request: Request): string | undefined => {
  if (request.headers.has("Cookie"))
    return parse(request.headers.get("Cookie")).CF_Authorization;
}
Example #6
Source File: Csrf.ts    From core with GNU Affero General Public License v3.0 5 votes vote down vote up
checkToken = (req: NextApiRequest, res: NextApiResponse, token: string): boolean => {
	const parsed = parse(req.headers.cookie || '')
	if (parsed[csrfKey] !== token || !tokenVerify(token)) {
		ResponseWrapper(res, { code: 400, message: 'CSRF 검증 에러 (페이지를 새로고침해주세요)' })
		return false
	} else return true
}
Example #7
Source File: cookies.test.tsx    From next-page-tester with MIT License 5 votes vote down vote up
describe('cookies', () => {
  describe.each([
    ['getServerSideProps', 'ssr', 'initialCookie=foo; sessionId=bar'],
    ['getInitialProps', 'gip', ''],
  ])('Page with %s', (dataFetchingType, directory, expectedCookie) => {
    it('Makes document.cookie available via ctx.req.headers.cookie', async () => {
      const parsedExpectedCookie = parse(expectedCookie);

      document.cookie = 'initialCookie=foo';
      const { render } = await getPage({
        nextRoot: path.join(__dirname, '__fixtures__', directory),
        route: '/login',
      });
      render();

      // Initial cookie available at first server side render
      screen.getByText('req.headers.cookies: "initialCookie=foo"');

      userEvent.click(screen.getByText('Login'));

      await screen.findByText('Authenticated content');
      await screen.findByText(`req.headers.cookies: "${expectedCookie}"`);
      if (dataFetchingType === 'getServerSideProps') {
        await screen.findByText(
          `req.cookies: "${JSON.stringify(parsedExpectedCookie)}"`
        );
      }

      userEvent.click(screen.getByText('To login'));

      await screen.findByText('Login');
      await screen.findByText(`req.headers.cookies: "${expectedCookie}"`);
      if (dataFetchingType === 'getServerSideProps') {
        await screen.findByText(
          `req.cookies: "${JSON.stringify(parsedExpectedCookie)}"`
        );
      }
    });
  });
});
Example #8
Source File: index.ts    From toucan-js with MIT License 5 votes vote down vote up
/**
   * Converts data from fetch event's Request to Sentry Request used in Sentry Event
   *
   * @param request FetchEvent Request
   * @returns Sentry Request
   */
  private toSentryRequest(request: FetchEvent['request']): Request {
    // Build cookies
    const cookieString = request.headers.get('cookie');
    let cookies: Record<string, string> | undefined = undefined;
    if (cookieString) {
      try {
        cookies = parse(cookieString);
      } catch (e) {}
    }

    const headers: Record<string, string> = {};

    // Build headers (omit cookie header, because we used it in the previous step)
    for (const [k, v] of (request.headers as any).entries()) {
      if (k !== 'cookie') {
        headers[k] = v;
      }
    }

    const rv: Request = {
      method: request.method,
      cookies,
      headers,
    };

    try {
      const url = new URL(request.url);
      rv.url = `${url.protocol}//${url.hostname}${url.pathname}`;
      rv.query_string = url.search;
    } catch (e) {
      // `new URL` failed, let's try to split URL the primitive way
      const qi = request.url.indexOf('?');
      if (qi < 0) {
        // no query string
        rv.url = request.url;
      } else {
        rv.url = request.url.substr(0, qi);
        rv.query_string = request.url.substr(qi + 1);
      }
    }
    return rv;
  }