|
3 | 3 | importtype{CollectionSlug}from'payload' |
4 | 4 |
|
5 | 5 | import{headersasnextHeaders}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 | | -exportasyncfunctionrefresh({collection,config }: {collection: CollectionSlug;config: any}){ |
| 11 | +exportasyncfunctionrefresh({ config }: {config: any}){ |
12 | 12 | constpayload=awaitgetPayload({ config }) |
13 | | -constauthConfig=payload.collections[collection]?.config.auth |
| 13 | +constheaders=awaitnextHeaders() |
| 14 | +constresult=awaitpayload.auth({ headers }) |
14 | 15 |
|
15 | | -if(!authConfig){ |
| 16 | +if(!result.user){ |
| 17 | +thrownewError('Cannot refresh token: user not authenticated') |
| 18 | +} |
| 19 | + |
| 20 | +constcollection: CollectionSlug|undefined=result.user.collection |
| 21 | +constcollectionConfig=payload.collections[collection] |
| 22 | + |
| 23 | +if(!collectionConfig?.config.auth){ |
16 | 24 | thrownewError(`No auth config found for collection: ${collection}`) |
17 | 25 | } |
18 | 26 |
|
19 | | -const{ user }=awaitpayload.auth({headers: awaitnextHeaders()}) |
| 27 | +constreq=awaitcreateLocalReq({user: result.user},payload) |
20 | 28 |
|
21 | | -if(!user){ |
22 | | -thrownewError('User not authenticated') |
| 29 | +constrefreshResult=awaitrefreshOperation({ |
| 30 | +collection: collectionConfig, |
| 31 | + req, |
| 32 | +}) |
| 33 | + |
| 34 | +if(!refreshResult){ |
| 35 | +return{message: 'Token refresh failed',success: false} |
23 | 36 | } |
24 | 37 |
|
25 | 38 | constexistingCookie=awaitgetExistingAuthToken(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 | awaitsetPayloadAuthCookie({ |
32 | | - authConfig, |
| 44 | +authConfig: collectionConfig.config.auth, |
33 | 45 | cookiePrefix: payload.config.cookiePrefix, |
34 | 46 | token: existingCookie.value, |
35 | 47 | }) |
|
0 commit comments