Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

인증관련 테스트 오류사항 변경 #28

Merged
merged 1 commit into from
Feb 15, 2024
Merged
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
30 changes: 21 additions & 9 deletions lib/namui-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export class NamuiApi {
private static instanceOption: CreateAxiosDefaults = {
baseURL: process.env.NEXT_PUBLIC_API_URL,
}
private static accessToken: string
private static accessToken: string = ''
/**
* @param provider
* @returns
Expand All @@ -24,7 +24,7 @@ export class NamuiApi {
method: 'POST',
url: `/api/v1/auth/login`,
data: {
provider,
provider: provider.toUpperCase(),
code,
},
})
Expand All @@ -40,20 +40,27 @@ export class NamuiApi {
private static async getNewToken() {
const serverURL = new URL(process.env.NEXT_PUBLIC_API_URL)
serverURL.pathname = '/api/v1/refresh'
const response = await fetch(serverURL).then(
(res) =>
res.json() as Promise<{
const response = await fetch(serverURL).then((res) => {
if (res.status > 400) {
throw raiseNamuiErrorFromStatus(res.status)
} else {
return res.json() as Promise<{
data: {
accessToken: 'string'
}
}>,
)
}>
}
})
NamuiApi.setToken(response.data.accessToken)
return response.data.accessToken
}

private static injectInterceptor(instance: AxiosInstance) {
const onRequest = (config: AxiosRequestConfig): AxiosRequestConfig => {
if (process.env.NODE_ENV === 'development') {
console.log(`[LOG-Request] : ${config.url}`)
console.log(`[LOG-Request] : ${config.headers}`)
}
const accessToken = NamuiApi.accessToken

config.headers = {
Expand All @@ -72,7 +79,11 @@ export class NamuiApi {
const onResponse = (config: AxiosResponse) => config.data
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const onErrorResponse = async (error: any) => {
console.log(error)
if (process.env.NODE_ENV === 'development') {
console.log(
`[LOG-RESPONSE-ERROR] : PATH-${error.request.path} ${error?.message}`,
)
}
if (error.response?.status === 401) {
const newAccessToken = await this.getNewToken()
error.config.headers = {
Expand All @@ -84,6 +95,7 @@ export class NamuiApi {
const errorInstance = axios.isAxiosError(error)
? raiseNamuiErrorFromStatus(error.status || error.response?.status)
: error

return Promise.reject(errorInstance)
}

Expand Down Expand Up @@ -112,6 +124,6 @@ export class NamuiApi {

private static async handler<Response>(config: AxiosRequestConfig) {
const instance = this.getInstance()
return instance<Response>(config)
return instance(config) as Response
}
}
6 changes: 3 additions & 3 deletions pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ export default function NamuiWikiApp({
return getLayout(
<SessionProvider
session={session}
onSessionChange={() => {
NamuiApi.setToken(session?.token?.accessToken)
onSessionChange={(newSession) => {
NamuiApi.setToken(newSession?.token?.accessToken)
}}
>
<Component {...pageProps} />
Expand All @@ -63,7 +63,7 @@ NamuiWikiApp.getInitialProps = async (
method: 'GET',
headers: headers,
})
const user = await res.json()
const user = (await res.json()) ?? {}
return {
...ctx,
session: {
Expand Down
38 changes: 13 additions & 25 deletions pages/api/auth/[provider].ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { AUTH } from '@/constants'
import { BadRequestError, isNamuiError } from '@/error'
import { Oauth, Provider } from '@/lib/auth'
import { BadRequestError, InternalServerError, isNamuiError } from '@/error'
import { Provider } from '@/lib/auth'
import { NamuiApi } from '@/lib/namui-api'
import { withError } from '@/lib/server/utils'
import withHandler from '@/lib/server/with-handler'
import { serialize } from 'cookie'
import type { NextApiRequest, NextApiResponse } from 'next'
Expand All @@ -11,47 +10,36 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
try {
const { provider, code } = req.query
const parsedProvider = Provider.safeParse(provider)
if (!parsedProvider.success) {
return withError(res, {
status: 400,
message: BadRequestError.message,
})
if (!parsedProvider.success || !code) {
throw new BadRequestError()
}

const url = Oauth.getAuthorizationURL(parsedProvider.data)
if (!url || !code) {
return withError(res, {
status: 400,
message: BadRequestError.message,
})
}

const {
data: { accessToken, refreshToken },
} = await NamuiApi.signIn(parsedProvider.data, code)
const { accessToken, refreshToken } = await NamuiApi.signIn(
parsedProvider.data,
code,
)

res.setHeader('Set-Cookie', [
serialize('accessToken', accessToken, {
path: '/',
httpOnly: true,
secure: true,
sameSite: 'none',
sameSite: 'lax',
maxAge: AUTH.ACCESS_EXPIRED_TIME,
}),
serialize('refreshToken', refreshToken, {
path: '/',
httpOnly: true,
secure: true,
sameSite: 'none',
sameSite: 'lax',
maxAge: AUTH.REFRESH_EXPIRED_TIME,
}),
])
res.status(200).redirect('/')
} catch (err) {
if (isNamuiError(err)) {
return res.redirect(307, `/?err=${err.name}`).json({ ok: true })
}
const error = isNamuiError(err) ? err : new InternalServerError()
return res.redirect(307, `/?err=${error.name}`).json({})
}
res.status(200).redirect('/')
}

export default withHandler({
Expand Down
6 changes: 3 additions & 3 deletions provider/session-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export type SessionContextValue<R extends boolean = false> = R extends true
}

type SessionHandler = {
signin: (args: { provider: ProviderType; callbackUrl?: string }) => void
signin: (args?: { provider: ProviderType; callbackUrl?: string }) => void
signout: () => Promise<void>
}
interface SessionProviderProps extends SessionContextType {
Expand Down Expand Up @@ -65,7 +65,7 @@ export const SessionProvider = ({
try {
if (session?.token?.accessToken) {
const newSession = await NamuiApi.getUserData()
setSession((prev) => ({ ...prev, user: newSession.data }))
setSession((prev) => ({ ...prev, user: newSession }))
}
} catch (error) {
setSession(null)
Expand Down Expand Up @@ -132,7 +132,7 @@ export const useSession = <R extends boolean>(options?: {
const { required } = options ?? {}

const signin: SessionHandler['signin'] = useCallback((args) => {
const { provider, callbackUrl } = args
const { provider = 'kakao', callbackUrl } = args ?? {}
if (callbackUrl) {
sessionStorage.setItem('callbackUrl', callbackUrl)
}
Expand Down
Loading