From 6ae0b071b7c9bee907771b2595d4a1ab8544d178 Mon Sep 17 00:00:00 2001 From: SushantJadhav Date: Thu, 26 Aug 2021 11:59:03 +0530 Subject: [PATCH] SignUp Initial Checkin --- components/common/UserNav/UserNav.tsx | 6 +- .../api/endpoints/signup/index.ts | 19 +++- .../api/endpoints/signup/signup.ts | 90 +++++++++++++++++++ .../api/mutations/signup-mutation.ts | 41 +++++++++ framework/kibocommerce/auth/use-signup.tsx | 45 +++++++--- framework/kibocommerce/types/signup.ts | 1 + 6 files changed, 189 insertions(+), 13 deletions(-) create mode 100644 framework/kibocommerce/api/endpoints/signup/signup.ts create mode 100644 framework/kibocommerce/api/mutations/signup-mutation.ts create mode 100644 framework/kibocommerce/types/signup.ts diff --git a/components/common/UserNav/UserNav.tsx b/components/common/UserNav/UserNav.tsx index 07e1af04d..de525b1e9 100644 --- a/components/common/UserNav/UserNav.tsx +++ b/components/common/UserNav/UserNav.tsx @@ -40,8 +40,8 @@ const UserNav: FC = ({ className }) => { )} - -
  • + {process.env.COMMERCE_CUSTOMERAUTH_ENABLED && ( +
  • {customer ? ( ) : ( @@ -54,6 +54,8 @@ const UserNav: FC = ({ className }) => { )}
  • + )} + diff --git a/framework/kibocommerce/api/endpoints/signup/index.ts b/framework/kibocommerce/api/endpoints/signup/index.ts index 491bf0ac9..3eda94d06 100644 --- a/framework/kibocommerce/api/endpoints/signup/index.ts +++ b/framework/kibocommerce/api/endpoints/signup/index.ts @@ -1 +1,18 @@ -export default function noopApi(...args: any[]): void {} +import { GetAPISchema, createEndpoint } from '@commerce/api' +import signupEndpoint from '@commerce/api/endpoints/signup' +import type { SignupSchema } from '../../../types/signup' +import type { KiboCommerceAPI } from '../..' +import signup from './signup' + +export type SignupAPI = GetAPISchema + +export type SignupEndpoint = SignupAPI['endpoint'] + +export const handlers: SignupEndpoint['handlers'] = { signup } + +const singupApi = createEndpoint({ + handler: signupEndpoint, + handlers, +}) + +export default singupApi diff --git a/framework/kibocommerce/api/endpoints/signup/signup.ts b/framework/kibocommerce/api/endpoints/signup/signup.ts new file mode 100644 index 000000000..87900a8be --- /dev/null +++ b/framework/kibocommerce/api/endpoints/signup/signup.ts @@ -0,0 +1,90 @@ +import Cookies from 'js-cookie' +import { FetcherError } from '@commerce/utils/errors' +import type { SignupEndpoint } from '.' +import { registerUserMutation, registerUserLoginMutation } from '../../mutations/signup-mutation' +import {prepareSetCookie} from '../../../lib/prepareSetCookie'; +import {setCookies} from '../../../lib/setCookie' + +const invalidCredentials = /invalid credentials/i + +let response; + +const signup: SignupEndpoint['handlers']['signup'] = async ({ + req, + res, + body: { email, password, firstName, lastName }, + config, + commerce, +}) => { + + if (!(email && password)) { + return res.status(400).json({ + data: null, + errors: [{ message: 'Invalid request' }], + }) + } + try { + + // Register user + const registerUserVariables = { + customerAccountInput: { + emailAddress: email, + firstName: firstName, + lastName: lastName, + acceptsMarketing: true, + isActive: true, + id: 0 + } + } + + const registerUserResponse = await config.fetch(registerUserMutation, { variables: registerUserVariables}) + const accountId = registerUserResponse.data?.account?.id; + + // Login user + const registerUserLoginVairables = { + accountId: accountId, + customerLoginInfoInput: { + emailAddress: email, + username: email, + password: password, + isImport: false + } + } + + response = await config.fetch(registerUserLoginMutation, { variables: registerUserLoginVairables}) + const { account: token } = response.data; + + // Set Cookie + const authCookie = prepareSetCookie( + config.customerCookie, + JSON.stringify(token), + token.accessTokenExpiration ? { expires: new Date(token.accessTokenExpiration) }: {}, + ) + + 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 signup \ No newline at end of file diff --git a/framework/kibocommerce/api/mutations/signup-mutation.ts b/framework/kibocommerce/api/mutations/signup-mutation.ts new file mode 100644 index 000000000..27311a56e --- /dev/null +++ b/framework/kibocommerce/api/mutations/signup-mutation.ts @@ -0,0 +1,41 @@ + +const registerUserMutation = ` +mutation registerUser($customerAccountInput: CustomerAccountInput!) { + account:createCustomerAccount(customerAccountInput:$customerAccountInput) { + emailAddress + userName + firstName + lastName + localeCode + userId + id + isAnonymous + attributes { + values + fullyQualifiedName + } + } +}`; + +const registerUserLoginMutation = ` +mutation registerUserLogin($accountId: Int!, $customerLoginInfoInput: CustomerLoginInfoInput!) { + account:createCustomerAccountLogin(accountId:$accountId, customerLoginInfoInput:$customerLoginInfoInput) { + accessToken + accessTokenExpiration + refreshToken + refreshTokenExpiration + userId + customerAccount { + id + emailAddress + firstName + userName + } + } +}`; + +export { + registerUserMutation, + registerUserLoginMutation +}; + diff --git a/framework/kibocommerce/auth/use-signup.tsx b/framework/kibocommerce/auth/use-signup.tsx index e9ad13458..28c144152 100644 --- a/framework/kibocommerce/auth/use-signup.tsx +++ b/framework/kibocommerce/auth/use-signup.tsx @@ -1,19 +1,44 @@ import { useCallback } from 'react' -import useCustomer from '../customer/use-customer' -import { MutationHook } from '@commerce/utils/types' +import type { MutationHook } from '@commerce/utils/types' +import { CommerceError } from '@commerce/utils/errors' import useSignup, { UseSignup } from '@commerce/auth/use-signup' +import type { SignupHook } from '../types/signup' +import useCustomer from '../customer/use-customer' export default useSignup as UseSignup -export const handler: MutationHook = { +export const handler: MutationHook = { fetchOptions: { - query: '', + url: '/api/signup', + method: 'POST', }, - async fetcher() { - return null + async fetcher({ + input: { firstName, lastName, email, password }, + options, + fetch, + }) { + if (!(firstName && lastName && email && password)) { + throw new CommerceError({ + message: + 'A first name, last name, email and password are required to signup', + }) + } + + return fetch({ + ...options, + body: { firstName, lastName, email, password }, + }) + }, + useHook: ({ fetch }) => () => { + const { revalidate } = useCustomer() + + return useCallback( + async function signup(input) { + const data = await fetch({ input }) + // await revalidate() + return data + }, + [fetch, revalidate] + ) }, - useHook: - ({ fetch }) => - () => - () => {}, } diff --git a/framework/kibocommerce/types/signup.ts b/framework/kibocommerce/types/signup.ts new file mode 100644 index 000000000..58543c6f6 --- /dev/null +++ b/framework/kibocommerce/types/signup.ts @@ -0,0 +1 @@ +export * from '@commerce/types/signup'