Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/lib/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import prisma from '@/db';
import { NextAuthOptions } from 'next-auth';
import { Session } from 'next-auth';
import { JWT } from 'next-auth/jwt';
import { randomUUID } from 'crypto';

interface AppxSigninResponse {
data: {
Expand Down Expand Up @@ -42,9 +43,12 @@ const generateJWT = async (payload: JWTPayload) => {

const jwk = await importJWK({ k: secret, alg: 'HS256', kty: 'oct' });

const jwt = await new SignJWT(payload)
const jwt = await new SignJWT({
...payload,
iat: Math.floor(Date.now() / 1000),
jti: randomUUID(), // Adding a unique jti to ensure each token is unique. This helps generate a unique jwtToken on every login
})
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setExpirationTime('365d')
.sign(jwk);

Expand Down
20 changes: 13 additions & 7 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { NextRequestWithAuth, withAuth } from 'next-auth/middleware';
import { NextRequestWithAuth } from 'next-auth/middleware';
import { NextResponse, NextRequest } from 'next/server';
import { jwtVerify, importJWK, JWTPayload } from 'jose';
import { getToken } from 'next-auth/jwt';

export const config = {
matcher: ['/courses/:path*', '/api/mobile/:path*'],
matcher: ['/courses/:path*', '/api/mobile/:path*', '/home'],
};

interface RequestWithUser extends NextRequest {
Expand Down Expand Up @@ -55,12 +56,15 @@ export const withMobileAuth = async (req: RequestWithUser) => {
});
};

export default withAuth(async (req) => {
const withAuth = async (req: NextRequestWithAuth) => {
if (process.env.LOCAL_CMS_PROVIDER) return;
const token = req.nextauth.token;

const token = await getToken({ req });

if (!token) {
return NextResponse.redirect(new URL('/invalidsession', req.url));
}

const user = await fetch(
`${process.env.NEXT_PUBLIC_BASE_URL_LOCAL}/api/user?token=${token.jwtToken}`,
);
Expand All @@ -69,12 +73,14 @@ export default withAuth(async (req) => {
if (!json.user) {
return NextResponse.redirect(new URL('/invalidsession', req.url));
}
});
};

export function middleware(req: NextRequestWithAuth) {
export async function middleware(req: NextRequestWithAuth) {
const { pathname } = req.nextUrl;
if (pathname.startsWith('/api/mobile')) {
return withMobileAuth(req);
}
return withAuth(req);
return await withAuth(req);
}

export default withAuth;
Loading