🎉 New! Web Push Notifications for Chatkit. Learn more in our latest blog post.
Hide
Products
chatkit_full-logo

Extensible API for in-app chat

channels_full-logo

Build scalable realtime features

beams_full-logo

Programmatic push notifications

Developers

Docs

Read the docs to learn how to use our products

Tutorials

Explore our tutorials to build apps with Pusher products

Support

Reach out to our support team for help and advice

Sign in
Sign up

Build a login approval system with Laravel and iOS - Part 1: Building the base application

  • Neo Ighodaro

May 2nd, 2019
You will need Xcode 10.x+ and Laravel 5.x+ installed on your machine.

When building applications that require authentication, it is not uncommon to see applications add 2FA (Two-factor authentication) to make things secure. With 2FA, when you log in in one device, you need to enter a code that would be sent to another trusted device via SMS or a code generator. Another form of 2FA is simply approving the login from another device.

In this article, we are going to consider how to build a simple login approval system that mimics this behavior using Laravel, Swift, and Pusher technologies.

How will it work?

We will build a sample dashboard with actual login but fake data. We will also build an accompanying mobile application that will serve as the authorized device where all the login approvals can be made.

When an administrator attempts to log in to the web dashboard, a push notification will be sent to the iOS application prompting the user to approve the login. The user can then approve or deny the login using the Approve or Deny option on the push notification, or clicking on Approve if the application is already opened.

Requirements

To build this system, we need the following requirements:

  • Xcode 10.x installed on your local machine.
  • Knowledge of the Xcode IDE.
  • Laravel v5.x installed on your local machine.
  • Knowledge of the Laravel PHP framework.
  • Knowledge of the Swift programming language.
  • A Pusher Beams application. Create one here.
  • A Pusher Channels application. Create one here.

If you have these requirements, let’s get started.

Setting up the web dashboard

To get started, we will be creating a web dashboard. Launch your terminal application and cd to the directory you want to install your web project to and run the following commands:

    $ laravel new dashboard
    $ cd dashboard

This will create a new Laravel project called dashboard. When the application is created, open the project in your preferred text editor.

Next, in your terminal, run the following command in the root of your application directory:

    $ php artisan make:auth

This command will generate an authentication scaffold. This means we will automatically have access to all of Laravel’s authentication system including the login and logout parts that we need.

Next, let’s connect the application to a database. You can use MySQL or any other supported database you want, but for simplicity, we will be using an SQLite database. Create a new database.sqlite file in the databases directory and leave it empty.

Next, for SQLite, open the .env file and remove all the DB_* keys except DB_CONNECTION and DB_DATABASE. You can set the values as seen below:

    DB_CONNECTION=sqlite
    DB_DATABASE=/path/to/database/database.sqlite

Since Laravel comes with a default database migration for the users table, we do not need to worry about that. However, let’s create a seeder to add sample data to the database and make it easy to set up a user without registering manually.

In your terminal, run the following command:

    $ php artisan make:seed UsersTableSeeder

In the generated seed class, replace the contents with the following:

    <?php
    // File: ./database/seeds/UsersTableSeeder.php

    use App\User;
    use Illuminate\Database\Seeder;
    use Illuminate\Support\Facades\Hash;

    class UsersTableSeeder extends Seeder
    {
        /**
         * Run the database seeds.
         *
         * @return void
         */
        public function run()
        {
            User::create([
                'name' => 'Jane Doe',
                'email' => 'janedoe@pusher.com',
                'password' => Hash::make('secret'),
            ]);
        }
    }

Next, open the database/seeds/DatabaseSeeder.php file and uncomment the call to the UsersTableSeeder in that file. Next, let’s migrate and seed our database. Run the following command to do so:

    $ php artisan migrate --seed

This command will run the migrations in the database/migrations directory and also seed the UsersTableSeeder. To verify that the user was indeed created, run the following command:

    $ php artisan tinker

This will launch a REPL session where we can run everything available in the Laravel application directly. In this REPL session, run the following:

    >>> App\User::all()

This should print a list of all the available users and your seeded user should be on this list.

Now that we have some data, we are done with the initial set up. Let’s move on to adding a good design and also making the login actually function as intended.

Creating the layout and routes

Before we start creating the frontend, we need to make sure the application’s routes are set up correctly. Open the routes/web.php file and replace the entire contents with the following:

    <?php

    Route::redirect('/', '/home');

    Auth::routes();

    Route::get('/home',                     'HomeController@index')->name('home');
    Route::post('/login/confirm',           'Auth\LoginController@confirmLogin');
    Route::post('/login/authorize',         'Auth\LoginController@authorizeLogin');
    Route::post('/login/client-authorized', 'Auth\LoginController@clientAuthorized');

Above we have defined routes to our application and we will need to start creating some of the methods these routes point to. For now, let’s focus on the ones that have to do with seeing our login screen.

We will be using the SB Admin 2 free template for the frontend of the dashboard. Before we start building, download the template from the link above as we will need some asset files from the template.

Adding the HTML template to the application

If you have downloaded the template we can move on to the next step. Open the app.blade.php file in the resources/views/layouts directory and replace the contents of the file with the following code:

    <!-- File: ./resources/views/layouts/app.blade.php -->
    <!DOCTYPE html>
    <html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <title>Dashboard | {{ config('app.name') }}</title>
        <link href="{{ asset('vendor/fontawesome-free/css/all.min.css') }}" rel="stylesheet">
        <link rel="dns-prefetch" href="//fonts.gstatic.com">
        <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">
        <link href="{{ asset('css/sb-admin-2.min.css') }}" rel="stylesheet">
    </head>
    <body id="page-top">
        <div id="wrapper">
            @include('partials.sidebar')
            <div id="content">
                @include('partials.topbar')
                @yield('content')
                <footer class="sticky-footer bg-white">
                    <div class="container my-auto">
                        <div class="copyright text-center my-auto">
                            <span>Copyright &copy; {{ config('app.name') }} {{ date('Y') }}</span>
                        </div>
                    </div>
                </footer>
            </div>
        </div>
        <a class="scroll-to-top rounded" href="#page-top">
            <i class="fas fa-angle-up"></i>
        </a>
        @include('modals.logout')
        <script src="{{ asset('vendor/jquery/jquery.min.js') }}"></script>
        <script src="{{ asset('vendor/bootstrap/js/bootstrap.bundle.min.') }}js"></script>
        <script src="{{ asset('vendor/jquery-easing/jquery.easing.min.') }}js"></script>
        <script src="{{ asset('js/sb-admin-2.min.js') }}"></script>
        <script src="{{ asset('vendor/chart.js/Chart.min.js') }}"></script>
        <script src="{{ asset('js/demo/chart-area-demo.js') }}"></script>
        <script src="{{ asset('js/demo/chart-pie-demo.js') }}"></script>
    </body>
    </html>

This will be the layout of the entire dashboard. In case you noticed, we included some nonexistent files in the blade template above so let’s create them.

Create a new directory in resources/views called partials and inside this new directory create some new files as seen below.

The first file will be the sidebar.blade.php:

    <!-- File: ./resources/views/sidebar.blade.php -->
    <ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">
        <a class="sidebar-brand d-flex align-items-center justify-content-center" href="index.html">
            <div class="sidebar-brand-icon rotate-n-15">
                <i class="fas fa-laugh-wink"></i>
            </div>
            <div class="sidebar-brand-text mx-3">SB Admin <sup>2</sup></div>
        </a>
        <hr class="sidebar-divider my-0">
        <li class="nav-item active">
            <a class="nav-link" href="index.html">
                <i class="fas fa-fw fa-tachometer-alt"></i>
                <span>Dashboard</span>
            </a>
        </li>
        <hr class="sidebar-divider">
        <div class="sidebar-heading">
            Interface
        </div>
        <li class="nav-item">
            <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo">
                <i class="fas fa-fw fa-cog"></i>
                <span>Components</span>
            </a>
            <div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionSidebar">
                <div class="bg-white py-2 collapse-inner rounded">
                    <h6 class="collapse-header">Custom Components:</h6>
                    <a class="collapse-item" href="buttons.html">Buttons</a>
                    <a class="collapse-item" href="cards.html">Cards</a>
                </div>
            </div>
        </li>
        <li class="nav-item">
            <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseUtilities" aria-expanded="true" aria-controls="collapseUtilities">
                <i class="fas fa-fw fa-wrench"></i>
                <span>Utilities</span>
            </a>
            <div id="collapseUtilities" class="collapse" aria-labelledby="headingUtilities" data-parent="#accordionSidebar">
                <div class="bg-white py-2 collapse-inner rounded">
                    <h6 class="collapse-header">Custom Utilities:</h6>
                    <a class="collapse-item" href="utilities-color.html">Colors</a>
                    <a class="collapse-item" href="utilities-border.html">Borders</a>
                    <a class="collapse-item" href="utilities-animation.html">Animations</a>
                    <a class="collapse-item" href="utilities-other.html">Other</a>
                </div>
            </div>
        </li>
        <hr class="sidebar-divider">
        <div class="sidebar-heading">
            Addons
        </div>
        <li class="nav-item">
            <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapsePages" aria-expanded="true" aria-controls="collapsePages">
                <i class="fas fa-fw fa-folder"></i>
                <span>Pages</span>
            </a>
            <div id="collapsePages" class="collapse" aria-labelledby="headingPages" data-parent="#accordionSidebar">
                <div class="bg-white py-2 collapse-inner rounded">
                    <h6 class="collapse-header">Login Screens:</h6>
                    <a class="collapse-item" href="login.html">Login</a>
                    <a class="collapse-item" href="register.html">Register</a>
                    <a class="collapse-item" href="forgot-password.html">Forgot Password</a>
                    <div class="collapse-divider"></div>
                    <h6 class="collapse-header">Other Pages:</h6>
                    <a class="collapse-item" href="404.html">404 Page</a>
                    <a class="collapse-item" href="blank.html">Blank Page</a>
                </div>
            </div>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="charts.html">
                <i class="fas fa-fw fa-chart-area"></i>
                <span>Charts</span></a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="tables.html">
                <i class="fas fa-fw fa-table"></i>
                <span>Tables</span></a>
        </li>
        <hr class="sidebar-divider d-none d-md-block">
        <div class="text-center d-none d-md-inline">
            <button class="rounded-circle border-0" id="sidebarToggle"></button>
        </div>
    </ul>

The above is just the extracted sidebar from the theme we downloaded earlier. Next create the second file topbar.blade.php inside the same partials directory:

    <!-- File: ./resources/views/topbar.blade.php -->
    <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">
        <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
            <i class="fa fa-bars"></i>
        </button>
        <form class="d-none d-sm-inline-block form-inline mr-auto ml-md-3 my-2 my-md-0 mw-100 navbar-search">
            <div class="input-group">
                <input type="text" class="form-control bg-light border-0 small" placeholder="Search for..." aria-label="Search" aria-describedby="basic-addon2">
                <div class="input-group-append">
                    <button class="btn btn-primary" type="button">
                        <i class="fas fa-search fa-sm"></i>
                    </button>
                </div>
            </div>
        </form>
        <ul class="navbar-nav ml-auto">
            <li class="nav-item dropdown no-arrow d-sm-none">
                <a class="nav-link dropdown-toggle" href="#" id="searchDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    <i class="fas fa-search fa-fw"></i>
                </a>
                <div class="dropdown-menu dropdown-menu-right p-3 shadow animated--grow-in" aria-labelledby="searchDropdown">
                    <form class="form-inline mr-auto w-100 navbar-search">
                        <div class="input-group">
                            <input type="text" class="form-control bg-light border-0 small" placeholder="Search for..." aria-label="Search" aria-describedby="basic-addon2">
                            <div class="input-group-append">
                                <button class="btn btn-primary" type="button">
                                    <i class="fas fa-search fa-sm"></i>
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </li>
            <div class="topbar-divider d-none d-sm-block"></div>
            <li class="nav-item dropdown no-arrow">
                <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    <span class="mr-2 d-none d-lg-inline text-gray-600 small">{{ auth()->user()->name }}</span>
                    <img class="img-profile rounded-circle" src="https://source.unsplash.com/QAB-WJcbgJk/60x60">
                </a>
                <div class="dropdown-menu dropdown-menu-right shadow animated--grow-in" aria-labelledby="userDropdown">
                    <a class="dropdown-item" href="#">
                        <i class="fas fa-user fa-sm fa-fw mr-2 text-gray-400"></i> Profile
                    </a>
                    <a class="dropdown-item" href="#">
                        <i class="fas fa-cogs fa-sm fa-fw mr-2 text-gray-400"></i> Settings
                    </a>
                    <a class="dropdown-item" href="#">
                        <i class="fas fa-list fa-sm fa-fw mr-2 text-gray-400"></i> Activity Log
                    </a>
                    <div class="dropdown-divider"></div>
                    <a class="dropdown-item" href="#" data-toggle="modal" data-target="#logoutModal">
                        <i class="fas fa-sign-out-alt fa-sm fa-fw mr-2 text-gray-400"></i> Logout
                    </a>
                </div>
            </li>
        </ul>
    </nav>

Now that we have both files, create a new directory modals inside the resources/views directory and inside this directory add this new file logout.blade.php:

    <!-- File: ./resources/views/modals/logout.blade.php -->
    <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
                   <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">Ă—</span>
                    </button>
                </div>
                <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                    <a class="btn btn-primary" href="{{ route('logout') }}"
                        onclick="event.preventDefault();
                                        document.getElementById('logout-form').submit();">
                        {{ __('Logout') }}
                    </a>
                    <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
                        @csrf
                    </form>
                </div>
            </div>
        </div>
    </div>

Next, open the resources/views/auth/login.blade.php file and replace the file with the following:

    <!-- File: ./resources/views/auth/login.blade.php -->
    <!DOCTYPE html>
    <html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <title>Dashboard Login | {{ config('app.name') }}</title>
        <script src="{{ asset('js/app.js') }}" defer></script>
        <link rel="dns-prefetch" href="//fonts.gstatic.com">
        <link href="{{ asset('vendor/fontawesome-free/css/all.min.css') }}" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">
        <link href="{{ asset('css/sb-admin-2.min.css') }}" rel="stylesheet">
    </head>
    <body class="bg-gradient-primary">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-xl-10 col-lg-12 col-md-9">
                    <div class="card o-hidden border-0 shadow-lg my-5">
                        <div class="card-body p-0">
                            <div class="row">
                                <div class="col-lg-6 d-none d-lg-block">
                                    <img src="https://source.unsplash.com/K4mSJ7kc0As/464x577">
                                </div>
                                <div class="col-lg-6">
                                    <div class="p-5 d-none" id="loginApprovalQueue">
                                        <div class="w-50 my-5 mx-auto mobilePhone">
                                            <img src="{{ asset('img/approval-mobile.svg') }}" class="w-100">
                                        </div>
                                        <h5 class="text-center text-primary">We sent an approval request to your registered devices</h5>
                                        <small class="d-block text-secondary text-center">
                                            To log in, open the dashboard app on one of your registered devices and approve the login request.
                                        </small>
                                        <div class="text-center mt-3">
                                            <img src="{{ asset('/img/spinner.svg') }}" alt="">
                                        </div>
                                    </div>
                                    <div class="p-5" id="loginFormWrapper">
                                        <div class="text-center">
                                            <h1 class="h4 text-gray-900 mb-4">Log in</h1>
                                        </div>
                                        <form method="POST" action="{{ route('login') }}" class="user" id="authenticationForm">
                                            @csrf
                                            <div class="form-group">
                                                <input type="email" class="form-control form-control-user" id="email" aria-describedby="emailHelp" placeholder="Email Address" name="email" value="{{ old('email') }}" required autofocus>
                                            </div>
                                            <div class="form-group">
                                                <input type="password" class="form-control form-control-user" id="password" placeholder="Password" name="password" required>
                                            </div>
                                            <div class="form-group">
                                                <div class="custom-control custom-checkbox small">
                                                    <input type="checkbox" class="custom-control-input" id="remember" name="remember" {{ old('remember') ? 'checked' : '' }}>
                                                    <label class="custom-control-label" for="remember">Remember Me</label>
                                                </div>
                                            </div>
                                            <button type="submit" class="btn btn-primary btn-user btn-block">
                                                Login
                                            </button>
                                            <hr>
                                            <a href="index.html" class="btn btn-google btn-user btn-block">
                                                <i class="fab fa-google fa-fw"></i> Login with Google
                                            </a>
                                            <a href="index.html" class="btn btn-facebook btn-user btn-block">
                                                <i class="fab fa-facebook-f fa-fw"></i> Login with Facebook
                                            </a>
                                        </form>
                                        <hr>
                                        @if (Route::has('password.request'))
                                        <div class="text-center">
                                            <a class="small" href="{{ route('password.request') }}">Forgot Password?</a>
                                        </div>
                                        @endif
                                        <div class="text-center">
                                            <a class="small" href="{{ route('register') }}">Create an Account!</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <script src="{{ asset('vendor/jquery/jquery.min.js') }}"></script>
        <script src="{{ asset('vendor/bootstrap/js/bootstrap.bundle.min.js') }}"></script>
        <script src="{{ asset('vendor/jquery-easing/jquery.easing.min.js') }}"></script>
        <script src="{{ asset('js/sb-admin-2.min.js') }}"></script>

        <script type="text/javascript">
        const showApprovalAndListenForApproval = callback => {
            $('#loginFormWrapper').addClass('d-none');
            $('#loginApprovalQueue').removeClass('d-none');

            Echo.channel('auth-request')
                .listen('.approval-granted', e => callback(e.hash));
        };

        const getLoginCredentials = () => {
            return {
                email: $('#email').val(),
                password: $('#password').val(),
                remember: $('#remember').val()
            }
        };

        $(document).ready(() => {
            $('#authenticationForm').on('submit', e => {
                e.preventDefault();

                const { email, password, remember } = getLoginCredentials();

                axios.post('/login/confirm', {email, password, remember })
                    .then(() => {
                        showApprovalAndListenForApproval(hash => {
                            axios.post('/login/authorize', { email, password, remember, hash })
                                .then(() => (window.location = '/home'))
                                .catch(() => alert('Invalid authorization. Please try again.'));
                        });
                    })
                    .catch(() => alert('Invalid login credentials!'));
            })
        })
        </script>
    </body>
    </html>

Above we have defined the login page, based on the template we downloaded earlier. We have also added Laravel specific login logic to the code. More importantly, note that we have some custom JavaScript at the bottom of the page.

In this script, we capture the login event and then use Axios to send the login request to the backend. When we receive a valid response, we display the login confirmation page so the user knows they have to approve the login from their device.

Also above, we use Laravel Echo to start listening for realtime messages from the Pusher API, we will get to this later. For us to have Echo, we need to install it and build the JavaScript file.

Adding assets and building our JavaScript file

First, open the app.js file in the resources/js directory and replace the contents with the following:

    // File: ./resources/js/app.js
    window.axios = require('axios');
    window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

    let token = document.head.querySelector('meta[name="csrf-token"]');

    if (token) {
        window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
    } else {
        console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
    }

    import Echo from 'laravel-echo';

    window.Pusher = require('pusher-js');
    window.Echo = new Echo({
        broadcaster: 'pusher',
        key: process.env.MIX_PUSHER_APP_KEY,
        cluster: process.env.MIX_PUSHER_APP_CLUSTER,
        encrypted: true
    });

Next, in your terminal run the following commands to install dependencies and build our JS file.

    $ npm install laravel-echo pusher-js
    $ npm install
    $ npm run dev

Next, unzip the downloaded template. Copy the following directories as seen below into the public directory:

  • Copy the .css files from css to the public/css directory
  • Copy the .js files (including the demo directory) from js to the public/js directory
  • Copy the .svg file in img to the public/img directory
  • Copy the vendor directory to the public directory.
  • Copy the approval-mobile.svg and spinner.svg from here.

That is all the assets we will be needing from the theme.

Running our application

When the build is complete, we can now run our application. In your terminal, run the following command to start a new PHP server for our application:

    $ php artisan serve

Now when you visit http://127.0.0.1:8000 you should see the login page for the application. It won’t work yet. We will make it work in the next part of the article.

Conclusion

In this part of the tutorial, we set up the application and added the login page.

In the next part, we will be making the login functionality work and also adding a dashboard page.

The source code to the application is available on GitHub.

Clone the project repository
  • Beams
  • iOS
  • Laravel
  • PHP
  • Swift
  • Channels
  • Beams

Products

  • Channels
  • Chatkit
  • Beams

© 2019 Pusher Ltd. All rights reserved.

Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 160 Old Street, London, EC1V 9BW.