Skip to content

Commit

Permalink
IPK-77 Fixed middleware bug
Browse files Browse the repository at this point in the history
  • Loading branch information
Ben committed Jan 22, 2024
1 parent a383e5b commit 8f6e9bc
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 7 deletions.
7 changes: 5 additions & 2 deletions src/lib/actions.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"use server";

import { User } from "@/types";
import { cookies } from "next/headers";
import { ZodError, z } from "zod";

Expand Down Expand Up @@ -67,7 +68,7 @@ export async function refreshAccessToken() {
}
}

export async function getUser() {
export async function getUser(): Promise<User | null> {
try {
if (!cookies().get("accessToken")) {
throw new Error("Unauthorized");
Expand All @@ -85,10 +86,12 @@ export async function getUser() {
} else if (!response.ok) {
throw new Error("Network error");
}
return response.json();
return response.json() as Promise<User>;
});
return null;
} catch (error) {
console.error("There was a problem with the Fetch operation: ", error);
return null;
}
}

Expand Down
9 changes: 4 additions & 5 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { NextRequest, NextResponse } from "next/server";
import { getUser } from "./lib/actions";
import { User } from "./types";

export async function middleware(req: NextRequest) {
const user = await getUser();
if (user?.status !== 200 && user?.status != undefined) {
return NextResponse.redirect(new URL("/login", req.url));
}
const user = (await getUser()) as User;
if (user) return NextResponse.redirect(new URL("/login", req.url));
try {
if (req.nextUrl.pathname.startsWith("/admin") && user && "role" in user && user?.role !== "ADMIN") {
if (req.nextUrl.pathname.startsWith("/admin") && (user as User).role !== "ADMIN") {
return NextResponse.redirect(new URL("/unauthorized", req.url));
}

Expand Down
7 changes: 7 additions & 0 deletions src/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,10 @@ type RegisterInputs = {
password: string;
password_confirmation: string;
};

type User = {
id: number;
name: string;
email: string;
role: string;
};

0 comments on commit 8f6e9bc

Please sign in to comment.