99 lines
2.3 KiB
JavaScript
99 lines
2.3 KiB
JavaScript
const AUTH_STORAGE_KEY = 'ten-minute-planner-auth'
|
|
import { buildApiUrl, toUserFacingApiError } from './apiBase'
|
|
|
|
function buildHeaders(token, hasBody, extraHeaders = {}) {
|
|
return {
|
|
...(hasBody ? { 'Content-Type': 'application/json' } : {}),
|
|
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
|
...extraHeaders,
|
|
}
|
|
}
|
|
|
|
async function request(path, { method = 'GET', token, body } = {}) {
|
|
const hasBody = body !== undefined
|
|
const response = await fetch(buildApiUrl(path), {
|
|
method,
|
|
headers: buildHeaders(token, hasBody),
|
|
body: hasBody ? JSON.stringify(body) : undefined,
|
|
})
|
|
|
|
const data = await response.json().catch(() => ({}))
|
|
|
|
if (!response.ok) {
|
|
throw new Error(toUserFacingApiError(data, '요청 처리 중 문제가 발생했습니다.'))
|
|
}
|
|
|
|
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,
|
|
})
|
|
}
|
|
|
|
export async function updateProfile(token, { email, nickname }) {
|
|
return request('/api/auth/profile', {
|
|
method: 'PUT',
|
|
token,
|
|
body: { email, nickname },
|
|
})
|
|
}
|
|
|
|
export async function updatePassword(token, { currentPassword, newPassword }) {
|
|
return request('/api/auth/password', {
|
|
method: 'PUT',
|
|
token,
|
|
body: { currentPassword, newPassword },
|
|
})
|
|
}
|