refactor(auth): 프론트엔드/백엔드 로그인 로직 개선
- 프론트엔드: login.js, api-helper.js, auth.js 모듈화 및 책임 분리 - 백엔드: authController가 역할 기반 redirectUrl을 제공하도록 수정 - 로그인 프로세스의 안정성 및 유지보수성 향상
This commit is contained in:
@@ -1,52 +1,7 @@
|
||||
// 깔끔한 로그인 로직 (login.js)
|
||||
import { API } from './api-config.js';
|
||||
// /js/login.js
|
||||
|
||||
function parseJwt(token) {
|
||||
try {
|
||||
return JSON.parse(atob(token.split('.')[1]));
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 역할별 대시보드 라우팅
|
||||
function routeToDashboard(user) {
|
||||
const accessLevel = (user.access_level || '').toLowerCase().trim();
|
||||
|
||||
// 그룹장/리더 관련 키워드들
|
||||
const leaderKeywords = [
|
||||
'group_leader', 'groupleader', 'group-leader',
|
||||
'leader', 'supervisor', 'team_leader', 'teamleader',
|
||||
'그룹장', '팀장', '현장책임자'
|
||||
];
|
||||
|
||||
// 관리자 관련 키워드들
|
||||
const adminKeywords = [
|
||||
'admin', 'administrator', 'system',
|
||||
'관리자', '시스템관리자'
|
||||
];
|
||||
|
||||
// 지원팀 관련 키워드들
|
||||
const supportKeywords = [
|
||||
'support', 'support_team', 'supportteam',
|
||||
'지원팀', '지원'
|
||||
];
|
||||
|
||||
// 키워드 매칭
|
||||
if (leaderKeywords.some(keyword => accessLevel.includes(keyword.toLowerCase()))) {
|
||||
return '/pages/dashboard/group-leader.html';
|
||||
}
|
||||
|
||||
if (adminKeywords.some(keyword => accessLevel.includes(keyword.toLowerCase()))) {
|
||||
return '/pages/dashboard/admin.html';
|
||||
}
|
||||
|
||||
if (supportKeywords.some(keyword => accessLevel.includes(keyword.toLowerCase()))) {
|
||||
return '/pages/dashboard/support.html';
|
||||
}
|
||||
|
||||
return '/pages/dashboard/user.html';
|
||||
}
|
||||
import { login } from './api-helper.js';
|
||||
import { saveAuthData, clearAuthData } from './auth.js';
|
||||
|
||||
document.getElementById('loginForm').addEventListener('submit', async function (e) {
|
||||
e.preventDefault();
|
||||
@@ -55,48 +10,45 @@ document.getElementById('loginForm').addEventListener('submit', async function (
|
||||
const password = document.getElementById('password').value;
|
||||
const errorDiv = document.getElementById('error');
|
||||
|
||||
// 로딩 상태 표시
|
||||
const submitBtn = e.target.querySelector('button[type="submit"]');
|
||||
const originalText = submitBtn.textContent;
|
||||
|
||||
// 로딩 상태 시작
|
||||
submitBtn.disabled = true;
|
||||
submitBtn.textContent = '로그인 중...';
|
||||
errorDiv.style.display = 'none';
|
||||
|
||||
try {
|
||||
const res = await fetch(`${API}/auth/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password })
|
||||
});
|
||||
// API 헬퍼를 통해 로그인 요청
|
||||
const result = await login(username, password);
|
||||
|
||||
const result = await res.json();
|
||||
if (result.success && result.token) {
|
||||
// 인증 정보 저장
|
||||
saveAuthData(result.token, result.user);
|
||||
|
||||
if (res.ok && result.success && result.token) {
|
||||
localStorage.setItem('token', result.token);
|
||||
localStorage.setItem('user', JSON.stringify(result.user));
|
||||
|
||||
// 역할별 대시보드로 리다이렉트
|
||||
const redirectUrl = routeToDashboard(result.user);
|
||||
// 백엔드가 지정한 URL로 리디렉션
|
||||
const redirectUrl = result.redirectUrl || '/pages/dashboard/user.html'; // 혹시 모를 예외처리
|
||||
|
||||
// 부드러운 전환 효과
|
||||
// 부드러운 화면 전환 효과
|
||||
document.body.style.transition = 'opacity 0.3s ease-out';
|
||||
document.body.style.opacity = '0';
|
||||
|
||||
setTimeout(() => {
|
||||
window.location.href = redirectUrl;
|
||||
}, 300);
|
||||
|
||||
} else {
|
||||
localStorage.removeItem('token');
|
||||
localStorage.removeItem('user');
|
||||
// 이 케이스는 api-helper에서 throw new Error()로 처리되어 catch 블록으로 바로 이동합니다.
|
||||
// 하지만, 만약의 경우를 대비해 방어 코드를 남겨둡니다.
|
||||
clearAuthData();
|
||||
errorDiv.textContent = result.error || '로그인에 실패했습니다.';
|
||||
errorDiv.style.display = 'block';
|
||||
|
||||
// 에러 메시지 자동 숨김
|
||||
setTimeout(() => {
|
||||
errorDiv.style.display = 'none';
|
||||
}, 5000);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('로그인 오류:', err);
|
||||
errorDiv.textContent = '서버 연결에 실패했습니다. 잠시 후 다시 시도해주세요.';
|
||||
clearAuthData();
|
||||
// api-helper에서 보낸 에러 메시지를 표시
|
||||
errorDiv.textContent = err.message || '서버 연결에 실패했습니다.';
|
||||
errorDiv.style.display = 'block';
|
||||
} finally {
|
||||
// 로딩 상태 해제
|
||||
|
||||
Reference in New Issue
Block a user