Skip to content

Commit

Permalink
fix: session issues and lessons navigation
Browse files Browse the repository at this point in the history
  • Loading branch information
BernardoSM committed Sep 23, 2023
1 parent ffcf206 commit eaa7045
Show file tree
Hide file tree
Showing 14 changed files with 191 additions and 73 deletions.
17 changes: 15 additions & 2 deletions apps/app/components/molecules/SearchModal.vue
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<script setup lang="ts">
import type { ParsedContent } from "../../../../node_modules/@nuxt/content/dist/runtime/types";
import { useDebounceFn } from "@vueuse/core";
import { useMagicKeys } from "@vueuse/core";
const { escape } = useMagicKeys();
Expand All @@ -23,7 +24,7 @@ function resetNavigatedIndex() {
}
const searchModalStore = useSearchModalStore();
const loading = ref(false);
const search = ref(null);
const { data: coursesAndCategories } = await useAsyncData(
Expand Down Expand Up @@ -62,6 +63,11 @@ function resetSearch() {
});
}
const searchDebounce = useDebounceFn(() => {
searchContent();
loading.value = false;
}, 1000);
async function searchContent() {
resetNavigatedIndex();
if (String(search.value).length <= 0) {
Expand Down Expand Up @@ -130,11 +136,18 @@ watch(searchModalStore, async (newValue) => {
ref="searchInput"
type="search"
v-model="search"
@input="searchContent"
@input="
loading = true;
searchDebounce();
"
autocomplete="off"
placeholder="Pesquise aulas ou escreva um comando..."
class="mb-3 block w-full pt-2 text-base font-medium text-zinc-950 !outline-none placeholder:text-zinc-500"
/>
<MSpinner
v-if="loading"
class="absolute top-[24px] right-[24px] w-[14px] h-[14px] border-zinc-400"
/>
<div class="flex items-center text-sm">
<div class="flex flex-1 items-center gap-2 text-zinc-700">
<Command icon="arrow-up" />
Expand Down
13 changes: 3 additions & 10 deletions apps/app/components/molecules/TopBar.vue
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,6 @@ const router = useRouter();
const sessionStore = useSessionStore();
const userStore = useUserStore();
const defaultAsideStore = useDefaultAsideStore();
function signOut() {
sessionStore.signOut();
router.push("/sign-in");
}
</script>

<template>
Expand Down Expand Up @@ -58,11 +53,9 @@ function signOut() {
<NuxtLink to="/profile">
<DropdownItem icon="circle-user" name="Perfil" />
</NuxtLink>
<DropdownItem
icon="arrow-right-from-bracket"
name="Sair"
@click="signOut"
/>
<NuxtLink to="/sign-out">
<DropdownItem icon="arrow-right-from-bracket" name="Sair" />
</NuxtLink>
</div>
</template>
</VDropdown>
Expand Down
6 changes: 5 additions & 1 deletion apps/app/components/organisms/DefaultAside.vue
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const queryBuilder = computed(() => {
return queryContent(`/${route.params?.slug ? route.params.slug[0] : ""}`);
});
const { data: navigation } = await useAsyncData(
const { data: navigation, refresh } = await useAsyncData(
route.params?.slug ? route.params.slug[0] : "navigation",
() => fetchContentNavigation(queryBuilder.value),
{
Expand All @@ -18,6 +18,10 @@ const { data: navigation } = await useAsyncData(
const isLesson = computed(() => {
return !!route.meta?.lesson;
});
watch(isLesson, async () => {
refresh();
});
</script>

<template>
Expand Down
10 changes: 10 additions & 0 deletions apps/app/composables/useCookieFetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { appendResponseHeader, H3Event } from "h3";

export const useCookieFetch = async (event: H3Event, url: string) => {
const res = await $fetch.raw(url);
const cookies = (res.headers.get("set-cookie") || "").split(",");
for (const cookie of cookies) {
appendResponseHeader(event, "set-cookie", cookie);
}
return res._data;
};
1 change: 1 addition & 0 deletions apps/app/layouts/default.vue
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
const userStore = useUserStore();
const sessionStore = useSessionStore();
const defaultAsideStore = useDefaultAsideStore();
sessionStore.refreshSession();
const content = ref();
Expand Down
18 changes: 7 additions & 11 deletions apps/app/middleware/session.global.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
import { useCookies } from "@vueuse/integrations/useCookies";

export default defineNuxtRouteMiddleware(async (to) => {
if (to.query.oauth) return;

const sessionStore = useSessionStore();
const userStore = useUserStore();
const serverUser = useCookie("m-user");

const userCookie = useCookies([]);
const userCookieValue = userCookie.get("m-user");
if (userCookieValue) {
userStore.user = userCookieValue;
console.log({ userCookieValue });
if (serverUser) {
userStore.user = serverUser.value as typeof userStore.user;
}

const serverHasSession = sessionStore.hasSession();
if (to.query.oauth) return;

const sessionStore = useSessionStore();
const serverHasSession = !!serverUser.value || sessionStore.hasSession();

if (["profile"].includes(String(to.name)) && !serverHasSession) {
return navigateTo("/sign-in");
Expand Down
2 changes: 1 addition & 1 deletion apps/app/modules/eslint-globals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ const autoImportEslint = defineNuxtModule({
getContents,
write: true,
});
console.log(`globals file is generated at ${fullPath}`);
// console.log(`globals file is generated at ${fullPath}`);
});
},
});
Expand Down
2 changes: 1 addition & 1 deletion apps/app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"postinstall": "nuxt prepare"
},
"devDependencies": {
"@nuxt/content": "^2.8.2",
"@nuxt/content": "npm:@nuxt/content-edge@latest",
"@nuxtjs/fontaine": "^0.2.5",
"@types/node": "^20.4.6",
"nuxt": "^3.7.3",
Expand Down
3 changes: 2 additions & 1 deletion apps/app/pages/code.vue
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,9 @@ async function sendCode() {
await signUpStore.attemptEmailAddressVerification({
code: code.join(""),
});
await sessionStore.refreshSession();
userStore.setUser();
await sessionStore.refreshSession();
router.push("/");
} catch (e) {
toast?.error("Código incorreto ou expirado.");
Expand Down
2 changes: 1 addition & 1 deletion apps/app/pages/sign-in.vue
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ async function clerkOAuth({ strategy }: { strategy: string }) {
/>
<MTextField
class="mb-6"
label="Password"
label="Senha"
type="password"
v-model="password"
:rules="['password']"
Expand Down
2 changes: 1 addition & 1 deletion apps/app/pages/sign-up.vue
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ async function clerkOAuth(strategy) {
/>
<MTextField
class="mb-6"
label="Password"
label="Senha"
type="password"
v-model="password"
:rules="['password']"
Expand Down
13 changes: 12 additions & 1 deletion apps/app/stores/clerk/session.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { defineStore } from "pinia";
import { useCookies } from "@vueuse/integrations/useCookies";
import { ClerkAPIError } from "@clerk/types";

export const useSessionStore = defineStore("session", {
state: (): { token: string | null; cleared: boolean } => ({
Expand All @@ -24,7 +25,17 @@ export const useSessionStore = defineStore("session", {
},
async refreshSession() {
const clientSession = this.$clerk?.client?.sessions[0];
await this.$clerk.setSession(clientSession);
if (!clientSession) return;
try {
await this.$clerk.setSession(clientSession);
} catch (e) {
const clerkError: { errors: ClerkAPIError[] } | any = e;
if (clerkError.errors[0].code === "authentication_invalid") {
this.$router.push("/sign-out");
}

throw new Error((e as Error).message);
}
},
async signOut() {
const clerkToken = useCookies([]);
Expand Down
3 changes: 2 additions & 1 deletion apps/app/stores/clerk/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,12 @@ export const useUserStore = defineStore("user", {
const userData = this.$clerk.user
? this.$clerk.user
: this.$clerk.client.sessions[0]?.user;

if (!userData) return;

this.user = userData;
const userCookie = useCookies([]);
userCookie.set("rise-user", userData);
userCookie.set("m-user", userData);
},
async updateUser() {
await this.$clerk.user.update<UpdateUserParams>({
Expand Down
Loading

0 comments on commit eaa7045

Please sign in to comment.