feat: login & check user

This commit is contained in:
naiba
2024-11-03 23:29:32 +08:00
parent 772d66334e
commit b1a0b607da
10 changed files with 157 additions and 11 deletions

View File

@@ -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 = () => {