Skip to content

Commit

Permalink
FEAT:single session/login
Browse files Browse the repository at this point in the history
  • Loading branch information
siinghd committed Feb 26, 2024
1 parent 062dace commit 89230ce
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 2 deletions.
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,5 @@ BOT_TOKEN = "123"
GUILD_ID = "123"
LOCAL_CMS_PROVIDER = true
CACHE_EXPIRE_S = 10
JWT_SECRET_TOKEN="JWT_SECRET_TOKEN"

15 changes: 15 additions & 0 deletions src/app/api/user/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { type NextRequest, NextResponse } from 'next/server';
import db from '@/db';

export async function GET(req: NextRequest) {
const url = new URL(req.url);
const token = url.searchParams.get('token');
const user = await db.user.findFirst({
where: {
token,
},
});
return NextResponse.json({
user,
});
}
16 changes: 16 additions & 0 deletions src/app/invalidsession/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
'use client';

import { signOut } from 'next-auth/react';
import React, { useEffect } from 'react';

const page = () => {
useEffect(() => {
signOut({
callbackUrl: '/signin',
});
}, []);

return <div>page</div>;
};

export default page;
5 changes: 3 additions & 2 deletions src/lib/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,16 +129,17 @@ export const authOptions = {
secret: process.env.NEXTAUTH_SECRET || 'secr3t',
callbacks: {
session: async ({ session, token }: any) => {
console.log('session', session, token);
if (session?.user) {
session.user.id = token.uid;
session.user.authToken = token;
session.user.jwtToken = token.jwtToken;
}

return session;
},
jwt: async ({ user, token }: any) => {
if (user) {
token.uid = user.id;
token.jwtToken = user.token;
}
return token;
},
Expand Down
21 changes: 21 additions & 0 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { withAuth } from 'next-auth/middleware';
import { NextResponse } from 'next/server';

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

export default withAuth(async (req) => {
const token = req.nextauth.token;
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}`,
);

const json = await user.json();
if (!json.user) {
return NextResponse.redirect(new URL('/invalidsession', req.url));
}
});

0 comments on commit 89230ce

Please sign in to comment.