# Multiplayer UI - Two factor authentication login (Part 2)

> Enabling two-factor authentication adds an extra layer of security, ensuring that only the rightful account owner can access it. This is typically achieved by generating a QR code that links the user's account with an authenticator app like Google Authenticator. The app then generates a code required for logging into the account. The server processes this code to verify the login attempt.

> Documentation index: https://coherent-labs.com/llms.txt lists every page of this documentation as Markdown; the full text is in https://coherent-labs.com/llms-full.txt.

Source: https://coherent-labs.com/blog/uitutorials/multiplayer-ui/two-factor-authentication/

## Multiplayer UI - Two factor authentication login (Part 2)

ui tutorials

8/6/2024

Kaloyan Geshev

1. Prerequisites
2. Showcase Overview
3. Source location
4. Getting started - Backend
   1. Add additional fields to the user
   2. Enable 2FA check in the login method
   3. Entries for linking the app or verifying the code.
5. Getting started - Frontend
   1. Refactoring the login page
   2. Navigate to the 2FA page
   3. 2FA page

Enabling two-factor authentication adds an extra layer of security, ensuring that only the rightful account owner can access it. This is typically achieved by generating a QR code that links the user’s account with an authenticator app like `Google Authenticator`. The app then generates a code required for logging into the account. The server processes this code to verify the login attempt.

You can find the rest Multiplayer UI series here.

## Prerequisites

In this tutorial, we will use [otplib ](https://www.npmjs.com/package/otplib)implementing two-factor authentication and [qrcode ](https://www.npmjs.com/package/qrcode)to generate the QR code needed for linking the user’s account with the [Google Authenticator ](https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2\&hl=en\&pli=1)app.

## Showcase Overview

We will extend the express server created for the Multiplayer UI in this post by adding two-factor authentication during user login. Additionally, we will include a new UI page for handling this authentication and displaying the QR code for the user to scan with the authenticator app.

## Source location

You can find the complete sample source within the `${Gameface package}/Samples/uiresources/UITutorials/MultiplayerUI` directory.

- `src` folder contains the UI source code.
- `api` folder contains the Express server source code.

Ensure to run `npm i` before testing the sample.

By default, two-factor authentication is disabled. To test it, run the express server locally by either:

1. Executing `npm run start:server:2fa` to enable login authentication with 2FA.
2. Adding `TWO_FACTOR_AUTHENTICATION_ENABLED="true"` to the `.env` file and then starting the server locally with the `npm run server:start` command.

Refer to the `README.md` file in this directory for information on running the sample locally or previewing it without building or starting any processes.

## Getting started - Backend

We will begin by modifying the backend to enable 2FA in the login method and adding additional APIs for handling code verification and linking to `Google Authenticator`.

First, install the required modules:

```shell
npm i otplib qrcode dotenv
```

### Add additional fields to the user

To store information about two-factor authentication in the user account, we need to extend the schema of the user in our database. We will add two new fields:

```js
const mongoose = require('mongoose');

const schema = new mongoose.Schema({
    firstName: String,
    lastName: String,
    email: String,
    password: String,
    status: Boolean,
    totpSecret: String,
    twoFactorEnabled: Boolean,
    friends: [{ type: String }]
});

module.exports = mongoose.model('user', schema);
```

The `totpSecret` field stores the generated secret needed for user authentication via the `Authenticator` app, while `twoFactorEnabled` indicates if the user’s account is linked with the app.

### Enable 2FA check in the login method

To enable 2FA during user login, we need to update our `login` method.

```js
const { authenticator } = require('otplib');
const qrcode = require('qrcode');

class UserController {
    async login(req, res) {
        const sessionId = req.headers['session-id'];
        if (sessionId && await sessions.findOne({ _id: sessionId })) return res.send(sessionId);

        const user = await User.findOne({ email: req.body.email, password: req.body.password });
        if (!user) return res.status(404).send('Wrong email or password!');

        if (!process.env.TWO_FACTOR_AUTHENTICATION_ENABLED) {
            user.status = true;
            await user.save();
            emit('user-online', user.id);
            res.json({ id: user._id.toString(), sessionId: req.sessionID, firstName: user.firstName, lastName: user.lastName });
            return res.json({ id: user._id.toString(), sessionId: req.sessionID, firstName: user.firstName, lastName: user.lastName });
        }

        if (!user.totpSecret) {
            const secret = authenticator.generateSecret();
            const keyUri = authenticator.keyuri(user.email, 'CoherentSample', secret);
            const secretQrCode = await qrcode.toDataURL(keyUri);
            return res.status(403).json({ error: 'missing_totp', secretQrCode, secret, id: user._id.toString() });
        }

        return res.status(403).json({ error: 'totp_verification_required', id: user._id.toString() });
    }
}
```

By default, 2FA is disabled during user login. This behavior is controlled via the `TWO_FACTOR_AUTHENTICATION_ENABLED` environment variable. To enable environment variables on the server, we previously installed the `dotenv` module and need to import it in the `index.js` file.

```js
const server = createServer(app);
require('dotenv').config();
```

Without the `TWO_FACTOR_AUTHENTICATION_ENABLED` variable, 2FA will remain disabled.

When 2FA is enabled, we need to handle user login properly by checking if the user has already linked the `Authenticator` app. We determine this by checking if the user has a `totpSecret` in the database - `if (!user.totpSecret)`.

1. If the user has a secret stored in the database, we return an error indicating that TOTP verification is required. The user should enter the generated code from the `Authenticator` app into the UI.

```js
return res.status(403).json({ error: 'totp_verification_required', id: user._id.toString() });
```

2. If the user does not have a secret stored in the database, the account should be linked with the `Authenticator` app. We generate a new secret and a QR code for adding the secret to the app by scanning it. The generated data is then sent to the UI.

```js
if (!user.totpSecret) {
    const secret = authenticator.generateSecret();
    const keyUri = authenticator.keyuri(user.email, 'CoherentSample', secret);
    const secretQrCode = await qrcode.toDataURL(keyUri);
    return res.status(403).json({ error: 'missing_totp', secretQrCode, secret, id: user._id.toString() });
}
```

### Entries for linking the app or verifying the code.

When the user needs to authenticate using the `Authenticator` app, there are two scenarios: the user has either already linked the app to their account or not. To handle these scenarios, we will create two new routes:

For that reason we will create two new entry points to the user routes:

```js
router.post('/bind-totp', UserController.bindTotp);
router.post('/verify-totp', UserController.totpVerify);
```

#### bindTotp method

To link the `Authenticator` app with the user account, we need to validate the generated code from the app and then store the secret in the user’s account if the code is correct. After this, the user can be logged in.

```js
class UserController {
    async bindTotp(req, res) {
        const { totpCode, userId, pendingTotpSecret } = req.body;
        if (!userId) return res.status(404).send('Unauthorized');

        const user = await User.findById(userId);
        if (!user) return res.status(404).send('Unauthorized');

        const totpVerified = authenticator.check(totpCode, pendingTotpSecret);
        if (!totpVerified) return res.status(400).json({ error: 'Invalid TOTP code' });

        user.twoFactorEnabled = true;
        user.totpSecret = pendingTotpSecret;
        user.status = true;
        await user.save();
        emit('user-online', user.id);

        return res.json({ id: user._id.toString(), sessionId: req.sessionID, firstName: user.firstName, lastName: user.lastName });
    }
}
```

#### totpVerify method

If the user has already linked the app to their account, we only need to check the generated code from the `Authenticator` app. If the code is correct, the user can successfully log in.

```js
class UserController {
    async totpVerify(req, res) {
        const { totpCode, userId } = req.body;
        if (!userId) return res.status(404).send('Unauthorized');

        const user = await User.findById(userId);
        if (!user) return res.status(404).send('Unauthorized');

        const { totpSecret } = user;
        const verified = authenticator.check(totpCode, totpSecret);
        if (!verified) return res.status(400).json({ error: 'Invalid TOTP code' });

        user.status = true;
        await user.save();
        emit('user-online', user.id);
        return res.json({ id: user._id.toString(), sessionId: req.sessionID, firstName: user.firstName, lastName: user.lastName });
    }
}
```

## Getting started - Frontend

To implement two-factor authentication (2FA) in the frontend, we’ll create a dedicated page where users can either scan a QR code to link their account with an authenticator app or input the code generated by the app.

### Refactoring the login page

First, we need to refactor the login page to reuse some of its logic on the 2FA page. We’ll create a custom hook for login operations that returns the states for the welcome message, user name, and a function to handle post-login operations.

```jsx
import { useEffect, useRef, useState } from "react";
import { useAuth } from "./useAuth";

const useLogin = () => {
    const { login } = useAuth();
    const [userName, setUserName] = useState('');
    const [showWelcomeMessage, setShowWelcomeMessage] = useState(false);
    const [zoomOut, setZoomOut] = useState(false);
    const timeoutRef = useRef(null);

    useEffect(() => {
        return (() => {
            if (timeoutRef.value) clearTimeout(timeoutRef.value);
        })
    }, []);

    const loginUser = (xhr) => {
        login(xhr.responseText);
        const userData = JSON.parse(xhr.responseText)
        setUserName(userData.firstName + ' ' + userData.lastName);
        setZoomOut(true);
        timeoutRef.value = setTimeout(() => setShowWelcomeMessage(true), 2000);
    }

    return { loginUser, userName, showWelcomeMessage, zoomOut };
}

export default useLogin;
```

This hook manages the state for `userName`, the zoom-out animation, and the visibility of the welcome message. It also clears the timeout if the component is unmounted by using the `useEffect` hook.

Next, integrate this hook into the login page.

```jsx
const [userName, setUserName] = useState('');
const [showWelcomeMessage, setShowWelcomeMessage] = useState(false);
const [zoomOut, setZoomOut] = useState(false);
const { login } = useAuth();
const { zoomOut, showWelcomeMessage, userName, loginUser } = useLogin();

const onSubmit = async () => {
    ...
    const [xhr, reqError] = await fetch('POST', `${process.env.SERVER_URL}/api/login`, { email, password });
    if (reqError) {
        setError(reqError);
        return console.error(reqError);
    }

    loginUser(xhr);
    login(xhr.responseText);
    const userData = JSON.parse(xhr.responseText)
    setUserName(userData.firstName + ' ' + userData.lastName);
    setZoomOut(true);
    setTimeout(() => {
        setShowWelcomeMessage(true);
        setTimeout(() => {
            navigate("/");
        }, 5000);
    }, 2000);
}
```

### Navigate to the 2FA page

When the user tries to log in and the server requires two-factor authentication, we need to navigate to the 2FA page. We’ll create a handler to check if 2FA is needed and navigate accordingly.

```jsx
const should2faAuth = (xhr) => {
    try {
        const responseObj = JSON.parse(xhr.responseText);
        if (responseObj.error && ['missing_totp', 'totp_verification_required'].includes(responseObj.error)) {
            return navigate('/totp', { state: { ...responseObj } });
        }

        return false;
    } catch (error) {
        setError('Internal error. Please try again!');
        console.error(error);
        return false;
    }
}

const onSubmit = async () => {
    setError('');
    const email = emailRef.current.value;
    const password = passowrdRef.current.value;
    const [xhr, reqError] = await fetch('POST', `${process.env.SERVER_URL}/api/login`, { email, password });
    if (should2faAuth(xhr)) return;
    if (reqError) {
        setError(reqError);
        return console.error(reqError);
    }
```

### 2FA page

We will create a new page to enable users to perform two-factor authentication (2FA).

First, we need to add this page to the router as a public path.

```jsx
import Totp from './pages/TOTP/Totp';
...
<Routes>
    <Route path='/' element={<ProtectedRoute><Home /></ProtectedRoute>} >
        <Route index element={<Friends />} />
        <Route path="/add-friends" element={<AddFriends />} />
    </Route>
    <Route path='/register' element={<Register />} />
    <Route path='/login' element={<Login />} />
    <Route path='/totp' element={<Totp />} />
</Routes>
```

Next, we will create a new page that reuses the login logic but ensures the user completes 2FA using their phone app.

```jsx
import React, { useRef, useState } from 'react';
import './Totp.scss';
import useFetch from '../../hooks/useFetch';
import { Link, Navigate, useLocation } from 'react-router-dom';
import { useLocalStorage } from '../../hooks/useLocalStorage';
import useEnter from '../../hooks/useEnter';
import LoginWrapper from '../../components/LoginWrapper';
import useLogin from '../../hooks/useLogin';

const Totp = () => {
    const { state } = useLocation();
    const { error, secretQrCode, secret, id } = state;
    const [user] = useLocalStorage('user');
    const [errorMessage, setError] = useState('');
    const { zoomOut, showWelcomeMessage, userName, loginUser } = useLogin();

    if (user) {
        return <Navigate to='/' />;
    }

    if (error !== 'missing_totp' && error !== 'totp_verification_required') {
        return <Navigate to='/login' />;
    }

    const verificationCodeRef = useRef(null);
    const fetch = useFetch();

    const verifyIdendityRequest = async (userId, totpCode, secret, bindTotp = false) => {
        const requestUrl = `${process.env.SERVER_URL}/api/${bindTotp ? 'bind-totp' : 'verify-totp'}`;
        const reqBody = { userId, totpCode };
        if (bindTotp) reqBody.pendingTotpSecret = secret;

        return await fetch('POST', requestUrl, reqBody);
    }

    const hasUserVerified = (xhr) => {
        try {
            const responseObj = JSON.parse(xhr.responseText);
            if (responseObj && !responseObj.error) return true;
            setError(responseObj.error);
            console.error(responseObj.error);
            return false;
        } catch (error) {
            setError('Internal error. Please try again!');
            console.error(error);
            return false;
        }
    }

    const onSubmit = async () => {
        setError('');
        const totpCode = verificationCodeRef.current.value;

        const [xhr, reqError] = await verifyIdendityRequest(id, totpCode, secret, error === 'missing_totp');
        if (!hasUserVerified(xhr)) return;
        if (reqError) {
            setError(reqError);
            return console.error(reqError);
        }

        loginUser(xhr);
    }

    useEnter(onSubmit);

    return (
        <LoginWrapper zoomOut={zoomOut} showWelcomeMessage={showWelcomeMessage} message={`Wellcome, ${userName}`}>
            {secretQrCode && <img className='totp-qr-code' src={secretQrCode} />}
            <div className='form-item totp-code'>
                <span className='label'>Verifiation code:</span>
                <input ref={verificationCodeRef} tabIndex={1} type="text" />
            </div>
            {errorMessage && <span className='error-message'>{errorMessage}</span>}
            <button className="totp-submit" onClick={onSubmit}>Verify</button>
            <Link to='/login'>
                <button className="totp-login-back" tabIndex={1}>Back to login</button>
            </Link>
        </LoginWrapper>
    )
}

export default Totp;
```

#### Retreiving navigation state

This page receives state from the navigation API when the login page redirects here. We use this state to determine whether to show the QR code for linking the app or just the verification code input.

```jsx
const { state } = useLocation();
const { error, secretQrCode, secret, id } = state;
```

If the server generates a secret when the user tries to log in, we display it as a QR code.

```jsx
{secretQrCode && <img className='totp-qr-code' src={secretQrCode} />}
```

Otherwise, only the verification code input is displayed.

#### Handle bad navigation to the page

We handle scenarios where the user is already logged in or the error state from navigation is undefined or unrelated to 2FA.

```jsx
if (user) {
    return <Navigate to='/' />;
}

if (error !== 'missing_totp' && error !== 'totp_verification_required') {
    return <Navigate to='/login' />;
}
```

#### Performing 2FA

To perform 2FA, we submit the verification code in the `onSubmit` method.

```jsx
const onSubmit = async () => {
    setError('');
    const totpCode = verificationCodeRef.current.value;

    const [xhr, reqError] = await verifyIdendityRequest(id, totpCode, secret, error === 'missing_totp');
    if (!hasUserVerified(xhr)) return;
    if (reqError) {
        setError(reqError);
        return console.error(reqError);
    }

    loginUser(xhr);
}
```

We also reuse the login logic wrapped in the `useLogin` hook.

```jsx
const { zoomOut, showWelcomeMessage, userName, loginUser } = useLogin();
```

We send a request to the server via `verifyIdentityRequest` and check if the verification succeeded with `hasUserVerified`. If the user is verified, we call `loginUser`.

#### Verifying identity

There are two types of requests to the server from `verifyIdentityRequest`. One for linking the app if it hasn’t been done yet, and another for verifying the generated code if the app is already linked.

For linking the app, we send a `POST` request to `/api/bind-totp` with the generated code and the secret.

For verification, we send a `POST` request to `/api/verify-totp` with the code.

```jsx
const verifyIdendityRequest = async (userId, totpCode, secret, bindTotp = false) => {
    const requestUrl = `${process.env.SERVER_URL}/api/${bindTotp ? 'bind-totp' : 'verify-totp'}`;
    const reqBody = { userId, totpCode };
    if (bindTotp) reqBody.pendingTotpSecret = secret;

    return await fetch('POST', requestUrl, reqBody);
}
```

By refactoring the login logic and handling 2FA requirements, we ensure a smooth user experience when integrating two-factor authentication into our application.

## On this page
