Skip to content

Commit

Permalink
Remember profile after page change SSR
Browse files Browse the repository at this point in the history
  • Loading branch information
Natsume-197 committed Jul 29, 2024
1 parent b106b21 commit 98a617d
Show file tree
Hide file tree
Showing 7 changed files with 78 additions and 25 deletions.
12 changes: 10 additions & 2 deletions backend/middleware/authentication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,16 @@ export const isAuthJWT = (req: any, _: Response, next: NextFunction): void => {
};

function extractTokenFromCookie(req: any): string | null {
const authHeader: string | undefined = req.headers["cookie"];
return authHeader ? authHeader.split("=")[1] : null;
const cookies: string | undefined = req.headers["cookie"];
if (!cookies) return null;
const cookieArray = cookies.split(';');
for (const cookie of cookieArray) {
const [name, value] = cookie.split('=').map(c => c.trim());
if (name === 'access_token') {
return value;
}
}
return null;
}

function getJwtSecretKey(): string {
Expand Down
4 changes: 3 additions & 1 deletion frontend_v2/components/global/Header.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
<script setup>
const store = userStore()
const isAuth = computed(() => store.isLoggedIn)
</script>
<template>
<header class="bg-header-background border-b border-neutral-700 inset-x-0 top-0 z-10 w-full">
Expand Down Expand Up @@ -54,7 +56,7 @@ const isAuth = computed(() => store.isLoggedIn)
</a>
</div>
<GeneralLanguageSelector class="hidden lg:flex" />
<button v-if="!isAuth" data-hs-overlay="#hs-vertically-centered-scrollable-loginsignup-modal"
<button v-if="!isAuth || isAuth == null" data-hs-overlay="#hs-vertically-centered-scrollable-loginsignup-modal"
class=" py-2.5 px-5 inline-flex items-center gap-x-2 text-sm sm:text-sm font-semibold rounded-lg border hover:bg-black/5 hover:border-white/70 transition-all text-gray-800 disabled:opacity-50 disabled:pointer-events-none dark:text-white">
Log in
</button>
Expand Down
1 change: 1 addition & 0 deletions frontend_v2/layouts/default.vue
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<template>
<div class="flex dark bg-background flex-col min-h-screen">
<GeneralAuthModalLoginSignUp/>
<Header />
<main class="flex-grow">
<slot />
Expand Down
16 changes: 16 additions & 0 deletions frontend_v2/middleware/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// middleware/auth.ts
const store = userStore();
const isAuth = computed(() => store.isLoggedIn);
export default defineNuxtRouteMiddleware(async (to, from) => {
if (import.meta.server) return;
if (!isAuth.value) return;
try {
await store.getBasicInfo();
if (!isAuth.value) {
return navigateTo("/");
}
} catch (error) {
console.error(error);
return navigateTo("/");
}
});
26 changes: 15 additions & 11 deletions frontend_v2/pages/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,15 @@ const checkScreenSize = () => {
isSmallScreen.value = window.innerWidth >= 1280 && window.innerWidth <= 1535 || window.innerWidth < 1280;
};
watch(() => window.innerWidth, checkScreenSize);
definePageMeta({
middleware: 'auth'
})
</script>

<template>
<NuxtLayout>
<GeneralAuthModalLoginSignUp/>
<div class="mx-auto">
<div class="relative text-white">
<div class="py-2">
Expand All @@ -58,25 +62,25 @@ watch(() => window.innerWidth, checkScreenSize);
<ul class="list-disc ml-8 py-4 font-normal">
<li class="mb-4">
{{ $t('home.nadeDbDescriptionJpSearch') }}:
<a class="underline text-blue-400/95 underline-offset-4"
href="search/sentence?query=彼女">彼女</a>
<NuxtLink class="underline text-blue-400/95 underline-offset-4"
to="search/sentence?query=彼女">彼女</NuxtLink>
</li>
<li class="mb-4">
{{ $t('home.nadeDbDescriptionOtherSearch') }}:
<a class="underline text-blue-400/95 underline-offset-4"
href="search/sentence?query=school">School</a>,
<a class="underline text-blue-400/95 underline-offset-4"
href="search/sentence?query=escuela">Escuela</a>
<NuxtLink class="underline text-blue-400/95 underline-offset-4"
to="search/sentence?query=school">School</NuxtLink>,
<NuxtLink class="underline text-blue-400/95 underline-offset-4"
to="search/sentence?query=escuela">Escuela</NuxtLink>
</li>
<li class="mb-4">
{{ $t('home.nadeDbDescriptionExclusiveSearch') }}:
<a class="underline text-blue-400/95 underline-offset-4"
href="search/sentence?query=卒業 -みんな">卒業 -みんな</a>
<NuxtLink class="underline text-blue-400/95 underline-offset-4"
to="search/sentence?query=卒業 -みんな">卒業 -みんな</NuxtLink>
</li>
<li class="">
{{ $t('home.nadeDbDescriptionExactSearch') }}:
<a href='search/sentence?query="食べられない"'
class="underline text-blue-400/90 underline-offset-4">"食べられない"</a>
<NuxtLink to='search/sentence?query="食べられない"'
class="underline text-blue-400/90 underline-offset-4">"食べられない"</NuxtLink>
</li>
</ul>
</div>
Expand Down
10 changes: 10 additions & 0 deletions frontend_v2/plugins/identity-auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Plugin identity-auth.ts
export default defineNuxtPlugin((nuxtApp) => {
const store = userStore();
const authCookie = useCookie("access_token");

if (import.meta.server) {
// En el servidor, verifica si existe el token
store.isLoggedIn = !!authCookie.value;
}
});
34 changes: 23 additions & 11 deletions frontend_v2/stores/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export const userStore = defineStore('user', {
}),
persist: {
key: 'info',
storage: typeof window !== 'undefined' ? window.localStorage : null,
storage: persistedState.localStorage,
paths: ['isLoggedIn', 'filterPreferences', 'userInfo']
},
actions: {
Expand Down Expand Up @@ -110,7 +110,7 @@ export const userStore = defineStore('user', {
console.log(error);
}
},
async logout(msg) {
async logout(msg: string) {
const config = useRuntimeConfig();
const router = useRouter();
try {
Expand All @@ -135,23 +135,35 @@ export const userStore = defineStore('user', {
},
async getBasicInfo() {
try {
let response = await fetch(import.meta.env.VITE_APP_BASE_URL_BACKEND + 'jwt/user/info', {
method: 'POST',
const config = useRuntimeConfig();
const response = await fetch(`${config.public.baseURLBackend}auth/identity/me`, {
method: 'GET',
mode: 'cors',
headers: {
'Content-Type': 'application/json'
},
withCredentials: true,
credentials: 'include'
})

response = await response.json()
if (response.status === 401) {
this.logout();
});

if (response.ok) {
const responseData = await response.json();
this.$patch((state) => {
state.isLoggedIn = true;
state.userInfo = {
roles: responseData?.user?.roles.map((role: any) => role.id_role)
};
});
return responseData; // Devuelve los datos de la respuesta en caso de éxito
} else {
this.isLoggedIn = false
if (response.status === 401) {
this.logout();
}
}
return response
} catch (error) {
console.log(error)
console.error("Network error:", error);
this.isLoggedIn = false
}
}
}
Expand Down

0 comments on commit 98a617d

Please sign in to comment.