|
3 | 3 | import type { CollectionSlug } from 'payload' |
4 | 4 |
|
5 | 5 | import { headers as nextHeaders } from 'next/headers.js' |
6 | | -import { getPayload } from 'payload' |
| 6 | +import { createLocalReq, getPayload, refreshOperation } from 'payload' |
7 | 7 |
|
8 | 8 | import { getExistingAuthToken } from '../utilities/getExistingAuthToken.js' |
9 | 9 | import { setPayloadAuthCookie } from '../utilities/setPayloadAuthCookie.js' |
10 | 10 |
|
11 | | -export async function refresh({ collection, config }: { collection: CollectionSlug; config: any }) { |
| 11 | +export async function refresh({ config }: { config: any }) { |
12 | 12 | const payload = await getPayload({ config }) |
13 | | - const authConfig = payload.collections[collection]?.config.auth |
| 13 | + const headers = await nextHeaders() |
| 14 | + const result = await payload.auth({ headers }) |
14 | 15 |
|
15 | | - if (!authConfig) { |
| 16 | + if (!result.user) { |
| 17 | + throw new Error('Cannot refresh token: user not authenticated') |
| 18 | + } |
| 19 | + |
| 20 | + const collection: CollectionSlug | undefined = result.user.collection |
| 21 | + const collectionConfig = payload.collections[collection] |
| 22 | + |
| 23 | + if (!collectionConfig?.config.auth) { |
16 | 24 | throw new Error(`No auth config found for collection: ${collection}`) |
17 | 25 | } |
18 | 26 |
|
19 | | - const { user } = await payload.auth({ headers: await nextHeaders() }) |
| 27 | + const req = await createLocalReq({ user: result.user }, payload) |
20 | 28 |
|
21 | | - if (!user) { |
22 | | - throw new Error('User not authenticated') |
| 29 | + const refreshResult = await refreshOperation({ |
| 30 | + collection: collectionConfig, |
| 31 | + req, |
| 32 | + }) |
| 33 | + |
| 34 | + if (!refreshResult) { |
| 35 | + return { message: 'Token refresh failed', success: false } |
23 | 36 | } |
24 | 37 |
|
25 | 38 | const existingCookie = await getExistingAuthToken(payload.config.cookiePrefix) |
26 | | - |
27 | 39 | if (!existingCookie) { |
28 | | - return { message: 'No valid token found', success: false } |
| 40 | + return { message: 'No valid token found to refresh', success: false } |
29 | 41 | } |
30 | 42 |
|
31 | 43 | await setPayloadAuthCookie({ |
32 | | - authConfig, |
| 44 | + authConfig: collectionConfig.config.auth, |
33 | 45 | cookiePrefix: payload.config.cookiePrefix, |
34 | 46 | token: existingCookie.value, |
35 | 47 | }) |
|
0 commit comments