add: auth logic composables

This commit is contained in:
Fadhli Syaifullah 2024-06-04 20:23:02 +07:00
parent d4d7bf8378
commit 8a9bad2eb3
7 changed files with 123 additions and 0 deletions

View File

@ -0,0 +1,20 @@
import axios from "axios";
import { useAuth } from "@/features/auth/stores/useAuth";
import type {
LoginCredential,
LoginResponse,
} from "@/features/auth/types/login.type";
export function useLogin() {
const { auth } = useAuth();
async function login(credential: LoginCredential) {
const response = await axios.post<LoginResponse>(
"/api/auth/login",
credential,
);
auth.auth = response.data.data || null;
}
return { login };
}

View File

@ -0,0 +1,26 @@
import axios from "axios";
import { useAuth } from "@/features/auth/stores/useAuth";
export function useLogout() {
const { auth } = useAuth();
async function logout() {
const response = await axios.post<{ success: boolean }>(
"/api/auth/logout",
null,
{
headers: {
Authorization: `Bearer ${auth.auth?.token}`,
},
},
);
if (!response.data.success) {
throw new Error();
}
auth.auth = null;
}
return { logout };
}

View File

@ -0,0 +1,7 @@
import { useAuth } from "@/features/auth/stores/useAuth";
export function useToken() {
const { auth } = useAuth();
return { token: auth.auth?.token };
}

View File

@ -0,0 +1,14 @@
import { computed } from "vue";
import { defineStore } from "pinia";
import { useLocalStorage } from "@vueuse/core";
import type { UserAuth } from "@/features/auth/types/auth.type";
export const useAuth = defineStore("auth", () => {
const auth = useLocalStorage<{ auth: UserAuth | null }>("asiagolf:auth", {
auth: null,
});
const isAuthenticated = computed(() => !!auth.value.auth);
return { auth, isAuthenticated };
});

View File

@ -0,0 +1,38 @@
export type UserAuth = {
token: string;
user: User;
employee: Employee;
affiliator: any;
};
export type User = {
id: number;
name: string;
email: string;
photo: string;
role: UserRole;
};
export type UserRole = {
id: number;
name: string;
permissions: Array<{
id: number;
name: string;
code: string;
}>;
};
export type Employee = {
id: number;
name: string;
email: string;
departement: {
id: number;
name: string;
};
location: {
id: number;
name: string;
};
};

View File

@ -0,0 +1,10 @@
import type { UserAuth } from "@/features/auth/types/auth.type";
export type LoginCredential = {
email: string;
password: string;
};
export type LoginResponse = {
data: UserAuth;
};

8
src/helpers/sleep.ts Normal file
View File

@ -0,0 +1,8 @@
export async function sleep(ms: number) {
return new Promise<void>((res) => {
const timeout = setTimeout(() => {
res();
clearTimeout(timeout);
}, ms);
});
}