Skip to content

Commit

Permalink
Store route and fetch user role
Browse files Browse the repository at this point in the history
  • Loading branch information
rr-adam committed Sep 13, 2024
1 parent d63f696 commit d7de911
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 9 deletions.
7 changes: 5 additions & 2 deletions general/components/Header/AuthLoginModal.vue
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ const toastStore = useToastStore();
const authStore = useAuthStore();
const authModalStore = useAuthModalStore();
const route = useRoute();
const identifier = ref<string>('');
const password = ref<string>('');
const error = ref<string | null>(null);
Expand Down Expand Up @@ -132,8 +134,7 @@ const handleSubmit = async () => {
});
if (response.jwt && response.user) {
authStore.setJwt(response.jwt);
authStore.setUserData(response.user);
await authStore.loginAndFetchProfile(response.jwt, response.user);
toastStore.addToast('You are logged in.');
hideModal();
} else {
Expand All @@ -160,6 +161,8 @@ const handleSubmit = async () => {
const connectGithub = () => {
const githubConnectUrl = `${baseURL()}/api/connect/github`;
authStore.setRedirectLink(route.fullPath);
window.location.href = githubConnectUrl;
};
Expand Down
15 changes: 11 additions & 4 deletions general/pages/connect/github.vue
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,14 @@ onMounted(async () => {
);
if (response.jwt && response.user) {
authStore.setJwt(response.jwt);
authStore.setUserData(response.user);
await authStore.loginAndFetchProfile(response.jwt, response.user);
toastStore.addToast('Successfully logged in with GitHub.');
statusMessage.value = 'Authentication successful. Redirecting...';
setTimeout(() => router.push('/ontology'), 2000);
const redirectUrl = authStore.redirectLink || '/ontology';
authStore.clearRedirectLink();
setTimeout(() => router.push(redirectUrl), 2000);
} else {
throw new Error('Invalid response from server');
}
Expand All @@ -86,7 +89,11 @@ const handleError = (message: string) => {
statusMessage.value = 'Authentication failed. Redirecting...';
toastStore.addToast(`GitHub authentication failed!`, 'error');
authStore.clear();
setTimeout(() => router.push('/'), 2000);
const redirectUrl = authStore.redirectLink || '/';
authStore.clearRedirectLink();
setTimeout(() => router.push(redirectUrl), 2000);
};
</script>

Expand Down
56 changes: 53 additions & 3 deletions general/stores/auth.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { defineStore } from 'pinia';
import { useRuntimeConfig } from '#app';

export interface UserData {
id: number;
Expand All @@ -22,14 +23,16 @@ export interface UserData {
interface AuthState {
jwt: string | null;
user: UserData | null;
redirectLink: string | null;
}

export const useAuthStore = defineStore({
id: 'auth-store',
state: (): AuthState => {
return {
jwt: null,
user: null
user: null,
redirectLink: null
};
},
actions: {
Expand All @@ -39,17 +42,64 @@ export const useAuthStore = defineStore({
setUserData(user: UserData) {
this.user = user;
},
setRedirectLink(link: string) {
this.redirectLink = link;
},
clearRedirectLink() {
this.redirectLink = null;
},
async fetchFullProfile() {
if (!this.jwt) {
throw new Error('No JWT token available');
}

const runtimeConfig = useRuntimeConfig();
const baseURL =
typeof window !== 'undefined'
? window.location.origin + `${runtimeConfig.public.strapiBasePath}`
: `${runtimeConfig.public.strapiBaseUrl}`;

try {
const response = await $fetch<UserData>(
`${baseURL}/api/users/me?populate=role`,
{
method: 'GET',
headers: {
Authorization: `Bearer ${this.jwt}`
}
}
);

if (response) {
this.setUserData(response);
} else {
throw new Error('Invalid response from server');
}
} catch (error) {
console.error('Error fetching full profile:', error);
throw error;
}
},
async loginAndFetchProfile(
jwt: string,
initialUserData: Partial<UserData>
) {
this.setJwt(jwt);
this.setUserData({ ...initialUserData } as UserData);
await this.fetchFullProfile();
},
clear() {
this.jwt = null;
this.user = null;
this.redirectLink = null;
}
},
persist: {
key: () => {
const runtimeConfig = useRuntimeConfig();
return `ontoviewer-auth-${runtimeConfig.public.ontologyName}`;
},
storage: process.client ? localStorage : undefined,
paths: ['jwt', 'user']
storage: import.meta.client ? localStorage : undefined,
paths: ['jwt', 'user', 'redirectLink']
}
});

0 comments on commit d7de911

Please sign in to comment.