generated from pricelees/issue-pr-template
<!-- 제목 양식 --> <!-- [이슈번호] 작업 요약 (예시: [#10] Gitea 템플릿 생성) --> ## 📝 관련 이슈 및 PR **PR과 관련된 이슈 번호** - #28 ## ✨ 작업 내용 <!-- 어떤 작업을 했는지 알려주세요! --> - 프론트엔드, 백엔드 쿠버네티스 환경 배포(ArgoCD 이용) - Helm 차트는 private repository에 업로드 ## 🧪 테스트 <!-- 어떤 테스트를 생각했고 진행했는지 알려주세요! --> - 배포 환경에서 기능 정상 동작 확인 ## 📚 참고 자료 및 기타 <!-- 참고한 자료, 또는 논의할 사항이 있다면 알려주세요! --> Reviewed-on: #29 Co-authored-by: pricelees <priceelees@gmail.com> Co-committed-by: pricelees <priceelees@gmail.com>
74 lines
2.3 KiB
TypeScript
74 lines
2.3 KiB
TypeScript
import { checkLogin as apiCheckLogin, login as apiLogin, logout as apiLogout } from '@_api/auth/authAPI';
|
|
import type { LoginRequest, LoginResponse } from '@_api/auth/authTypes';
|
|
import React, { createContext, useContext, useEffect, useState, type ReactNode } from 'react';
|
|
|
|
interface AuthContextType {
|
|
loggedIn: boolean;
|
|
userName: string | null;
|
|
role: 'ADMIN' | 'MEMBER' | null;
|
|
loading: boolean; // Add loading state to type
|
|
login: (data: LoginRequest) => Promise<LoginResponse>;
|
|
logout: () => Promise<void>;
|
|
checkLogin: () => Promise<void>;
|
|
}
|
|
|
|
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
|
|
|
export const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
|
|
const [loggedIn, setLoggedIn] = useState(false);
|
|
const [userName, setUserName] = useState<string | null>(null);
|
|
const [role, setRole] = useState<'ADMIN' | 'MEMBER' | null>(null);
|
|
const [loading, setLoading] = useState(true); // Add loading state
|
|
|
|
const checkLogin = async () => {
|
|
try {
|
|
const response = await apiCheckLogin();
|
|
setLoggedIn(true);
|
|
setUserName(response.name);
|
|
setRole(response.role);
|
|
} catch (error) {
|
|
setLoggedIn(false);
|
|
setUserName(null);
|
|
setRole(null);
|
|
localStorage.removeItem('accessToken');
|
|
} finally {
|
|
setLoading(false); // Set loading to false after check is complete
|
|
}
|
|
};
|
|
|
|
useEffect(() => {
|
|
checkLogin();
|
|
}, []);
|
|
|
|
const login = async (data: LoginRequest) => {
|
|
const response = await apiLogin(data);
|
|
await checkLogin();
|
|
return response;
|
|
};
|
|
|
|
const logout = async () => {
|
|
try {
|
|
await apiLogout();
|
|
} finally {
|
|
setLoggedIn(false);
|
|
setUserName(null);
|
|
setRole(null);
|
|
localStorage.removeItem('accessToken');
|
|
}
|
|
};
|
|
|
|
return (
|
|
<AuthContext.Provider value={{ loggedIn, userName, role, loading, login, logout, checkLogin }}>
|
|
{children}
|
|
</AuthContext.Provider>
|
|
);
|
|
};
|
|
|
|
export const useAuth = (): AuthContextType => {
|
|
const context = useContext(AuthContext);
|
|
if (!context) {
|
|
throw new Error('useAuth must be used within an AuthProvider');
|
|
}
|
|
return context;
|
|
};
|