Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/app/dashboard/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import useDashboardStore from '@/store/useDashboardStore'
* 주스탠드에 저장된 대시보드 목록에서 dashboardid 로 title 가져올 수 잇을 듯
*/
export default function UserDashboardLayout({ children }: PropsWithChildren) {
useRedirect({ requireAuth: true })
// useRedirect({ requireAuth: true })

const { id } = useParams()
const { dashboards, dashboard, setDashboard } = useDashboardStore()
Expand Down
26 changes: 9 additions & 17 deletions src/app/login/components/LoginForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import { getDashboardList } from '@/lib/dashboardsApi'
import useDashboardStore from '@/store/useDashboardStore'
import useModalStore from '@/store/useModalStore'

import loginAction from '../loginAction'

export interface LoginFormValue {
email: string
password: string
Expand All @@ -29,30 +31,20 @@ export default function LoginForm() {
} = useForm<LoginFormValue>()

const router = useRouter()

const { openModal } = useModalStore()
const { setDashboards } = useDashboardStore()

const [pwdVisible, togglePwd] = useToggle(false)
const passwordType = pwdVisible ? 'text' : 'password'

const onSubmit = async (data: LoginFormValue) => {
try {
const response = await api.post('auth/login', data)
const { accessToken, user } = response.data
sessionStorage.setItem('accessToken', accessToken)
sessionStorage.setItem('user', JSON.stringify(user))
const dashboards = await getDashboardList()
setDashboards(dashboards)
router.push('/mydashboard')
} catch (error) {
let loginErrorMessage = ''
if (axios.isAxiosError(error)) {
loginErrorMessage = error.response?.data.message
} else {
loginErrorMessage =
'서버에 문제가 있는거 같아요. 잠시 후에 다시 시도해보시겠어요?'
}
openModal(<ConfirmModalContent message={loginErrorMessage} />)
// 로그인 액션 실행
const errMsg = await loginAction(data)

// 에러 메시지 팝업
if (errMsg) {
openModal(<ConfirmModalContent message={errMsg} />)
}
}

Expand Down
29 changes: 29 additions & 0 deletions src/app/login/loginAction.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
'use server'
import { cookies } from 'next/headers'
import { redirect } from 'next/navigation'

import api from '@/lib/axiosServer'

import { LoginFormValue } from './components/LoginForm'

export default async function loginAction(data: LoginFormValue) {
// 백엔드 요청
try {
const response = await api.post('/auth/login', data, {})
const { accessToken, user } = response.data

// 가져온 json token 쿠키 설정 하기
cookies().set('Authorization', accessToken, {
secure: true,
// httpOnly: true,
expires: new Date(Date.now() + 24 * 60 * 60 * 1000 * 3),
// path: '/',
sameSite: 'strict',
})
} catch (error: any) {
return error.response?.data?.message || error.message
}
Comment on lines +1 to +25
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

서버 액션 이렇게 적용하는 거군요...!
감사합니다 큰 공부가 되네요


// 로그인 여부에 따라 redirect
redirect('/mydashboard')
}
2 changes: 1 addition & 1 deletion src/app/mydashboard/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ type PaginationAction = 'prev' | 'next'
const ITEM_PER_PAGE = 5

export default function MyDashboard() {
useRedirect({ requireAuth: true })
// useRedirect({ requireAuth: true })

const { openModal } = useModalStore()
const { dashboards } = useDashboardStore()
Expand Down
2 changes: 1 addition & 1 deletion src/app/mypage/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import PasswordEditForm from './components/PasswordEditForm'
import ProfileEditForm from './components/ProfileEditForm'

export default function MyPagePage() {
useRedirect({ requireAuth: true })
// useRedirect({ requireAuth: true })

const handleGoBack = useGoBack()

Expand Down
2 changes: 1 addition & 1 deletion src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import useRedirect from '@/hooks/useRedirect'
import { Providers } from './providers'

export default function Home() {
useRedirect({ requireAuth: false })
// useRedirect({ requireAuth: false })

return (
<>
Expand Down
2 changes: 1 addition & 1 deletion src/app/signup/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import useRedirect from '@/hooks/useRedirect'
import AuthPageLayout from '@/layouts/AuthPageLayout'

export default function SignupPage() {
useRedirect({ requireAuth: false })
// useRedirect({ requireAuth: false })
return (
<AuthPageLayout page='signup'>
<SignupForm />
Expand Down
3 changes: 3 additions & 0 deletions src/components/UserProfile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export default function UserProfile() {
try {
const response = await api.get('users/me')
setUser(response.data)
sessionStorage.setItem('user', response.data)
} catch (error) {
throw error
}
Expand All @@ -31,6 +32,8 @@ export default function UserProfile() {
router.push('/login')
setUser(null)
sessionStorage.clear()

document.cookie = `Authorization=; Max-Age=-99999999;`
}

useEffect(() => {
Expand Down
19 changes: 11 additions & 8 deletions src/lib/axiosInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,21 @@ const api = axios.create({
'Content-Type': 'application/json',
},
// withCredentials: true,
// timeout: 10000, // 요청 제한 시간 설정 (밀리초)
})

let accessToken: string = ''

export const setAccessToken = (token: string) => {
accessToken = token
}

api.interceptors.request.use(
config => {
const token = sessionStorage.getItem('accessToken')
function getCookie(name: string) {
const value = `; ${document.cookie}`
const parts = value.split(`; ${name}=`)

if (parts) {
return parts[1].split(';').shift()
}
}

const token = getCookie('Authorization')
console.log(token)
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
Expand Down
29 changes: 29 additions & 0 deletions src/lib/axiosServer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
'use server'

import axios from 'axios'
import { cookies } from 'next/headers'

const api = axios.create({
baseURL: 'https://sp-taskify-api.vercel.app/7-2',
headers: {
'Content-Type': 'application/json',
},
withCredentials: true,
})

api.interceptors.request.use(
config => {
console.log('interceptor')
const token = cookies().get('Authorization')

if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
},
error => {
return Promise.reject(error)
}
)

export default api
19 changes: 19 additions & 0 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { cookies } from 'next/headers'
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'

export async function middleware(request: NextRequest) {
// 쿠키 확인
const cookie = cookies().get('Authorization')
if (!cookie) {
return NextResponse.redirect(new URL('/login', request.url))
}

if (cookie && request.nextUrl.pathname === '/') {
return NextResponse.redirect(new URL('/mydashboard', request.url))
}
}

export const config = {
matcher: ['/', '/mydashboard/:path*', '/dashboard/:path*', '/mypage/:path*'],
}