test('Users can add 2FA to their account and use it when logging in', async ({
page,
insertNewUser,
}) => {
const password = faker.internet.password()
const user = await insertNewUser({ password })
invariant(user.name, 'User name is not defined')
const session = await prisma.session.create({
data: {
expirationDate: getSessionExpirationDate(),
userId: user.id,
},
})
const cookieSession = await sessionStorage.getSession(session.id)
cookieSession.set(sessionKey, session.id)
const cookieConfig = cookieParser.parseString(
await sessionStorage.commitSession(cookieSession),
) as any
page.context().addCookies([{ ...cookieConfig, domain: 'localhost' }])
await page.goto('/settings/profile')
await page.getByRole('link', { name: /enable 2fa/i }).click()
await expect(page).toHaveURL(`/settings/profile/two-factor`)
const main = page.getByRole('main')
await main.getByRole('button', { name: /enable 2fa/i }).click()
const otpUrlString = await main
.getByLabel(/One-time Password URI/i)
.textContent()
invariant(otpUrlString, 'OTP URL is not defined')
const otpUrl = new URL(otpUrlString)
const options = Object.fromEntries(otpUrl.searchParams.entries())
const { otp } = generateTOTP(options)
await main.getByRole('textbox', { name: /code/i }).fill(otp)
await main.getByRole('button', { name: /submit/i }).click()
await expect(page).toHaveURL('/settings/profile/two-factor')
await page.goto('/settings/profile')
await page.getByRole('button', { name: /logout/i }).click()
await page.getByRole('link', { name: /login/i }).click()
await expect(page).toHaveURL('/login')
await page.getByRole('textbox', { name: /username/i }).fill(user.username)
await page.getByRole('textbox', { name: /password/i }).fill(password)
await page.getByRole('button', { name: /log in/i }).click()
await expect(page).toHaveURL(/verify*/i)
const { otp: otp2 } = generateTOTP(options)
await page.getByRole('textbox', { name: /code/i }).fill(otp2)
await page.getByRole('button', { name: /submit/i }).click()
await expect(page).toHaveURL('/')
})