简化H5应用用户授权
This commit is contained in:
@@ -51,6 +51,13 @@ const DEFAULT_PROFILE: UserProfile = {
|
||||
};
|
||||
|
||||
const STORAGE_KEY = "pregnancy_user_profile";
|
||||
const USER_BASIC_KEY = "user_basic";
|
||||
|
||||
export interface BasicUserInfo {
|
||||
id: string;
|
||||
openid: string;
|
||||
phone: string;
|
||||
}
|
||||
|
||||
function loadProfile(): UserProfile {
|
||||
try {
|
||||
@@ -169,6 +176,7 @@ interface UserContextValue {
|
||||
updateUser: (data: Partial<UserProfile>) => void;
|
||||
updateUserRemote: (data: Partial<UserProfile>) => Promise<void>;
|
||||
setToken: (token: string) => void;
|
||||
setTokenAndUser: (token: string, info: BasicUserInfo) => void;
|
||||
fetchProfile: () => Promise<void>;
|
||||
logout: () => void;
|
||||
}
|
||||
@@ -224,17 +232,28 @@ export function UserProvider({ children }: { children: ReactNode }) {
|
||||
}
|
||||
}, [updateUser]);
|
||||
|
||||
const fetchProfile = useCallback(async () => {
|
||||
const fetchProfile = useCallback(async (): Promise<UserProfileDTO | null> => {
|
||||
try {
|
||||
const dto = await getUserProfile();
|
||||
const profile = mapDtoToProfile(dto);
|
||||
setUser(profile);
|
||||
saveProfile(profile);
|
||||
return dto;
|
||||
} catch {
|
||||
// Token 失效会被 api.ts 自动处理(跳转登录页)
|
||||
return null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const setTokenAndUser = useCallback((newToken: string, info: BasicUserInfo) => {
|
||||
// 清理前一个用户的本地数据
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
setUser(DEFAULT_PROFILE);
|
||||
saveToken(newToken);
|
||||
localStorage.setItem(USER_BASIC_KEY, JSON.stringify(info));
|
||||
setTokenState(newToken);
|
||||
}, []);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
clearToken();
|
||||
localStorage.removeItem(STORAGE_KEY);
|
||||
@@ -250,7 +269,7 @@ export function UserProvider({ children }: { children: ReactNode }) {
|
||||
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
return (
|
||||
<UserContext.Provider value={{ user, token, updateUser, updateUserRemote, setToken, fetchProfile, logout }}>
|
||||
<UserContext.Provider value={{ user, token, updateUser, updateUserRemote, setToken, setTokenAndUser, fetchProfile, logout }}>
|
||||
{children}
|
||||
</UserContext.Provider>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user