Skip to content

Commit

Permalink
feat: added middleware for mobile routes
Browse files Browse the repository at this point in the history
  • Loading branch information
rishavvajpayee committed Sep 24, 2024
1 parent cd90055 commit a60ba45
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 53 deletions.
16 changes: 4 additions & 12 deletions src/app/api/mobile/courses/route.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,13 @@

import db from '@/db';
import { NextResponse, NextRequest } from 'next/server';
// import bcrypt from 'bcrypt';

export async function GET(req: NextRequest) {
try {
console.log(req);
const user = {
id: '1',
appxUserId: '100',
disableDrm: false,
email: '[email protected]',
password: 'fjklasjf',
token: 'jfskd.fjskdf.fsdf',
};

console.log(user);
const user = JSON.parse(req.headers.get('g') || '');
if (!user) {
return NextResponse.json({ message: 'User Not Found' }, { status: 400 });
}
const userCourses = await db.course.findMany({
where: {
purchasedBy: {
Expand Down
61 changes: 58 additions & 3 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,55 @@
import { withAuth } from 'next-auth/middleware';
import { NextResponse } from 'next/server';
import { NextRequestWithAuth, withAuth } from 'next-auth/middleware';
import { NextResponse, NextRequest } from 'next/server';
import { jwtVerify, importJWK, JWTPayload } from 'jose';

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

interface RequestWithUser extends NextRequest {
user?: any;
}

export const verifyJWT = async (token: string): Promise<JWTPayload | null> => {
const secret = process.env.JWT_SECRET || '';

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

return payload;
} catch (error) {
console.error('Invalid token:', error);
return null;
}
};

export const withMobileAuth = async (req: RequestWithUser) => {
if (req.headers.get('Auth-Key')) {
return NextResponse.next();
}
const token = req.headers.get('Authorization'); // Extract the token
console.log('token', token);
if (!token) {
return NextResponse.json({ message: 'Unauthorized' }, { status: 403 });
}
const payload = await verifyJWT(token);
if (!payload) {
return NextResponse.json({ message: 'Unauthorized' }, { status: 403 });
}
const newHeaders = new Headers(req.headers);

/**
* Add a global object 'g'
* it holds the request claims and other keys
* easily pass around this key as request context
*/
newHeaders.set('g', JSON.stringify(payload));
return NextResponse.next({
request: {
headers: newHeaders,
},
});
};

export default withAuth(async (req) => {
Expand All @@ -20,3 +67,11 @@ export default withAuth(async (req) => {
return NextResponse.redirect(new URL('/invalidsession', req.url));
}
});

export function middleware(req: NextRequestWithAuth) {
const { pathname } = req.nextUrl;
if (pathname.startsWith('/api/mobile')) {
return withMobileAuth(req);
}
return withAuth(req);
}
38 changes: 0 additions & 38 deletions src/withMobileAuth.ts

This file was deleted.

0 comments on commit a60ba45

Please sign in to comment.