Skip to content
This repository has been archived by the owner on May 15, 2024. It is now read-only.

Commit

Permalink
feat(lib): add function 'isApiAuthenticated'
Browse files Browse the repository at this point in the history
  ## what
  - add function 'isApiAuthenticated' to ./src/lib/AuthSession/index.ts
  - function is used for checking if the user has authenticated

  ## how
  - to be used by API ONLY
  - check if a session cookie exists
  - if the session cookie exists, then the user is authenticated. return true
  - if the session cookie doesn't exists, then the user is NOT authenticated, return false

  ## why
  - this will be used as a check before processing any of the protected API routes

  ## where
  - ./src/lib/AuthSession/index.ts

  ## usage
  • Loading branch information
Clumsy-Coder committed Aug 20, 2023
1 parent 19d3903 commit 752284b
Showing 1 changed file with 32 additions and 1 deletion.
33 changes: 32 additions & 1 deletion src/lib/AuthSession/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@
// this file is a wrapper with defaults to be used in both API routes and `getServerSideProps` functions
import type { IronSessionOptions } from 'iron-session';
import { withIronSessionApiRoute, withIronSessionSsr } from 'iron-session/next';
import { GetServerSidePropsContext, GetServerSidePropsResult, NextApiHandler } from 'next';
import {
GetServerSidePropsContext,
GetServerSidePropsResult,
NextApiHandler,
NextApiRequest,
} from 'next';

/**
* Iron session data format to be used
Expand Down Expand Up @@ -73,6 +78,32 @@ export function withSessionRoute(handler: NextApiHandler) {
return withIronSessionApiRoute(handler, sessionOptions);
}

/**
* Check if the user is authenticated. This is meant to be used on a API endpoint
*
* @example
* ```typescript
* // /api/summary
*
* import { withSessionRoute, isApiAuthenticated } from '@lib/AuthSession
*
* const requestHandler = async (req: NextApiRequest, res: NextApiResponse) => {
* if(!isApiAuthenticated(req)) { res.status(401).send('Not Authorized') }
* }
*
* withSessionRoute(requestHandler)
* ```
*
* @param req - NextApiRequest
* @returns boolean - true if the user is authenticated. false otherwise
*/
export const isApiAuthenticated = (req: NextApiRequest) => {
const { authSession } = req.session;

// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
return authSession !== undefined;
};

/**
* Wrapping function used for getServerSideProps function on client side
*
Expand Down

0 comments on commit 752284b

Please sign in to comment.