Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 3x 3x 3x 3x | import { createContext, useContext, useState, useCallback, useEffect } from 'react';
import { isSupportedLocale, LOCALE_STORAGE_KEY, setCurrentLocale } from '@/i18n';
import { ApiError, setTokenRefreshManager } from '@/services/api';
import { profileService } from '@/services/profileService';
import type { UserRole } from '@/models/auth';
const STORAGE_KEY_TOKEN = 'sem_access_token';
const STORAGE_KEY_REFRESH = 'sem_refresh_token';
const STORAGE_KEY_USERNAME = 'sem_username';
const STORAGE_KEY_AVATAR_URL = 'sem_avatar_url';
const STORAGE_KEY_DISPLAY_NAME = 'sem_display_name';
const STORAGE_KEY_ROLE = 'sem_role';
function normalizeRole(value: string | null | undefined): UserRole | null {
return value === 'ADMIN' || value === 'USER' ? value : null;
}
function readRoleFromAccessToken(accessToken: string): UserRole | null {
const payload = accessToken.split('.')[1];
if (!payload) return null;
try {
const normalized = payload.replace(/-/g, '+').replace(/_/g, '/');
const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=');
const decoded = JSON.parse(window.atob(padded)) as { role?: string };
return normalizeRole(decoded.role);
} catch {
return null;
}
}
export interface ProfileSummary {
avatarUrl: string | null;
displayName: string | null;
}
interface AuthContextType {
token: string | null;
refreshToken: string | null;
username: string | null;
role: UserRole | null;
avatarUrl: string | null;
displayName: string | null;
isLoading: boolean;
setSession: (accessToken: string, refreshToken: string, username: string, role?: UserRole) => void;
setProfileSummary: (data: ProfileSummary) => void;
clearAuth: () => void;
}
const AuthContext = createContext<AuthContextType | null>(null);
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [token, setToken] = useState<string | null>(null);
const [refreshToken, setRefreshToken] = useState<string | null>(null);
const [username, setUsername] = useState<string | null>(null);
const [role, setRole] = useState<UserRole | null>(null);
const [avatarUrl, setAvatarUrl] = useState<string | null>(null);
const [displayName, setDisplayName] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true);
const setProfileSummary = useCallback((data: ProfileSummary) => {
setAvatarUrl(data.avatarUrl);
setDisplayName(data.displayName);
if (data.avatarUrl) {
localStorage.setItem(STORAGE_KEY_AVATAR_URL, data.avatarUrl);
} else {
localStorage.removeItem(STORAGE_KEY_AVATAR_URL);
}
if (data.displayName) {
localStorage.setItem(STORAGE_KEY_DISPLAY_NAME, data.displayName);
} else {
localStorage.removeItem(STORAGE_KEY_DISPLAY_NAME);
}
}, []);
useEffect(() => {
const storedToken = localStorage.getItem(STORAGE_KEY_TOKEN);
const storedRefresh = localStorage.getItem(STORAGE_KEY_REFRESH);
const storedUsername = localStorage.getItem(STORAGE_KEY_USERNAME);
if (storedToken && storedRefresh) {
setToken(storedToken);
setRefreshToken(storedRefresh);
setUsername(storedUsername);
const storedRole = normalizeRole(localStorage.getItem(STORAGE_KEY_ROLE)) ?? readRoleFromAccessToken(storedToken) ?? 'USER';
setRole(storedRole);
localStorage.setItem(STORAGE_KEY_ROLE, storedRole);
const storedAvatar = localStorage.getItem(STORAGE_KEY_AVATAR_URL);
const storedDisplayName = localStorage.getItem(STORAGE_KEY_DISPLAY_NAME);
setAvatarUrl(storedAvatar);
setDisplayName(storedDisplayName);
}
setIsLoading(false);
}, []);
const setSession = useCallback(
(accessToken: string, refresh: string, user: string, nextRole: UserRole = 'USER') => {
localStorage.setItem(STORAGE_KEY_TOKEN, accessToken);
localStorage.setItem(STORAGE_KEY_REFRESH, refresh);
localStorage.setItem(STORAGE_KEY_USERNAME, user);
localStorage.setItem(STORAGE_KEY_ROLE, nextRole);
localStorage.removeItem(STORAGE_KEY_AVATAR_URL);
localStorage.removeItem(STORAGE_KEY_DISPLAY_NAME);
setToken(accessToken);
setRefreshToken(refresh);
setUsername(user);
setRole(nextRole);
setAvatarUrl(null);
setDisplayName(null);
},
[],
);
const clearAuth = useCallback(() => {
localStorage.removeItem(STORAGE_KEY_TOKEN);
localStorage.removeItem(STORAGE_KEY_REFRESH);
localStorage.removeItem(STORAGE_KEY_USERNAME);
localStorage.removeItem(STORAGE_KEY_ROLE);
localStorage.removeItem(STORAGE_KEY_AVATAR_URL);
localStorage.removeItem(STORAGE_KEY_DISPLAY_NAME);
setToken(null);
setRefreshToken(null);
setUsername(null);
setRole(null);
setAvatarUrl(null);
setDisplayName(null);
}, []);
useEffect(() => {
if (!token) return;
let cancelled = false;
profileService
.getMyProfile(token)
.then((data) => {
if (!cancelled) {
setProfileSummary({
avatarUrl: data.avatar_url ?? null,
displayName: data.display_name ?? null,
});
const localPreference = localStorage.getItem(LOCALE_STORAGE_KEY);
if (isSupportedLocale(localPreference)) {
void setCurrentLocale(localPreference);
} else if (isSupportedLocale(data.locale)) {
void setCurrentLocale(data.locale);
}
}
})
.catch((err: unknown) => {
if (!cancelled && err instanceof ApiError && (err.status === 401 || err.status === 403 || err.status === 404)) {
clearAuth();
return;
}
/* keep cached profile summary from localStorage */
});
return () => {
cancelled = true;
};
}, [token, setProfileSummary, clearAuth]);
useEffect(() => {
setTokenRefreshManager({
getRefreshToken: () => localStorage.getItem(STORAGE_KEY_REFRESH),
onRefreshSuccess: (accessToken, newRefreshToken, newUsername, newRole) => {
setSession(accessToken, newRefreshToken, newUsername, newRole);
},
onRefreshFailure: clearAuth,
});
return () => {
setTokenRefreshManager(null);
};
}, [setSession, clearAuth]);
return (
<AuthContext.Provider
value={{
token,
refreshToken,
username,
role,
avatarUrl,
displayName,
isLoading,
setSession,
setProfileSummary,
clearAuth,
}}
>
{children}
</AuthContext.Provider>
);
}
export function useAuth(): AuthContextType {
const ctx = useContext(AuthContext);
if (!ctx) throw new Error('useAuth must be used within AuthProvider');
return ctx;
}
|