({ config }: { config: MaybePromise<SanitizedConfig> })
| 9 | import { setPayloadAuthCookie } from '../utilities/setPayloadAuthCookie.js' |
| 10 | |
| 11 | export async function refresh({ config }: { config: MaybePromise<SanitizedConfig> }) { |
| 12 | const payload = await getPayload({ config, cron: true }) |
| 13 | const headers = await nextHeaders() |
| 14 | const result = await payload.auth({ headers }) |
| 15 | |
| 16 | if (!result.user) { |
| 17 | throw new Error('Cannot refresh token: user not authenticated') |
| 18 | } |
| 19 | |
| 20 | const existingCookie = await getExistingAuthToken(payload.config.cookiePrefix) |
| 21 | if (!existingCookie) { |
| 22 | return { message: 'No valid token found to refresh', success: false } |
| 23 | } |
| 24 | |
| 25 | const collection: CollectionSlug | undefined = result.user.collection |
| 26 | const collectionConfig = payload.collections[collection] |
| 27 | |
| 28 | if (!collectionConfig?.config.auth) { |
| 29 | throw new Error(`No auth config found for collection: ${collection}`) |
| 30 | } |
| 31 | |
| 32 | const req = await createLocalReq({ user: result.user }, payload) |
| 33 | |
| 34 | const refreshResult = await refreshOperation({ |
| 35 | collection: collectionConfig, |
| 36 | req, |
| 37 | }) |
| 38 | |
| 39 | if (!refreshResult) { |
| 40 | return { message: 'Token refresh failed', success: false } |
| 41 | } |
| 42 | |
| 43 | await setPayloadAuthCookie({ |
| 44 | authConfig: collectionConfig.config.auth, |
| 45 | cookiePrefix: payload.config.cookiePrefix, |
| 46 | token: refreshResult.refreshedToken, |
| 47 | }) |
| 48 | |
| 49 | return { message: 'Token refreshed successfully', success: true } |
| 50 | } |
no test coverage detected
searching dependent graphs…