Skip to content

@W-17550783 - [Passwordless login] Redirect customer to page prior to login #2221

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,8 @@ export const AuthModal = ({

const handlePasswordlessLogin = async (email) => {
try {
// Save the path where the user logged in
window.localStorage.setItem('returnToPage', window.location.pathname)
Copy link
Contributor

@alexvuong alexvuong Jan 28, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What was the reason behind using localStorage? Can we use a query param to avoid having to handle this variable? Something like https://pwa-kit.storefront.com/login?token&1234&redirectTo=/checkout

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are a few benefits of using query param than localStorage. One of which is it is not tied to a device. Imagine a shopper clicks login with link on a laptop, and then they check email and click on the magic link to logic. Can they resume their shopping from their?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@alexvuong To send the redirect_url I would have to pass it in as part of the callbackURL param when calling the 1st authorizePasswordless API call so I thought this method would be more straightforward (though Blair did say that passing in the query params as part of the callback URL should be fine).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@yunakim714 Why would we need to pass it into the callbackURL ? 🤔

Copy link
Contributor

@alexvuong alexvuong Jan 28, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd suggest we try the query param solution if possible since the localStorage can potential cause more bugs. There are some edge cases that will potentially disable the redirection. Say, what if users clear their storage before they click on the magic link? or when they use incognito browser?

await authorizePasswordlessLogin.mutateAsync({userid: email})
setCurrentView(EMAIL_VIEW)
} catch (error) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import Account from '@salesforce/retail-react-app/app/pages/account'
import {rest} from 'msw'
import {mockedRegisteredCustomer} from '@salesforce/retail-react-app/app/mocks/mock-data'
import * as ReactHookForm from 'react-hook-form'
import {AuthHelpers} from '@salesforce/commerce-sdk-react'

jest.setTimeout(60000)

Expand Down Expand Up @@ -47,6 +48,21 @@ const mockRegisteredCustomer = {
login: 'customer@test.com'
}

const mockAuthHelperFunctions = {
[AuthHelpers.AuthorizePasswordless]: {mutateAsync: jest.fn()},
[AuthHelpers.Register]: {mutateAsync: jest.fn()}
}

jest.mock('@salesforce/commerce-sdk-react', () => {
const originalModule = jest.requireActual('@salesforce/commerce-sdk-react')
return {
...originalModule,
useAuthHelper: jest
.fn()
.mockImplementation((helperType) => mockAuthHelperFunctions[helperType])
}
})

let authModal = undefined
const MockedComponent = (props) => {
const {initialView, isPasswordlessEnabled = false} = props
Expand Down Expand Up @@ -155,17 +171,71 @@ test('Renders check email modal on email mode', async () => {
mockUseForm.mockRestore()
})

test('Renders passwordless login when enabled', async () => {
const user = userEvent.setup()
describe('Passwordless enabled', () => {
beforeAll(() => {
jest.spyOn(window.localStorage, 'setItem')
})

renderWithProviders(<MockedComponent isPasswordlessEnabled={true} />)
beforeEach(() => {
jest.resetModules()
window.localStorage.setItem.mockClear()
})

// open the modal
const trigger = screen.getByText(/open modal/i)
await user.click(trigger)
afterAll(() => {
window.localStorage.setItem.mockRestore()
})

await waitFor(() => {
expect(screen.getByText(/continue securely/i)).toBeInTheDocument()
test('Renders passwordless login when enabled', async () => {
const user = userEvent.setup()

renderWithProviders(<MockedComponent isPasswordlessEnabled={true} />)

// open the modal
const trigger = screen.getByText(/open modal/i)
await user.click(trigger)

await waitFor(() => {
expect(screen.getByText(/continue securely/i)).toBeInTheDocument()
})
})

test('Allows passwordless login', async () => {
const {user} = renderWithProviders(<MockedComponent isPasswordlessEnabled={true} />)
const validEmail = 'test@salesforce.com'

// open the modal
const trigger = screen.getByText(/open modal/i)
await user.click(trigger)

await waitFor(() => {
expect(screen.getByText(/continue securely/i)).toBeInTheDocument()
})

// enter a valid email address
await user.type(screen.getByLabelText('Email'), validEmail)

// initiate passwordless login
const passwordlessLoginButton = screen.getByText(/continue securely/i)
// Click the button twice as the isPasswordlessLoginClicked state doesn't change after the first click
await user.click(passwordlessLoginButton)
await user.click(passwordlessLoginButton)
expect(
mockAuthHelperFunctions[AuthHelpers.AuthorizePasswordless].mutateAsync
).toHaveBeenCalledWith({userid: validEmail})

// check that check email modal is open
await waitFor(() => {
const withinForm = within(screen.getByTestId('sf-form-resend-passwordless-email'))
expect(withinForm.getByText(/Check Your Email/i)).toBeInTheDocument()
expect(withinForm.getByText(validEmail)).toBeInTheDocument()
expect(window.localStorage.setItem).toHaveBeenCalled()
})

// resend the email
user.click(screen.getByText(/Resend Link/i))
expect(
mockAuthHelperFunctions[AuthHelpers.AuthorizePasswordless].mutateAsync
).toHaveBeenCalledWith({userid: validEmail})
})
})

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ const ContactInfo = ({isSocialEnabled = false, isPasswordlessEnabled = false, id

const handlePasswordlessLogin = async (email) => {
try {
// Save the path where the user logged in
window.localStorage.setItem('returnToPage', window.location.pathname)
await authorizePasswordlessLogin.mutateAsync({userid: email})
setAuthModalView(EMAIL_VIEW)
authModal.onOpen()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,14 @@ describe('passwordless and social disabled', () => {

describe('passwordless enabled', () => {
let currentBasket = JSON.parse(JSON.stringify(scapiBasketWithItem))

beforeAll(() => {
jest.spyOn(window.localStorage, 'setItem')
})

beforeEach(() => {
window.localStorage.setItem.mockClear()

global.server.use(
rest.put('*/baskets/:basketId/customer', (req, res, ctx) => {
currentBasket.customerInfo.email = validEmail
Expand All @@ -114,6 +121,10 @@ describe('passwordless enabled', () => {
)
})

afterAll(() => {
window.localStorage.setItem.mockRestore()
})

test('renders component', async () => {
const {getByRole} = renderWithProviders(<ContactInfo isPasswordlessEnabled={true} />)
expect(getByRole('button', {name: 'Checkout as Guest'})).toBeInTheDocument()
Expand Down Expand Up @@ -166,6 +177,7 @@ describe('passwordless enabled', () => {
const withinForm = within(screen.getByTestId('sf-form-resend-passwordless-email'))
expect(withinForm.getByText(/Check Your Email/i)).toBeInTheDocument()
expect(withinForm.getByText(validEmail)).toBeInTheDocument()
expect(window.localStorage.setItem).toHaveBeenCalled()
})

// resend the email
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,8 +170,10 @@ const Login = ({initialView = LOGIN_VIEW}) => {
useEffect(() => {
if (isRegistered) {
handleMergeBasket()
if (location?.state?.directedFrom) {
navigate(location.state.directedFrom)
const locatedFrom = window.localStorage.getItem('returnToPage')
window.localStorage.removeItem('returnToPage')
if (locatedFrom) {
navigate(locatedFrom)
} else {
navigate('/account')
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import Registration from '@salesforce/retail-react-app/app/pages/registration'
import ResetPassword from '@salesforce/retail-react-app/app/pages/reset-password'
import mockConfig from '@salesforce/retail-react-app/config/mocks/default'
import {mockedRegisteredCustomer} from '@salesforce/retail-react-app/app/mocks/mock-data'
import * as sdk from '@salesforce/commerce-sdk-react'

const mockMergedBasket = {
basketId: 'a10ff320829cb0eef93ca5310a',
currency: 'USD',
Expand Down Expand Up @@ -77,6 +79,11 @@ afterEach(() => {
})

describe('Logging in tests', function () {
beforeAll(() => {
jest.spyOn(window.localStorage, 'getItem')
jest.spyOn(window.localStorage, 'removeItem')
})

beforeEach(() => {
global.server.use(
rest.post('*/oauth2/token', (req, res, ctx) =>
Expand All @@ -97,6 +104,12 @@ describe('Logging in tests', function () {
})
)
})

afterAll(() => {
window.localStorage.getItem.mockRestore()
window.localStorage.removeItem.mockRestore()
})

test('Allows customer to sign in to their account', async () => {
const {user} = renderWithProviders(<MockedComponent />, {
wrapperProps: {
Expand Down Expand Up @@ -134,6 +147,28 @@ describe('Logging in tests', function () {
expect(screen.getByText(/My Profile/i)).toBeInTheDocument()
})
})

test('If customer is registered, check the returnToPage local storage item', async () => {
jest.doMock('@salesforce/commerce-sdk-react', () => ({
...jest.requireActual('@salesforce/commerce-sdk-react'),
useCustomerType: jest.fn(() => {
return {isRegistered: true}
})
}))

renderWithProviders(<MockedComponent />, {
wrapperProps: {
siteAlias: 'uk',
locale: {id: 'en-GB'},
appConfig: mockConfig.app,
bypassAuth: false
}
})
await waitFor(() => {
expect(window.localStorage.getItem).toHaveBeenCalled()
expect(window.localStorage.removeItem).toHaveBeenCalled()
})
})
})

describe('Error while logging in', function () {
Expand Down
4 changes: 3 additions & 1 deletion packages/template-retail-react-app/app/utils/jwt-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ export const createRemoteJWKSet = (tenantId) => {
const shortCode = appConfig.commerceAPI.parameters.shortCode
const configTenantId = appConfig.commerceAPI.parameters.organizationId.replace(/^f_ecom_/, '')
if (tenantId !== configTenantId) {
throw new Error(`The tenant ID in your PWA Kit configuration ("${configTenantId}") does not match the tenant ID in the SLAS callback token ("${tenantId}").`)
throw new Error(
`The tenant ID in your PWA Kit configuration ("${configTenantId}") does not match the tenant ID in the SLAS callback token ("${tenantId}").`
)
}
const JWKS_URI = `${appOrigin}/${shortCode}/${tenantId}/oauth2/jwks`
return joseCreateRemoteJWKSet(new URL(JWKS_URI))
Expand Down
Loading