Guest User

Replacing Payload Auth

a guest
Jan 22nd, 2025
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
TypeScript 2.05 KB | Software | 0 0
  1. export const POST = async (request: Request) => {
  2.   const req = await createPayloadRequest({
  3.     config: configPromise,
  4.     request,
  5.   })
  6.  
  7.   await addDataAndFileToRequest(req)
  8.  
  9.   const { email, password } = req.data as { email: string; password: string }
  10.  
  11.   const payload = await getPayload({
  12.     config: configPromise,
  13.   })
  14.  
  15.   const customAuthResponse = await fetch('<custom auth endpoint>', {
  16.     method: 'POST',
  17.     headers: {
  18.       'Content-Type': 'application/json',
  19.       Accept: 'application/json',
  20.     },
  21.     body: JSON.stringify({
  22.       query: `mutation LoginMutation($password: String!, $username: String!) {
  23.         tokenAuth(password: $password, username: $username) {
  24.           user {
  25.             id
  26.           }
  27.         }
  28.       }`,
  29.       variables: { username: email, password },
  30.     }),
  31.   })
  32.  
  33.   const response = await customAuthResponse.json()
  34.  
  35.   const isSuccessful = !!response.data?.tokenAuth
  36.  
  37.   if (isSuccessful) {
  38.     const collectionConfig = payload.collections['users'].config
  39.     const _user = await findOrCreateUser(email)
  40.  
  41.     const fieldsToSign: User = {
  42.       email: _user.email,
  43.       id: _user.id,
  44.       collection: 'users',
  45.     }
  46.  
  47.     const issueAt = Math.floor(Date.now() / 1000)
  48.     const exp = issueAt + collectionConfig.auth.tokenExpiration
  49.     const jwtToken = await new SignJWT(fieldsToSign)
  50.       .setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
  51.       .setIssuedAt(issueAt)
  52.       .setExpirationTime(exp)
  53.       .sign(new TextEncoder().encode(process.env.PAYLOAD_SECRET || 'default_secret'))
  54.  
  55.     const cookie = generatePayloadCookie({
  56.       collectionAuthConfig: collectionConfig.auth,
  57.       cookiePrefix: payload.config.cookiePrefix,
  58.       token: jwtToken,
  59.     })
  60.  
  61.     return Response.json(
  62.       { status: 'SUCCESS', user: fieldsToSign, exp, token: jwtToken },
  63.       { headers: new Headers({ 'Set-Cookie': cookie }), status: 200 },
  64.     )
  65.   }
  66.  
  67.   return Response.json(
  68.     { status: 'FAILED', errors: [{ message: 'The email or password provided is incorrect.' }] },
  69.     { status: 401 },
  70.   )
  71. }
Advertisement
Add Comment
Please, Sign In to add comment