Skip to content

Commit

Permalink
fix: check auth
Browse files Browse the repository at this point in the history
  • Loading branch information
nhedger committed Nov 14, 2023
1 parent 32e2b0b commit 29963a4
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 37 deletions.
15 changes: 10 additions & 5 deletions src/runtime/middlewares/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,16 @@ import { useSanctum } from "../composables/sanctum";
*
* The auth middleware is used to protect routes that require authentication.
*/
export const auth = defineNuxtRouteMiddleware(async (to, from) => {
export const auth = defineNuxtRouteMiddleware(async () => {
const { authenticated, check } = useSanctum();
const config = useRuntimeConfig().public.sanctum;

// If the user is not authenticated, redirect to the unauthenticated page.
if (!useSanctum().authenticated.value) {
return config.middlewares.auth.redirectsTo;

// Because we know the last authenticated state, we can use it to determine
// if we should make a request to the server to check if the user is still
// authenticated.
if (authenticated.value || (await check())) {
return;
}

return config.middlewares.auth.redirectsTo;
});
30 changes: 0 additions & 30 deletions src/runtime/middlewares/check.ts

This file was deleted.

2 changes: 0 additions & 2 deletions src/runtime/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import { addRouteMiddleware, defineNuxtPlugin, useRuntimeConfig } from "#app";
import { auth } from "./middlewares/auth";
import { check } from "./middlewares/check";
import { guest } from "./middlewares/guest";

export default defineNuxtPlugin(async () => {
const config = useRuntimeConfig().public.sanctum;

// Register middlewares
addRouteMiddleware(config.middlewares.check.name, check, { global: true });
addRouteMiddleware(config.middlewares.auth.name, auth);
addRouteMiddleware(config.middlewares.guest.name, guest);
});

0 comments on commit 29963a4

Please sign in to comment.