Skip to content

Commit 9fa34d5

Browse files
SSRerror_solved
1 parent 76061ba commit 9fa34d5

File tree

6 files changed

+82
-39
lines changed

6 files changed

+82
-39
lines changed

app/api/login/route.ts

+37-22
Original file line numberDiff line numberDiff line change
@@ -2,32 +2,47 @@ import { NextResponse } from 'next/server'
22
import { prisma } from '@/lib/prisma'
33
import { cookies } from 'next/headers'
44

5-
6-
75
export async function POST(request: Request) {
8-
const { username, password } = await request.json()
9-
console.log('Received username:', username)
10-
console.log('Received password:', password)
11-
6+
try {
7+
// Parsing the request body
8+
let username: string, password: string;
129
try {
13-
const user = await prisma.user.findUnique({ where: { username } })
14-
if (!user) {
15-
console.log('User not found')
16-
return NextResponse.json({ error: 'Invalid credentials' }, { status: 400 })
17-
}
10+
const body = await request.json();
11+
username = body.username;
12+
password = body.password;
13+
console.log('Received username:', username);
14+
console.log('Received password:', password);
15+
} catch (err) {
16+
console.error('Invalid JSON in request:', err);
17+
return NextResponse.json({ error: 'Invalid request format' }, { status: 400 });
18+
}
19+
20+
// Fetching user from database
21+
const user = await prisma.user.findUnique({ where: { username } });
22+
if (!user) {
23+
console.error('User not found for username:', username);
24+
return NextResponse.json({ error: 'Invalid credentials' }, { status: 400 });
25+
}
1826

27+
// Validating password (without bcrypt)
1928
if (user.password !== password) {
20-
console.log('Invalid password')
21-
return NextResponse.json({ error: 'Invalid credentials' }, { status: 400 })
29+
console.error('Invalid password for user:', username);
30+
return NextResponse.json({ error: 'Invalid credentials' }, { status: 400 });
2231
}
23-
24-
cookies().set('userId', user.id, { httpOnly: true, secure: process.env.NODE_ENV === 'production' })
25-
cookies().set('username', user.username, { httpOnly: true, secure: process.env.NODE_ENV === 'production' })
26-
27-
return NextResponse.json({ message: 'Login successful' })
28-
} catch (error) {
29-
console.error('Login error:', error)
30-
return NextResponse.json({ error: 'An error occurred during login' }, { status: 500 })
32+
33+
// Setting cookies with 1-week expiry
34+
try {
35+
cookies().set('userId', user.id, { httpOnly: true, secure: process.env.NODE_ENV === 'production', maxAge: 60 * 60 * 24 * 7 }); // 1 week expiry
36+
cookies().set('username', user.username, { httpOnly: true, secure: process.env.NODE_ENV === 'production', maxAge: 60 * 60 * 24 * 7 });
37+
} catch (cookieError) {
38+
console.error('Error setting cookies:', cookieError);
39+
return NextResponse.json({ error: 'Error setting cookies' }, { status: 500 });
3140
}
41+
42+
return NextResponse.json({ message: 'Login successful' });
43+
} catch (error) {
44+
console.error('Login error:', error);
45+
return NextResponse.json({ error: 'An error occurred during login' }, { status: 500 });
3246
}
33-
47+
}
48+

components/dashboard.tsx

-3
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,6 @@ import { useToast } from "@/components/ui/toast"
1414
import { getUserData, getLeaderboardData, updateTopic } from '../app/dashboard/action'
1515
import { User, Topic, LeaderboardEntry} from '../app/dashboard/types'
1616

17-
18-
19-
2017
const RadialProgress = ({ value, size }: { value: number, size: number }) => {
2118
const data = [
2219
{ name: 'Progress', value: value },

lib/auth.ts

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { cookies } from 'next/headers';
2+
import { NextResponse } from 'next/server';
3+
4+
export function requireAuth() {
5+
// Get userId from cookies
6+
const userId = cookies().get('userId');
7+
8+
// If the user is not authenticated, throw an error
9+
if (!userId) {
10+
return NextResponse.json({ error: 'User not authenticated' }, { status: 401 });
11+
}
12+
13+
// Return the authenticated userId if necessary
14+
return userId;
15+
}

middleware.ts

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { NextResponse } from 'next/server';
2+
import type { NextRequest } from 'next/server';
3+
4+
// List of routes that don't require authentication (e.g., login, register, etc.)
5+
const publicRoutes = ['/login', '/register'];
6+
7+
export function middleware(request: NextRequest) {
8+
// Extract the userId from cookies
9+
const userId = request.cookies.get('userId')?.value;
10+
11+
// Check if the current path is public (e.g., login, register)
12+
if (publicRoutes.includes(request.nextUrl.pathname)) {
13+
// If the user is trying to access a public page, allow them
14+
return NextResponse.next();
15+
}
16+
17+
// If the user is trying to access a protected page without being authenticated
18+
if (!userId) {
19+
// Redirect the user to the login page
20+
return NextResponse.redirect(new URL('/login', request.url));
21+
}
22+
23+
// If authenticated, allow the request
24+
return NextResponse.next();
25+
}
26+
27+
// Enable middleware for all routes
28+
export const config = {
29+
matcher: '/((?!api|_next/static|_next/image|favicon.ico).*)', // Matches all routes except api, static files, and favicon
30+
};

package-lock.json

-12
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

-2
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,6 @@
2222
"@radix-ui/react-slot": "^1.1.0",
2323
"@radix-ui/react-tabs": "^1.1.0",
2424
"@radix-ui/react-toast": "^1.2.1",
25-
"@types/bcryptjs": "^2.4.6",
26-
"bcryptjs": "^2.4.3",
2725
"class-variance-authority": "^0.7.0",
2826
"clsx": "^2.1.1",
2927
"framer-motion": "^11.9.0",

0 commit comments

Comments
 (0)