Skip to content

Commit

Permalink
Configures middleware to handle auth
Browse files Browse the repository at this point in the history
  • Loading branch information
wdevon99 committed Mar 3, 2024
1 parent ee67be5 commit 2bc5689
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 35 deletions.
36 changes: 18 additions & 18 deletions src/app/dashboard/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,24 @@ export default function Dashboard() {
getAllTodos();
}, [])

const getAllTodos = async () => {
setIsLoading(true);

try {
const response = await TodoService.getAllTodos();

// TODO :: Handle errors based on response status
const todos = await response.json();

setTodos(Array.isArray(todos) ? todos : []);

} catch (error) {
console.error(error);
} finally {
setIsLoading(false);
}
};

const createTodo = async () => {
setIsBusy(true);

Expand All @@ -47,25 +65,7 @@ export default function Dashboard() {
}
};

const getAllTodos = async () => {
setIsLoading(true);

try {
const response = await TodoService.getAllTodos();
const todos = await response.json();
setTodos(todos);

} catch (error) {
console.error(error);
} finally {
setIsLoading(false);
}
};

const deleteTodo = async (todoId: string) => {

console.log("todoId => ", todoId);

const response = await TodoService.deleteTodo(todoId);
const deletedTodoId = await response.text();
const filteredTodos = todos?.filter((t: any) => t._id !== deletedTodoId);
Expand Down
10 changes: 5 additions & 5 deletions src/components/molecules/AuthCard/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,23 +31,23 @@ function AuthCard() {

if (session) {
return (
<Card style={{ width: CARD_WIDTH, height: CARD_HEIGHT }} >
<Card style={{ width: CARD_WIDTH }} >
<div className={styles.container}>
<p className={styles.label}>You are signed in as <b>{session?.user?.name}</b>.</p>
<Button
type="primary"
className={styles.button}
onClick={() => router.push('/dashboard')}
block={true}
block
>
Go to Dashboard
</Button>
<Button
className={styles.button}
type="dashed"
onClick={() => signOut()}
block={true}
danger={true}
block
danger
>
Log out
</Button>
Expand All @@ -59,7 +59,7 @@ function AuthCard() {

if (isLoading) {
return (
<Card style={{ width: CARD_WIDTH, alignItems: 'center', justifyContent: 'center' }} >
<Card style={{ width: CARD_WIDTH }} >
<div className={styles.container}>
<SkeletonButton active={true} block={true} style={{ marginBottom: 10, marginTop: 10, height: 42 }} />
<SkeletonButton active={true} block={true} style={{ marginBottom: 10, height: 42 }} />
Expand Down
3 changes: 2 additions & 1 deletion src/components/molecules/AuthCard/styles.module.sass
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
.container
padding: 0 100px
padding: 0 120px
.button
margin-bottom: 10px
.label
margin-top: 0
margin-bottom: 12px
font-size: 14px
text-align: center
32 changes: 21 additions & 11 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,29 @@
import { NextRequest } from "next/server";
import { NextRequest, NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";

// Limit the middleware to paths starting with `/api/`
export const config = {
matcher: "/api/:function*",
};
const PROTECTED_API_ROUTES = ["/api/todo"];
const PROTECTED_ROUTES = ["/dashboard"];

export async function middleware(request: NextRequest) {
const token = await getToken({ req: request });
const isProtectedApiRoute = PROTECTED_API_ROUTES.some((route: string) => request.nextUrl?.pathname?.startsWith(route));
const isProtectedRoute = PROTECTED_ROUTES.some((route: string) => request.nextUrl?.pathname?.startsWith(route));

// TODO :: Token is availble here but need to handle auth for currect routes

const isAuthenticated = true; // TODO :: Implement Role based Auth
if (isProtectedApiRoute) {
if (!isAuthenticated(request)) {
return Response.json({ success: false, message: "Authentication failed" }, { status: 401 });
}
}

if (!isAuthenticated) {
return Response.json({ success: false, message: "Authentication failed" }, { status: 401 });
if (isProtectedRoute) {
if (!isAuthenticated(request)) {
return NextResponse.redirect(new URL("/", request.url));
}
}

return NextResponse.next();
}

const isAuthenticated = async (request: NextRequest) => {
const token = await getToken({ req: request });
return !!token && Date.now() <= token.exp * 1000;
};

0 comments on commit 2bc5689

Please sign in to comment.