Skip to content

Commit a7b89d9

Browse files
committed
Add basic middleware, prepare for API refactor
1 parent 5bfcfd6 commit a7b89d9

File tree

3 files changed

+47
-43
lines changed

3 files changed

+47
-43
lines changed

peerprep/api/gateway.ts

Lines changed: 7 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { SafeParseReturnType, SafeParseSuccess } from "zod";
1+
import { cookies } from "next/headers";
22
import {
33
Question,
44
StatusBody,
@@ -7,43 +7,16 @@ import {
77
SigninResponse,
88
} from "./structs";
99

10-
const questions: { [key: string]: Question } = {
11-
"0": {
12-
id: 0,
13-
difficulty: 2,
14-
title: "Two Sum",
15-
description:
16-
"Given an array of integers, return indices of the two numbers such that they add up to a specific target.",
17-
categories: ["Hash Table", "Array"],
18-
test_cases: {
19-
"[2, 7, 11, 15], 9": "[0, 1]",
20-
"[3, 2, 4], 6": "[1, 2]",
21-
"[3, 3], 6": "[0, 1]",
22-
},
23-
},
24-
"1": {
25-
id: 1,
26-
difficulty: 1,
27-
title: "Reverse Integer",
28-
description: "Given a 32-bit signed integer, reverse digits of an integer.",
29-
categories: ["Math"],
30-
test_cases: {
31-
"123": "321",
32-
"1": "1",
33-
"22": "22",
34-
},
35-
},
36-
};
10+
function generateJSONHeaders() {
11+
return {
12+
"Content-type": "application/json; charset=UTF-8",
13+
"Authorization": `Bearer ${cookies().get("session")}`
14+
}
15+
}
3716

3817
export async function fetchQuestion(
3918
questionId: string
4019
): Promise<Question | StatusBody> {
41-
// remove this when services are up
42-
if (process.env.DEV_ENV === "dev") {
43-
return questions[questionId] === undefined
44-
? { error: "Question not found", status: 404 }
45-
: questions[questionId];
46-
}
4720
try {
4821
const response = await fetch(
4922
`${process.env.NEXT_PUBLIC_QUESTION_SERVICE}/questions/solve/${questionId}`

peerprep/app/actions/server_actions.ts

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ import { getSessionLogin, postSignupUser } from '@/api/gateway';
33
// defines the server-sided login action.
44
import { SignupFormSchema, LoginFormSchema, FormState, isError } from '@/api/structs';
55
import { createSession } from '@/app/actions/session';
6-
import { cookies } from 'next/headers';
76
import { redirect } from 'next/navigation';
87

98
// credit - taken from Next.JS Auth tutorial
@@ -49,15 +48,8 @@ export async function login(state: FormState, formData: FormData) {
4948

5049
const json = await getSessionLogin(validatedFields.data);
5150
if (!isError(json)) {
52-
if (cookies().has('session')) {
53-
console.log(cookies().get('session'));
54-
console.log("Note a cookie already exists, overriding!");
55-
}
5651
await createSession(json.data.accessToken);
57-
58-
if (cookies().has('session')) {
59-
console.log(`New cookie: ${cookies().get('session')?.value}`);
60-
}
52+
redirect("/questions");
6153
} else {
6254
console.log(json.error);
6355
}

peerprep/middleware.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { cookies } from 'next/headers'
2+
import { NextResponse } from 'next/server'
3+
import type { NextRequest } from 'next/server'
4+
5+
function isNoSession(request: NextRequest): boolean {
6+
return request.nextUrl.pathname.startsWith('/auth') && cookies().has("session");
7+
}
8+
9+
function isSession(request: NextRequest): boolean {
10+
return !request.nextUrl.pathname.startsWith('/auth') && !cookies().has("session");
11+
}
12+
13+
export function middleware(request: NextRequest) {
14+
if (isNoSession(request)) {
15+
return NextResponse.redirect(new URL("/questions", request.url));
16+
}
17+
18+
if (isSession(request)) {
19+
return NextResponse.redirect(new URL("/auth/login", request.url));
20+
}
21+
}
22+
23+
// taken from Next.JS's Middleware tutorial
24+
export const config = {
25+
matcher: [
26+
/*
27+
* Match all request paths except for the ones starting with:
28+
* - api (API routes)
29+
* - _next/static (static files)
30+
* - _next/image (image optimization files)
31+
* - favicon.ico, sitemap.xml, robots.txt (metadata files)
32+
*/
33+
'/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)',
34+
// We also want to match all internal API routes from the browser
35+
// This allows us to inject the JWT token for client components, when
36+
// they make a request to the route.
37+
'/api/internal/:path*',
38+
],
39+
}

0 commit comments

Comments
 (0)