v0.1.11 - 인증 UI 연결
This commit is contained in:
81
src/lib/authClient.js
Normal file
81
src/lib/authClient.js
Normal file
@@ -0,0 +1,81 @@
|
||||
const AUTH_STORAGE_KEY = 'ten-minute-planner-auth'
|
||||
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:3001'
|
||||
|
||||
function buildHeaders(token, extraHeaders = {}) {
|
||||
return {
|
||||
'Content-Type': 'application/json',
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
...extraHeaders,
|
||||
}
|
||||
}
|
||||
|
||||
async function request(path, { method = 'GET', token, body } = {}) {
|
||||
const response = await fetch(`${API_BASE_URL}${path}`, {
|
||||
method,
|
||||
headers: buildHeaders(token),
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
})
|
||||
|
||||
const data = await response.json().catch(() => ({}))
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.message || '요청 처리 중 문제가 발생했습니다.')
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
export function readAuthState() {
|
||||
if (typeof window === 'undefined') {
|
||||
return { token: '', user: null }
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(window.localStorage.getItem(AUTH_STORAGE_KEY) ?? '{"token":"","user":null}')
|
||||
} catch (error) {
|
||||
console.warn('저장된 인증 상태를 불러오지 못했습니다.', error)
|
||||
return { token: '', user: null }
|
||||
}
|
||||
}
|
||||
|
||||
export function persistAuthState({ token, user }) {
|
||||
if (typeof window === 'undefined') {
|
||||
return
|
||||
}
|
||||
|
||||
window.localStorage.setItem(
|
||||
AUTH_STORAGE_KEY,
|
||||
JSON.stringify({
|
||||
token,
|
||||
user,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
export function clearAuthState() {
|
||||
if (typeof window === 'undefined') {
|
||||
return
|
||||
}
|
||||
|
||||
window.localStorage.removeItem(AUTH_STORAGE_KEY)
|
||||
}
|
||||
|
||||
export async function signup({ email, password, nickname }) {
|
||||
return request('/api/auth/signup', {
|
||||
method: 'POST',
|
||||
body: { email, password, nickname },
|
||||
})
|
||||
}
|
||||
|
||||
export async function login({ email, password }) {
|
||||
return request('/api/auth/login', {
|
||||
method: 'POST',
|
||||
body: { email, password },
|
||||
})
|
||||
}
|
||||
|
||||
export async function fetchCurrentUser(token) {
|
||||
return request('/api/auth/me', {
|
||||
token,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user