Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- export const POST = async (request: Request) => {
- const req = await createPayloadRequest({
- config: configPromise,
- request,
- })
- await addDataAndFileToRequest(req)
- const { email, password } = req.data as { email: string; password: string }
- const payload = await getPayload({
- config: configPromise,
- })
- const customAuthResponse = await fetch('<custom auth endpoint>', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- Accept: 'application/json',
- },
- body: JSON.stringify({
- query: `mutation LoginMutation($password: String!, $username: String!) {
- tokenAuth(password: $password, username: $username) {
- user {
- id
- }
- }
- }`,
- variables: { username: email, password },
- }),
- })
- const response = await customAuthResponse.json()
- const isSuccessful = !!response.data?.tokenAuth
- if (isSuccessful) {
- const collectionConfig = payload.collections['users'].config
- const _user = await findOrCreateUser(email)
- const fieldsToSign: User = {
- email: _user.email,
- id: _user.id,
- collection: 'users',
- }
- const issueAt = Math.floor(Date.now() / 1000)
- const exp = issueAt + collectionConfig.auth.tokenExpiration
- const jwtToken = await new SignJWT(fieldsToSign)
- .setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
- .setIssuedAt(issueAt)
- .setExpirationTime(exp)
- .sign(new TextEncoder().encode(process.env.PAYLOAD_SECRET || 'default_secret'))
- const cookie = generatePayloadCookie({
- collectionAuthConfig: collectionConfig.auth,
- cookiePrefix: payload.config.cookiePrefix,
- token: jwtToken,
- })
- return Response.json(
- { status: 'SUCCESS', user: fieldsToSign, exp, token: jwtToken },
- { headers: new Headers({ 'Set-Cookie': cookie }), status: 200 },
- )
- }
- return Response.json(
- { status: 'FAILED', errors: [{ message: 'The email or password provided is incorrect.' }] },
- { status: 401 },
- )
- }
Advertisement
Add Comment
Please, Sign In to add comment