generated from atls-lab/template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
get-kratos.session.ts
47 lines (34 loc) · 1.09 KB
/
get-kratos.session.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import type { NextApiRequest } from 'next'
import { Logger } from '@atls/logger'
import { Session } from '@ory/kratos-client'
import { IncomingMessage } from 'http'
import { getKratosClient } from './get-kratos.client'
const logger = new Logger('getKratosSession')
const getCookie = (req: IncomingMessage & NextApiRequest): string | null => {
if (req.cookies?.ory_kratos_session) {
return `ory_kratos_session=${req.cookies.ory_kratos_session}`
}
if (req.headers?.cookie?.includes('ory_kratos_session')) {
return req.headers.cookie
}
return null
}
export const getKratosSession = async (
req: IncomingMessage & NextApiRequest
): Promise<Session | null> => {
const cookie = getCookie(req)
const authorization = req.headers?.authorization
if (cookie || authorization) {
try {
const kratos = getKratosClient()
const { data: session } = await kratos.whoami(cookie, authorization)
if (session) {
logger.debug(session)
return session
}
} catch (error) {
logger.error(error)
}
}
return null
}