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

[v14] TripleWeb에 sessionProvider 추가 #2981

Merged
merged 8 commits into from
Nov 13, 2023
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
5 changes: 4 additions & 1 deletion packages/triple-web-binding-nextjs-pages/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,10 @@
]
},
"dependencies": {
"ua-parser-js": "^1.0.36"
"@titicaca/fetcher": "^13.8.1",
"@titicaca/view-utilities": "^13.8.1",
"ua-parser-js": "^1.0.36",
"universal-cookie": "^4.0.4"
},
"devDependencies": {
"@titicaca/triple-web": "workspace:*",
Expand Down
146 changes: 146 additions & 0 deletions packages/triple-web-binding-nextjs-pages/src/session.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import { NextPageContext } from 'next'
import {
GET_USER_REQUEST_URL,
SessionProviderValue,
SessionUser,
checkClientApp,
} from '@titicaca/triple-web'
import {
ssrFetcherize,
captureHttpError,
authFetcherize,
post,
get,
} from '@titicaca/fetcher'
import Cookies from 'universal-cookie'

/**
* - app (server-side): refresh X
* - app (client-side): refresh X
* - browser (server-side) refresh O
* - browser (client-side) refresh O
* @returns
*/
export async function getSession(
ctx: NextPageContext,
): Promise<SessionProviderValue> {
const userAgent = ctx.req
? ctx.req.headers['user-agent'] ?? ''
: window.navigator.userAgent

const isClientApp = checkClientApp(userAgent)

const user = await fetchUser(ctx, isClientApp)

return {
initialSession: {
user,
},
}
}

async function fetchUser(ctx: NextPageContext, isClientApp: boolean) {
if (ctx.req) {
// Server-side

// 세션이 없으면 fetch를 스킵합니다.
const cookies = new Cookies(ctx.req.headers.cookie)

let hasSession = false

if (isClientApp) {
hasSession = !!cookies.get('x-soto-session')
} else {
hasSession = !!ctx.req.headers['x-triple-web-login']
if (process.env.NODE_ENV !== 'production') {
hasSession = !!cookies.get('TP_SE')
}
}

if (!hasSession) {
return null
}

// fetch 시작
const ssrFetcherizeOptions = {
apiUriBase: process.env.API_URI_BASE || '',
cookie: ctx.req.headers.cookie,
}

if (isClientApp) {
const finalFetcher = ssrFetcherize(get, ssrFetcherizeOptions)

const response = await finalFetcher<SessionUser>(GET_USER_REQUEST_URL)

if (response.status !== 401) {
captureHttpError(response)
}

if (response.ok === false) {
return null
}

return response.parsedBody
} else {
const finalFetcher = authFetcherize(
ssrFetcherize(get, ssrFetcherizeOptions),
{
refresh: () =>
ssrFetcherize(
post,
ssrFetcherizeOptions,
)('/api/users/web-session/token'),
},
)

const response = await finalFetcher<SessionUser>(GET_USER_REQUEST_URL)

if (response === 'NEED_LOGIN') {
return null
}

captureHttpError(response)

if (response.ok === false) {
return null
}

return response.parsedBody
}
} else {
// Client-side
if (isClientApp) {
const finalFetcher = get

const response = await finalFetcher<SessionUser>(GET_USER_REQUEST_URL)

if (response.status !== 401) {
captureHttpError(response)
}

if (response.ok === false) {
return null
}

return response.parsedBody
} else {
const finalFetcher = authFetcherize(get, {
refresh: () => post('/api/users/web-session/token'),
})

const response = await finalFetcher<SessionUser>(GET_USER_REQUEST_URL)

if (response === 'NEED_LOGIN') {
return null
}

captureHttpError(response)

if (response.ok === false) {
return null
}

return response.parsedBody
}
}
}
2 changes: 2 additions & 0 deletions packages/triple-web-binding-nextjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@
]
},
"dependencies": {
"@titicaca/fetcher": "^13.8.1",
"@titicaca/view-utilities": "^13.8.1",
"server-only": "^0.0.1",
"ua-parser-js": "^1.0.36"
},
Expand Down
109 changes: 109 additions & 0 deletions packages/triple-web-binding-nextjs/src/session.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import 'server-only'

import { cookies, headers } from 'next/headers'
import {
ssrFetcherize,
captureHttpError,
authFetcherize,
post,
get,
} from '@titicaca/fetcher'
import {
GET_USER_REQUEST_URL,
checkClientApp,
SessionUser,
Session,
} from '@titicaca/triple-web'

/**
* - app: refresh X
* - browser: refresh O
* @returns
*/
export async function getSession(): Promise<Session> {
const headersList = headers()
const userAgent = headersList.get('user-agent') ?? ''

const isClientApp = checkClientApp(userAgent)
const hasSession = checkSession(isClientApp)

if (!hasSession) {
return {
user: null,
}
}

const user = await fetchUser(isClientApp)

return {
user,
}
}

function checkSession(isClientApp: boolean) {
const headersList = headers()
const cookiesList = cookies()

let hasSession = false

if (isClientApp) {
hasSession = cookiesList.has('x-soto-session')
} else {
hasSession = headersList.has('x-triple-web-login')

if (process.env.NODE_ENV !== 'production') {
hasSession = cookiesList.has('TP_SE')
}
}

return hasSession
}

async function fetchUser(isClientApp: boolean) {
const headersList = headers()

const ssrFetcherizeOptions = {
apiUriBase: process.env.API_URI_BASE || '',
cookie: headersList.get('cookie') ?? undefined,
}

if (isClientApp) {
const finalFetcher = ssrFetcherize(get, ssrFetcherizeOptions)

const response = await finalFetcher<SessionUser>(GET_USER_REQUEST_URL)

if (response.status !== 401) {
captureHttpError(response)
}

if (response.ok === false) {
return null
}

return response.parsedBody
} else {
const finalFetcher = authFetcherize(
ssrFetcherize(get, ssrFetcherizeOptions),
{
refresh: () =>
ssrFetcherize(
post,
ssrFetcherizeOptions,
)('/api/users/web-session/token'),
},
)
const response = await finalFetcher<SessionUser>(GET_USER_REQUEST_URL)

if (response === 'NEED_LOGIN') {
return null
}

captureHttpError(response)

if (response.ok === false) {
return null
}

return response.parsedBody
}
}
4 changes: 4 additions & 0 deletions packages/triple-web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,11 @@
]
},
"dependencies": {
"@titicaca/fetcher": "^13.9.0",
"@titicaca/view-utilities": "^13.9.0",
"@types/qs": "^6.9.8",
"@types/semver": "^7.5.3",
"qs": "^6.11.2",
"semver": "^7.5.4",
"ua-parser-js": "^1.0.36"
},
Expand Down
1 change: 1 addition & 0 deletions packages/triple-web/src/contexts/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './client-app'
export * from './env'
export * from './session'
export * from './user-agent'
71 changes: 71 additions & 0 deletions packages/triple-web/src/contexts/session.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import {
Dispatch,
PropsWithChildren,
SetStateAction,
createContext,
useState,
} from 'react'

export interface SessionUser {
name: string
provider: Provider
country: string
lang: string
unregister: boolean | null
photo: string
mileage: Mileage
uid: string
}

type Provider = 'TRIPLE' | 'NAVER' | 'KAKAO' | 'FACEBOOK' | 'APPLE'

interface Mileage {
badges: {
icon: {
imageUrl: string
}
}[]
level: number
point: number
}

export interface Session {
user: SessionUser | null
}

export const SessionStateContext = createContext<Session | undefined>(undefined)
export const SessionUpdaterContext = createContext<
Dispatch<SetStateAction<Session>> | undefined
>(undefined)

export interface SessionProviderValue {
initialSession: Session
}

export interface SessionProviderProps extends PropsWithChildren {
value: SessionProviderValue | undefined
}

export function SessionProvider({ children, value }: SessionProviderProps) {
if (value === undefined) {
return <>{children}</>
}

return <InnerSessionProvider value={value}>{children}</InnerSessionProvider>
}

interface InnerSessionProviderProps extends PropsWithChildren {
value: SessionProviderValue
}

function InnerSessionProvider({ children, value }: InnerSessionProviderProps) {
const [session, setSession] = useState(value.initialSession)

return (
<SessionStateContext.Provider value={session}>
<SessionUpdaterContext.Provider value={setSession}>
{children}
</SessionUpdaterContext.Provider>
</SessionStateContext.Provider>
)
}
2 changes: 2 additions & 0 deletions packages/triple-web/src/hooks/client-app/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './use-client-app'
export * from './use-feature-flag'
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useContext } from 'react'

import { ClientAppContext } from '../contexts/client-app'
import { ClientAppContext } from '../../contexts/client-app'

export function useClientApp() {
const context = useContext(ClientAppContext)
Expand Down
1 change: 1 addition & 0 deletions packages/triple-web/src/hooks/env/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './use-env'
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useContext } from 'react'

import { EnvContext } from '../contexts'
import { EnvContext } from '../../contexts'

export function useEnv() {
const context = useContext(EnvContext)
Expand Down
7 changes: 4 additions & 3 deletions packages/triple-web/src/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './use-client-app'
export * from './use-env'
export * from './use-user-agent'
export * from './client-app'
export * from './env'
export * from './session'
export * from './user-agent'
3 changes: 3 additions & 0 deletions packages/triple-web/src/hooks/session/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from './use-login'
export * from './use-logout'
export * from './use-session'
Loading
Loading