64 lines
2.0 KiB
TypeScript
64 lines
2.0 KiB
TypeScript
import { defineStore } from "pinia";
|
||
import { ref, computed } from "vue";
|
||
import type { AuthResponse } from "@/types/api";
|
||
import router from "@/router";
|
||
import authService from "@/services/authService";
|
||
|
||
export const useAuthStore = defineStore("auth", () => {
|
||
const token = ref<string | null>(localStorage.getItem("token"));
|
||
const refreshToken = ref<string | null>(localStorage.getItem("refresh"));
|
||
const userId = ref<number | null>(JSON.parse(localStorage.getItem("userId") || "null"));
|
||
const username = ref<string | null>(localStorage.getItem("username"));
|
||
const fullName = ref<string | null>(localStorage.getItem("fullName"));
|
||
|
||
const isAuthenticated = computed(() => !!token.value);
|
||
|
||
function setAuthData(data: AuthResponse) {
|
||
// Сохраняем токены с кавычками, как требует ТЗ
|
||
localStorage.setItem("token", JSON.stringify(data.auth_token));
|
||
localStorage.setItem("refresh", JSON.stringify(data.refresh));
|
||
localStorage.setItem("userId", JSON.stringify(data.id));
|
||
localStorage.setItem("username", data.username);
|
||
localStorage.setItem("fullName", data.full_name);
|
||
|
||
token.value = JSON.stringify(data.auth_token);
|
||
refreshToken.value = JSON.stringify(data.refresh);
|
||
userId.value = data.id;
|
||
username.value = data.username;
|
||
fullName.value = data.full_name;
|
||
}
|
||
|
||
function logout() {
|
||
localStorage.removeItem("token");
|
||
localStorage.removeItem("refresh");
|
||
localStorage.removeItem("userId");
|
||
localStorage.removeItem("username");
|
||
localStorage.removeItem("fullName");
|
||
|
||
token.value = null;
|
||
refreshToken.value = null;
|
||
userId.value = null;
|
||
username.value = null;
|
||
fullName.value = null;
|
||
|
||
router.push({ name: "Login" });
|
||
}
|
||
|
||
async function login(email: string, pass: string) {
|
||
const data = await authService.login(email, pass);
|
||
setAuthData(data);
|
||
}
|
||
|
||
return {
|
||
token,
|
||
refreshToken,
|
||
userId,
|
||
username,
|
||
fullName,
|
||
isAuthenticated,
|
||
login,
|
||
logout,
|
||
setAuthData,
|
||
};
|
||
});
|