Skip to content

Instantly share code, notes, and snippets.

@epicbytes
Last active January 20, 2025 20:45
Show Gist options
  • Select an option

  • Save epicbytes/7628f9a341fc31985475157c2b285846 to your computer and use it in GitHub Desktop.

Select an option

Save epicbytes/7628f9a341fc31985475157c2b285846 to your computer and use it in GitHub Desktop.
NextJS Authorization Files
/* /commons/src/jwt.ts */
export type TokenGeneric = {
exp: number;
id: number;
role: string;
};
export function parseJwt(token: string): TokenGeneric | null {
try {
return JSON.parse(atob(token.split(".")[1]));
} catch (e) {
return null;
}
}
export function isTokenValid(token: string, role: string): boolean {
if (!token) return false;
const nowUnix = (+new Date() / 1e3) | 0;
const decodedToken = parseJwt(token);
if (decodedToken === null) return false;
if (decodedToken.role !== role) return false;
return decodedToken.exp > nowUnix;
}
/* /pages/api/login.ts */
import { NextApiRequest, NextApiResponse } from "next";
import { CustomApi } from "@/services";
import { parseJwt } from "commons/src/jwt";
const handlerLogin = async (req: NextApiRequest, res: NextApiResponse) => {
const nowUnix = (+new Date() / 1e3) | 0;
const CustomerApi = new CustomApi();
try {
const { access_token, refresh_token } =
await CustomerApi.customerSignInRequestWrapper({
body: JSON.parse(req.body),
});
const access_token_decoded: { exp: number } = parseJwt(access_token);
const refresh_token_decoded: { exp: number } = parseJwt(refresh_token);
res.setHeader("Set-Cookie", [
`token=${access_token}; Max-Age=${
access_token_decoded.exp - nowUnix
}; Path=/`,
`refresh_token=${refresh_token}; Max-Age=${
refresh_token_decoded.exp - nowUnix
}; Path=/; HttpOnly=true`,
]);
res.send({ refresh_token });
} catch (e) {
res.status(401);
res.send({ message: "error_while_login" });
}
};
export default handlerLogin;
/* /pages/lk/logout.tsx */
import { GetServerSideProps } from "next";
const LogoutPage = () => {
return <></>;
};
export const getServerSideProps: GetServerSideProps = async (context) => {
context.res.setHeader("Set-Cookie", [
`token=deleted; Max-Age=0; Path=/`,
`refresh_token=deleted; Max-Age=0; Path=/`,
]);
return {
redirect: { permanent: false, destination: "/" },
props: { initialState: {} },
};
};
export default LogoutPage;
import { NextRequest, NextResponse } from "next/server";
import { isTokenValid } from "commons/src/jwt";
export const config = {
matcher: "/lk/:path*",
};
export function middleware(req: NextRequest) {
const url = req.nextUrl.clone();
url.pathname = "/";
return isTokenValid(req.cookies?.get("token"), "customer")
? NextResponse.next()
: NextResponse.redirect(url);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment