Final Changes

This commit is contained in:
SushantJadhav 2021-08-25 17:57:46 +05:30
parent 56dbee6955
commit c71b2fb14d
6 changed files with 38 additions and 14 deletions

View File

@ -12,10 +12,9 @@ export type LoginEndpoint = LoginAPI['endpoint']
export const handlers: LoginEndpoint['handlers'] = { login } export const handlers: LoginEndpoint['handlers'] = { login }
const loginApi = createEndpoint<LoginAPI>({ export const loginApi = createEndpoint<LoginAPI>({
handler: loginEndpoint, handler: loginEndpoint,
handlers, handlers,
}) })
export default loginApi

View File

@ -1,16 +1,21 @@
import { FetcherError } from '@commerce/utils/errors' import { FetcherError } from '@commerce/utils/errors'
import type { LoginEndpoint } from '.' import type { LoginEndpoint } from '.'
import { loginMutation } from '../../../utils/mutations/login-mutation'
import {prepareSetCookie} from '../../utils/prepareSetCookie';
import {setCookies} from '../../utils/setCookie'
const invalidCredentials = /invalid credentials/i const invalidCredentials = /invalid credentials/i
let response;
const login: LoginEndpoint['handlers']['login'] = async ({ const login: LoginEndpoint['handlers']['login'] = async ({
req,
res, res,
body: { email, password }, body: { email, password },
config, config,
commerce, commerce,
}) => { }) => {
console.log('login hit', email, password)
// TODO: Add proper validations with something like Ajv
if (!(email && password)) { if (!(email && password)) {
return res.status(400).json({ return res.status(400).json({
data: null, data: null,
@ -18,12 +23,17 @@ const login: LoginEndpoint['handlers']['login'] = async ({
}) })
} }
try { try {
/*
const loginMutation = ` mutation loginAccount($input) { login($input) { } } ` response = await config.fetch(loginMutation, { variables: { loginInput : { username: email, password }}})
const variables = { input: { email, password } } const { account } = response.data;
const loginResponse = await config.fetch(loginMutation, { variables })
setCookie(res) const authCookie = prepareSetCookie(
*/ config.customerCookie,
JSON.stringify(response.data.account),
account.accessTokenExpiration ? { expires: new Date(account.accessTokenExpiration) }: {},
)
setCookies(res, [authCookie])
} catch (error) { } catch (error) {
// Check if the email and password didn't match an existing account // Check if the email and password didn't match an existing account
if ( if (
@ -45,7 +55,7 @@ setCookie(res)
throw error throw error
} }
res.status(200).json({ data: null }) res.status(200).json({ data: response })
} }
export default login export default login

View File

@ -0,0 +1,13 @@
export function prepareSetCookie(name: string, value: string, options: any = {}): string {
const cookieValue = [`${name}=${value}`];
if (options.maxAge) {
cookieValue.push(`Max-Age=${options.maxAge}`);
}
if (options.expires && !options.maxAge) {
cookieValue.push(`Expires=${options.expires.toUTCString()}`);
}
return cookieValue.join('; ');
}

View File

@ -0,0 +1,3 @@
export function setCookies(res: any, cookies: string[]): void {
res.setHeader('Set-Cookie', cookies);
}

View File

@ -5,14 +5,12 @@ import { useCallback } from 'react'
import { CommerceError } from '@commerce/utils/errors' import { CommerceError } from '@commerce/utils/errors'
import type { LoginHook } from '../types/login' import type { LoginHook } from '../types/login'
import useCustomer from '../customer/use-customer' import useCustomer from '../customer/use-customer'
import { loginMutation } from '../utils/mutations/login-mutation'
export default useLogin as UseLogin<typeof handler> export default useLogin as UseLogin<typeof handler>
export const handler: MutationHook<LoginHook> = { export const handler: MutationHook<LoginHook> = {
fetchOptions: { fetchOptions: {
url: '/api/login', url: '/api/login',
method: 'POST', method: 'POST'
query: loginMutation
}, },
async fetcher({ input: { email, password }, options, fetch }) { async fetcher({ input: { email, password }, options, fetch }) {
if (!(email && password)) { if (!(email && password)) {

View File

@ -6,6 +6,7 @@ mutation login($loginInput:CustomerUserAuthInfoInput!) {
userId userId
refreshToken refreshToken
refreshTokenExpiration refreshTokenExpiration
accessTokenExpiration
customerAccount { customerAccount {
id id
firstName firstName