Skip to content

Commit

Permalink
Refactor protectedRoutes and add authentication for protected API routes
Browse files Browse the repository at this point in the history
  • Loading branch information
Kevin Zuniga Cuellar committed Mar 21, 2024
1 parent 2d96786 commit ac56ed0
Showing 1 changed file with 33 additions and 2 deletions.
35 changes: 33 additions & 2 deletions src/middleware/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import { defineMiddleware } from "astro:middleware";
import { supabase } from "../lib/supabase";
import micromatch from "micromatch";

const protectedRoutes = ["/dashboard(|/)", "/api/guestbook(|/)"];
const protectedRoutes = ["/dashboard(|/)"];
const redirectRoutes = ["/signin(|/)", "/register(|/)"];
const proptectedAPIRoutes = ["/api/guestbook(|/)"];

export const onRequest = defineMiddleware(
async ({ locals, url, cookies, redirect }, next) => {
Expand Down Expand Up @@ -51,7 +52,37 @@ export const onRequest = defineMiddleware(
return redirect("/dashboard");
}
}


if (micromatch.isMatch(url.pathname, proptectedAPIRoutes)) {
const accessToken = cookies.get("sb-access-token");
const refreshToken = cookies.get("sb-refresh-token");

// Check for tokens
if (!accessToken || !refreshToken) {
return new Response(
JSON.stringify({
error: "Unauthorized",
}),
{ status: 401 },
);
}

// Verify the tokens
const { error } = await supabase.auth.setSession({
access_token: accessToken.value,
refresh_token: refreshToken.value,
});

if (error) {
return new Response(
JSON.stringify({
error: "Unauthorized",
}),
{ status: 401 },
);
}
}

return next();
},
);

0 comments on commit ac56ed0

Please sign in to comment.