mirror of
https://github.com/Buriburizaem0n/admin-frontend-domain.git
synced 2026-02-04 12:40:08 +00:00
feat: login & check user
This commit is contained in:
@@ -1,7 +1,9 @@
|
||||
import { createContext, useContext, useMemo } from "react";
|
||||
import { createContext, useContext, useEffect, useMemo, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useMainStore } from "./useMainStore";
|
||||
import { AuthContextProps, User } from "@/types";
|
||||
import { AuthContextProps } from "@/types";
|
||||
import { getProfile, login as loginRequest } from "@/api/user";
|
||||
import { toast } from "sonner";
|
||||
|
||||
const AuthContext = createContext<AuthContextProps>({
|
||||
profile: undefined,
|
||||
@@ -14,11 +16,35 @@ export const AuthProvider = ({ children }: {
|
||||
}) => {
|
||||
const profile = useMainStore(store => store.profile)
|
||||
const setProfile = useMainStore(store => store.setProfile)
|
||||
const [lastUpdatedAt, setLastUpdatedAt] = useState<number>(0);
|
||||
|
||||
// FIXME @naiba 触发了两次
|
||||
useEffect(() => {
|
||||
if (profile && Date.now() - lastUpdatedAt > 1000 * 60 * 5) {
|
||||
console.log(profile, Date.now(), lastUpdatedAt)
|
||||
getProfile().then((data) => {
|
||||
setLastUpdatedAt(Date.now())
|
||||
if (data && data.username !== profile.username) {
|
||||
console.log('bingo', data.username);
|
||||
setProfile(data)
|
||||
}
|
||||
}).catch(() => {
|
||||
setLastUpdatedAt(Date.now())
|
||||
setProfile(undefined)
|
||||
})
|
||||
}
|
||||
}, [profile])
|
||||
|
||||
const navigate = useNavigate();
|
||||
|
||||
const login = async (profile: User | undefined) => {
|
||||
setProfile(profile);
|
||||
navigate("/dashboard");
|
||||
const login = async (username: string, password: string) => {
|
||||
try {
|
||||
await loginRequest(username, password)
|
||||
setProfile({ username: username });
|
||||
navigate("/dashboard");
|
||||
} catch (error: any) {
|
||||
toast(error.message);
|
||||
}
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
|
||||
Reference in New Issue
Block a user