tiefen_space_web/utils/auth.js

48 lines
1.1 KiB
JavaScript
Raw Normal View History

2024-01-03 01:07:16 +08:00
import { setCookie, deleteCookie, getCookie } from "cookies-next";
import baseRequest from "./baseRequest";
import { generateSignature } from "@/utils/crypto";
export async function checkAuth() {
const token = getCookie("token");
const account = getCookie("account");
if (token && account) {
//验证是否过期
try {
const base = baseRequest();
const signature = generateSignature({
...base,
});
const response = await fetch(
`/api/login/validate?signature=${signature}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
...base,
}),
}
);
const data = await response.json();
if (data.ret === -1) {
return false;
}
return true;
} catch (e) {
console.warn(e);
}
}
return false;
}
export function signIn(data) {
setCookie("token", data.data.token);
setCookie("account", data.data.account);
}
export function signOut() {
deleteCookie("token");
deleteCookie("account");
}