mirror of
https://github.com/vercel/commerce.git
synced 2025-07-15 00:41:21 +00:00
* Update README.md * Initial Commit * Commited Keys * GraphQL Changes * GraphQL Query * Final Changes * Changed login.ts * Made changes in login.ts * Final Changes * Refactored login.ts * SignUp Initial Checkin * logout Initial * Customer Account Initial Commit * Logout - deleted cookie * Reverted ReadMe and UserNav file * Final Changes * Resolved comments * Resolved comments 1 * Resolved comments 2 * Resolved comments 3 * Resolved comments 4 Co-authored-by: SushantJadhav <Sushant.Jadhav@kibocommerce.com>
66 lines
1.7 KiB
TypeScript
66 lines
1.7 KiB
TypeScript
import { FetcherError } from '@commerce/utils/errors'
|
|
import type { LoginEndpoint } from '.'
|
|
import { loginMutation } from '../../mutations/login-mutation'
|
|
import { prepareSetCookie } from '../../../lib/prepareSetCookie';
|
|
import { setCookies } from '../../../lib/setCookie'
|
|
import { getCookieExpirationDate } from '../../../lib/getCookieExpirationDate'
|
|
|
|
const invalidCredentials = /invalid credentials/i
|
|
|
|
const login: LoginEndpoint['handlers']['login'] = async ({
|
|
req,
|
|
res,
|
|
body: { email, password },
|
|
config,
|
|
commerce,
|
|
}) => {
|
|
|
|
if (!(email && password)) {
|
|
return res.status(400).json({
|
|
data: null,
|
|
errors: [{ message: 'Invalid request' }],
|
|
})
|
|
}
|
|
|
|
let response;
|
|
try {
|
|
|
|
const variables = { loginInput : { username: email, password }};
|
|
response = await config.fetch(loginMutation, { variables })
|
|
const { account: token } = response.data;
|
|
|
|
// Set Cookie
|
|
const cookieExpirationDate = getCookieExpirationDate(config.customerCookieMaxAgeInDays)
|
|
|
|
const authCookie = prepareSetCookie(
|
|
config.customerCookie,
|
|
JSON.stringify(token),
|
|
token.accessTokenExpiration ? { expires: cookieExpirationDate }: {},
|
|
)
|
|
setCookies(res, [authCookie])
|
|
|
|
} catch (error) {
|
|
// Check if the email and password didn't match an existing account
|
|
if (
|
|
error instanceof FetcherError &&
|
|
invalidCredentials.test(error.message)
|
|
) {
|
|
return res.status(401).json({
|
|
data: null,
|
|
errors: [
|
|
{
|
|
message:
|
|
'Cannot find an account that matches the provided credentials',
|
|
code: 'invalid_credentials',
|
|
},
|
|
],
|
|
})
|
|
}
|
|
|
|
throw error
|
|
}
|
|
|
|
res.status(200).json({ data: response })
|
|
}
|
|
|
|
export default login |