🎉 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 - Part 2: Building the backend

  • Neo Ighodaro

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

In the previous part of this series, we set up the Laravel application and in the application, we added a login page of the application so we would be able to log in to the app. However, we did not implement any functionality.

In this part, we will be adding the logic to make logging in work. We will also be completing the dashboard using the same template we downloaded in the first part.

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.

Making login work

The first thing we want to do is make the login work. From the first part, we attached a script that used Axios to send the login request to a different endpoint /login/confirm. Let us implement the logic for this route.

Open the LoginController in the app/Http/Controllers/Auth directory. Update the class as seen below:

    <?php
    // File: ./app/Http/Controllers/Auth/LoginController.php
    // [...]

    use Illuminate\Support\Str;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Hash;
    use App\Events\LoginAuthorizationRequested;

    // [...]

    class LoginController extends Controller
    {
        // [...]

        public function confirmLogin(Request $request)
        {
            $this->validateLogin($request);

            if ($this->hasTooManyLoginAttempts($request)) {
                $this->fireLockoutEvent($request);
                return $this->sendLockoutResponse($request);
            }

            if ($this->guard()->validate($this->credentials($request))) {
                $username = $request->get($this->username());
                $hashKey = sha1($username . '_' . Str::random(32));
                $unhashedLoginHash = $hashKey . '.' . Str::random(32);

                // Store the hash for 5 minutes...
                $mins = now()->addMinutes(5);
                $key = "{$hashKey}_login_hash";
                cache()->put($key, Hash::make($unhashedLoginHash), $mins);

                event(new LoginAuthorizationRequested($unhashedLoginHash, $username));

                return ['status' => true];
            }

            $this->incrementLoginAttempts($request);

            return $this->sendFailedLoginResponse($request);
        }
    }

In the above, we are adding the confirmLogin method that we specified in the routes file. In this method we are doing the following:

  • Validating the request
  • Checking for excessive login attempts
  • Validating the login credentials without logging in
  • Creating and storing a hash for five minutes
  • Triggering an event to broadcast that the login needs authorization
  • Returning a true status so the client knows a request for authorization has been issued

Creating login events and listeners

We do not currently have this event we triggered so let’s create it. In your terminal, run the following command:

    $ php artisan make:event LoginAuthorizationRequested

Next, open this app/Events/LoginAuthorizationRequested.php file and replace the contents with the following:

    <?php
    // File: ./app/Events/LoginAuthorizationRequested.php

    namespace App\Events;

    use Illuminate\Broadcasting\Channel;
    use Illuminate\Queue\SerializesModels;
    use Illuminate\Foundation\Events\Dispatchable;
    use Illuminate\Broadcasting\InteractsWithSockets;
    use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

    class LoginAuthorizationRequested implements ShouldBroadcast
    {
        use Dispatchable, InteractsWithSockets, SerializesModels;

        public $hash;
        public $email;

        public function __construct(string $hash, string $email)
        {
            $this->hash = $hash;
            $this->email = $email;
        }

        public function broadcastOn()
        {
            return new Channel('auth-request');
        }

        public function broadcastAs()
        {
            return 'key-dispatched';
        }
    }

You can learn more about Laravel’s event system.

Very important to note above, we are implementing the ShouldBroadcast interface which will instruct the event to be broadcasted using the driver set in the .env file. Open the .env file and set the BROADCAST_DRIVER to pusher.

    # File: ./.env

    # [...]

    BROADCAST_DRIVER=pusher

    # [...]

Also in this .env file, update the PUSHER_* keys to match the values you have in your Pusher dashboard. Below the PUSHER_* keys, add and update the following keys:

    PUSHER_BEAMS_SECRET_KEY=
    PUSHER_BEAMS_INSTANCE_ID=

Next, let’s register the event we just created and attach a listener to it. The listener will automatically be fired when the event is triggered. We will use this listener to send push notifications through Pusher Beams to the user’s device as well.

In your terminal, run the following command:

    $ php artisan make:listener SendLoginAuthorization

Now open this file app/Listeners/SendLoginAuthorization.php and replace the contents with the following:

    <?php
    // File: ./app/Listeners/SendLoginAuthorization.php

    namespace App\Listeners;

    use Illuminate\Queue\InteractsWithQueue;
    use Illuminate\Contracts\Queue\ShouldQueue;
    use App\Events\LoginAuthorizationRequested;
    use Pusher\PushNotifications\PushNotifications;

    class SendLoginAuthorization implements ShouldQueue
    {
        use InteractsWithQueue;

        protected $beams;

        public function __construct(PushNotifications $pushNotifications)
        {
            $this->beams = $pushNotifications;
        }

        public function handle(LoginAuthorizationRequested $event)
        {
            $payload = [
                'title' => 'Dashboard',
                'body' => 'Dashboard just sent a new approval request',
            ];

            // Interest: auth-janedoe-at-pushercom
            $interests = ['auth-' . str_slug($event->email)];

            $this->beams->publishToInterests($interests, [
                'apns' => [
                    'aps' => [
                        'alert' => $payload,
                        'category' => 'LoginActions',
                        'payload' => ['hash' => $event->hash, 'email' => $event->email],
                    ],
                ],
            ]);
        }
    }

In this listener, we are basically triggering a push notification using the Pusher Beams SDK for PHP. In this notification, we pass the hash so the client can use that when authorizing the login.

To register the listener, open the app/Providers/EventServiceProvider.php and add the following array to the listeners property:

    \App\Events\LoginAuthorizationRequested::class => [
       \App\Listeners\SendLoginAuthorization::class,
    ],

Finally, go to your config/app.php file and uncomment the BroadcastServiceProvider from the list of providers.

Installing the Pusher PHP SDKs

Right now we have not installed any of the Pusher PHP SDKs. In your terminal, run the following code to install them:

    $ composer require pusher/pusher-php-server pusher/pusher-push-notifications

Configuring the Pusher push notifications SDK for Laravel

Now that we have the packages installed, let’s add a class to the Laravel service container so that when we pass the PushNotifications class, it will go through the service container. Open the app/Providers/AppServiceProvider.php and in the register add the following:

    <?php
    // File: ./app/Providers/AppServiceProvider.php

    // [...]

    class AppServiceProvider extends ServiceProvider {

      // [...]

      public function register() {
        // [...]

        $this->app->bind(PushNotifications::class, function () {
            $config = config('broadcasting.connections.pusher.beams');

            return new PushNotifications([
                'secretKey' => $config['secret_key'] ?? '',
                'instanceId' => $config['instance_id'] ?? '',
            ]);
        });

        // [...]
      }

      // [...]
    }

You need to also import the push notifications class at the top of the file:

    use Pusher\PushNotifications\PushNotifications;

Next, let’s create the configuration items that we referenced in the code above. Open the config/broadcasting.php file and update as seen below:

    <?php
    // File: ./config/broadcasting.php

    return [

        // [...]

        'connections' => [
            'pusher' => [
                // [...]

                'beams' => [
                    'secret_key' => env('PUSHER_BEAMS_SECRET_KEY'),
                    'instance_id' => env('PUSHER_BEAMS_INSTANCE_ID'),
                ]
            ],
        ],

        // [...]
    ];

Now, let’s run the application to see if we get the right results. In your terminal, run the following command to start the PHP server:

    $ php artisan serve

Now when you go to http://127.0.0.1:8000 you should see the login page as before. However, if you try to log in using the credentials below:

You should see the new screen that shows you that approval has been requested. Also if you check your Pusher Beams & Channels debug console, you should see the events and notification has been triggered.

Adding other login endpoints

Now that we have the login working, let us add some additional endpoints as defined in the routes file. Open the app/Http/Controllers/LoginController.php file and add the following methods:

    <?php
    // File: ./app/Http/Controllers/LoginController.php
    // [...]

    use App\Events\LoginAuthorized;

    // [...]

    class LoginController extends Controller
    {
        // [...]

        public function clientAuthorized(Request $request)
        {
            $request->validate(['hash' => 'required|string']);

            $sentHash = $request->get('hash');
            [$hashKey] = explode('.', $sentHash);
            $storedHash = cache()->get($hashKey . '_login_hash');

            if (!Hash::check($sentHash, $storedHash)) {
                abort(422);
            }

            event(new LoginAuthorized($sentHash));

            return ['status' => true];
        }

        public function authorizeLogin(Request $request)
        {
            $request->validate([
                'hash' => 'required|string',
                'password' => 'required|string',
                $this->username() => 'required|string',
            ]);

            $sentHash = $request->get('hash');
            [$hashKey] = explode('.', $sentHash);
            $storedHash = cache()->get($hashKey . '_login_hash');

            if (!Hash::check($sentHash, $storedHash) || !$this->attemptLogin($request)) {
                abort(422);
            }

            return ['status' => true];
        }
    }

The first method will be the logic fired when the client has authorized the login. The second one will be called by the login script in the login.blade.php.

In these two methods, we validate the hash sent and make sure it matches the one stored in the cache. If for any reason the user does not validate in five minutes, the cache will expire and they would have to start the process again.

In the first method, we see that there is another event LoginAuthorized fired when the client authorizes the login. In this event, we will trigger an event that will be received on the web login page. When the web login receives this event, it will send a request to the authorizeLogin method above and the process will be complete. Let’s create this event.

In your terminal, run the following command:

    $ php artisan make:event LoginAuthorized

In the event file generated, replace the content with the following:

    <?php
    // File: ./app/Events/LoginAuthorized.php

    namespace App\Events;

    use Illuminate\Broadcasting\Channel;
    use Illuminate\Queue\SerializesModels;
    use Illuminate\Foundation\Events\Dispatchable;
    use Illuminate\Broadcasting\InteractsWithSockets;
    use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

    class LoginAuthorized implements ShouldBroadcast
    {
        use Dispatchable, InteractsWithSockets, SerializesModels;

        public $hash;

        public function __construct($hash)
        {
            $this->hash = $hash;
        }

        public function broadcastOn()
        {
            return new Channel('auth-request');
        }

        public function broadcastAs()
        {
            return 'approval-granted';
        }
    }

That’s all. We have a working login system that sends push notifications and Channel events to the Pusher API. Now we just need an iOS client that will receive these events and make it possible for the user to authorize logins.

Adding a sample dashboard for logged in users

One last thing we want to add is the dashboard that will show when a user is logged in. This dashboard will not be functional though, just a sample. Open the home.blade.php file inside the resources/views directory and replace the contents with the following code:

    {{-- File: ./resources/views/home.blade.php --}}
    @extends('layouts.app')

    @section('content')
    <div class="container-fluid">
        <div class="d-sm-flex align-items-center justify-content-between mb-4">
            <h1 class="h3 mb-0 text-gray-800">Dashboard</h1>
            <a href="#" class="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm"><i class="fas fa-download fa-sm text-white-50"></i> Generate Report</a>
        </div>

        <div class="row">
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card border-left-primary shadow h-100 py-2">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Earnings (Monthly)</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">$40,000</div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-calendar fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card border-left-success shadow h-100 py-2">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Earnings (Annual)</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">$215,000</div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-dollar-sign fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card border-left-info shadow h-100 py-2">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-info text-uppercase mb-1">Tasks</div>
                                <div class="row no-gutters align-items-center">
                                    <div class="col-auto">
                                        <div class="h5 mb-0 mr-3 font-weight-bold text-gray-800">50%</div>
                                    </div>
                                    <div class="col">
                                        <div class="progress progress-sm mr-2">
                                            <div class="progress-bar bg-info" role="progressbar" style="width: 50%" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-clipboard-list fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card border-left-warning shadow h-100 py-2">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Pending Requests</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">18</div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-comments fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-xl-8 col-lg-7">
                <div class="card shadow mb-4">
                    <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                        <h6 class="m-0 font-weight-bold text-primary">Earnings Overview</h6>
                        <div class="dropdown no-arrow">
                            <a class="dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                <i class="fas fa-ellipsis-v fa-sm fa-fw text-gray-400"></i>
                            </a>
                            <div class="dropdown-menu dropdown-menu-right shadow animated--fade-in" aria-labelledby="dropdownMenuLink">
                                <div class="dropdown-header">Dropdown Header:</div>
                                <a class="dropdown-item" href="#">Action</a>
                                <a class="dropdown-item" href="#">Another action</a>
                                <div class="dropdown-divider"></div>
                                <a class="dropdown-item" href="#">Something else here</a>
                            </div>
                        </div>
                    </div>
                    <!-- Card Body -->
                    <div class="card-body">
                        <div class="chart-area">
                            <canvas id="myAreaChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xl-4 col-lg-5">
                <div class="card shadow mb-4">
                    <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                        <h6 class="m-0 font-weight-bold text-primary">Revenue Sources</h6>
                        <div class="dropdown no-arrow">
                            <a class="dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                <i class="fas fa-ellipsis-v fa-sm fa-fw text-gray-400"></i>
                            </a>
                            <div class="dropdown-menu dropdown-menu-right shadow animated--fade-in" aria-labelledby="dropdownMenuLink">
                                <div class="dropdown-header">Dropdown Header:</div>
                                <a class="dropdown-item" href="#">Action</a>
                                <a class="dropdown-item" href="#">Another action</a>
                                <div class="dropdown-divider"></div>
                                <a class="dropdown-item" href="#">Something else here</a>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="chart-pie pt-4 pb-2">
                            <canvas id="myPieChart"></canvas>
                        </div>
                        <div class="mt-4 text-center small">
                            <span class="mr-2">
                            <i class="fas fa-circle text-primary"></i> Direct
                        </span>
                            <span class="mr-2">
                            <i class="fas fa-circle text-success"></i> Social
                        </span>
                            <span class="mr-2">
                            <i class="fas fa-circle text-info"></i> Referral
                        </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-lg-6 mb-4">
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">Projects</h6>
                    </div>
                    <div class="card-body">
                        <h4 class="small font-weight-bold">Server Migration <span class="float-right">20%</span></h4>
                        <div class="progress mb-4">
                            <div class="progress-bar bg-danger" role="progressbar" style="width: 20%" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"></div>
                        </div>
                        <h4 class="small font-weight-bold">Sales Tracking <span class="float-right">40%</span></h4>
                        <div class="progress mb-4">
                            <div class="progress-bar bg-warning" role="progressbar" style="width: 40%" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100"></div>
                        </div>
                        <h4 class="small font-weight-bold">Customer Database <span class="float-right">60%</span></h4>
                        <div class="progress mb-4">
                            <div class="progress-bar" role="progressbar" style="width: 60%" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100"></div>
                        </div>
                        <h4 class="small font-weight-bold">Payout Details <span class="float-right">80%</span></h4>
                        <div class="progress mb-4">
                            <div class="progress-bar bg-info" role="progressbar" style="width: 80%" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100"></div>
                        </div>
                        <h4 class="small font-weight-bold">Account Setup <span class="float-right">Complete!</span></h4>
                        <div class="progress">
                            <div class="progress-bar bg-success" role="progressbar" style="width: 100%" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-lg-6 mb-4">
                        <div class="card bg-primary text-white shadow">
                            <div class="card-body">
                                Primary
                                <div class="text-white-50 small">#4e73df</div>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-6 mb-4">
                        <div class="card bg-success text-white shadow">
                            <div class="card-body">
                                Success
                                <div class="text-white-50 small">#1cc88a</div>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-6 mb-4">
                        <div class="card bg-info text-white shadow">
                            <div class="card-body">
                                Info
                                <div class="text-white-50 small">#36b9cc</div>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-6 mb-4">
                        <div class="card bg-warning text-white shadow">
                            <div class="card-body">
                                Warning
                                <div class="text-white-50 small">#f6c23e</div>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-6 mb-4">
                        <div class="card bg-danger text-white shadow">
                            <div class="card-body">
                                Danger
                                <div class="text-white-50 small">#e74a3b</div>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-6 mb-4">
                        <div class="card bg-secondary text-white shadow">
                            <div class="card-body">
                                Secondary
                                <div class="text-white-50 small">#858796</div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>

            <div class="col-lg-6 mb-4">
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">Illustrations</h6>
                    </div>
                    <div class="card-body">
                        <div class="text-center">
                            <img class="img-fluid px-3 px-sm-4 mt-3 mb-4" style="width: 25rem;" src="img/undraw_posting_photo.svg" alt="">
                        </div>
                        <p>Add some quality, svg illustrations to your project courtesy of <a target="_blank" rel="nofollow" href="https://undraw.co/">unDraw</a>, a constantly updated collection of beautiful svg images that you can use completely free and without attribution!</p>
                        <a target="_blank" rel="nofollow" href="https://undraw.co/">Browse Illustrations on unDraw &rarr;</a>
                    </div>
                </div>
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">Development Approach</h6>
                    </div>
                    <div class="card-body">
                        <p>SB Admin 2 makes extensive use of Bootstrap 4 utility classes in order to reduce CSS bloat and poor page performance. Custom CSS classes are used to create custom components and custom utility classes.</p>
                        <p class="mb-0">Before working with this theme, you should become familiar with the Bootstrap framework, especially the utility classes.</p>
                    </div>
                </div>

            </div>
        </div>

    </div>
    @endsection

Conclusion

In this part, we have been able to make the login system work and also push different events to the Pusher API for consumption. In the next part, we will create the iOS application and consume the events that are sent.

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.