Reader small image

You're reading from  Laravel 5.x Cookbook

Product typeBook
Published inSep 2016
Reading LevelIntermediate
PublisherPackt
ISBN-139781786462084
Edition1st Edition
Languages
Tools
Right arrow
Authors (2):
Terry Matula
Terry Matula
author image
Terry Matula

Terry Matula is a web developer and Laravel advocate based in Austin, TX. He's been a passionate computer enthusiast since he first played Oregon Trail on an Apple//e. He started programming in BASIC at a young age, making simple Scott Adams-like games on a Commodore Vic-20. Since then, he's worked as a developer using Flash/ActionScript, ASP.NET, PHP, and numerous PHP frameworks, with Laravel being his favorite by far. He blogs web development tips and tricks at his website http://terrymatula.com
Read more about Terry Matula

Alfred Nutile
Alfred Nutile
author image
Alfred Nutile

Alfred Nutile is an Enterprise Architect and Laravel lead based in Western Massachusetts. He's been working in the industry since the mid 90's. He started in PHP and MySQL back around that time and has worked with Ruby on Rails, Drupal, and Angular along the way. He introduced Laravel into an enterprise web stack, where he is currently contracted at, as Laravel proved itself as an amazing framework to build API's and Angular heavy application. You can read more about him and checkout his blog at http://www.alfrednutile.info/ or follow him on Twitter at https://twitter.com/alnutile Make sure to checkout the discount LaraCasts is offering those who buy the book! Get a coupon for 50% on your first bill. Make it a yearly subscription and save $43! Coupon Code: LaracastsLovesPackt https://laracasts.com/signup?plan=yearly&coupon=LaracastsLovesPackt.
Read more about Alfred Nutile

View More author details
Right arrow

Chapter 7. Authentication, Security, and Subscriptions

In this chapter, we will cover the following topics:

  • Using policies and guard to protect user pages

  • Adding feature flags to hide features from users

  • Implementing Socialite to allow users to login with Facebook

  • Adding custom middleware to protect the user admin area

  • Using Laravel to set up a subscription site

  • Creating an interface for the user to manage subscriptions

  • Creating an admin interface for subscriptions

Introduction


This chapter will cover many of the day-to-day workflows that are needed to protect your site, manage subscriptions, and administer users.

By the time you are done, you will have a better understanding of how these features work and when to use them.

Using policies and guard to protect user pages


Here, I am going to show how we can use gate to keep users from deleting other people's Favorites.

Getting ready

A fresh install of Laravel will do. But if you have followed along this far, you will have all the routes and controllers in place.

How to do it...

  1. Using Artisan, we will make a policy as follows:

    > php artisan make:policy FavoriteDeletePolicy
    
  2. It will create a file called app/Policies/FavoriteDeletePolicy.php.

  3. Then, we register it with the app/Providers/AuthServiceProvider.php class:

    Register Policy

  4. Now, we update the policy to have delete just as model:

  5. Then, we will plug the gate into the controller called app/Http/Controllers/FavoriteRemove.php:

  6. Once this is done, you will see how users are rejected if they do not own Favorite; for a moment, I will update the policy to be this—the opposite of what we really want—just for example:

    This is the response that they will get:

    Failed Response

  7. You will see that it works correctly if we put it back...

Adding feature flags to hide features from users


Now that we did gate, let's use a library with gate Laravel feature flag, so we can show and hide features based on the user who logs in!

This can really be a big deal. Say, I am not ready to show any user, but myself, a feature, then when I login, I can see it working. But when I am ready for another user to see it, I can then add features to the list of people who can see it.

Getting ready

I am going to use the install from the start of this recipe book, but you can just jump in as we just need two users to try this out.

How to do it…

  1. First, I will make sure I have two users.

  2. Then, I will install the library per it's instructions:

    > composer require alfred-nutile-inc/laravel-feature-flag
    
  3. Now, let's load the provider:

  4. Let's run the migration for this library:

    >php artisan vendor:publish --\ provider="AlfredNutileInc\LaravelFeatureFlags\FeatureFlagsProvider" --tag='migrations'
    
  5. Now, let's add a migration based on their example to put this in...

Implementing Socialite to allow users to login with Facebook


Keep the track of passwords is not fun. In this section, we are going to make the app allow the user to login using Facebook! Thanks to Socialite this is super easy.

Getting ready

A fresh install of Laravel will do as I am going to work it into my existing comic book app.

How to do it…

  1. Install the Socialite library. Make sure you read its docs for the steps needed to get the setup at https://github.com/laravel/socialite.

  2. Set up config/services.php to add Facebook:

    Adding ENV settings

  3. Make a controller:

    >php artisan make:controller FacebookAuthController
    
  4. Set up the controller to do some work:

  5. Get your key from Facebook at https://developers.facebook.com/. They have made this fairly very easy. In the end, I ended up with this dash:

  6. Now, plug in app ID and app secret into your .env file, since we will use this in config/service.php:

    Adding settings to .env

  7. Let's update the app/Http/routes.php route to give us the two routes that we need:

  8. Update...

Adding custom middleware to protect user admin area


In this section, I am going to use middleware to protect an admin area. We will build this area as our user admin area later, but for now I just want to show how to implement middleware that makes sure that the user is the admin.

Getting ready

Base install of Laravel with users imported.

How to do it…

  1. First, I am going to add a new field to the user table to set some users as admins:

    > php artisan make:migration alter_user_table_add_is_admin
    
  2. I will edit the database/migrations/2016_05_21_132909_alter_user_table_add_is_admin.php file so that it looks as follows:

    Migration

  3. Then, I will make middleware to consider this:

    > php artisan make:middleware IsAdminMiddleWare
    
  4. I will then edit the app/Http/Middleware/IsAdminMiddleWare.php file, so it looks like this:

  5. Then, I will update app/Http/Kernel.php to include the new is_admin middleware:

  6. Then, I will make the route for this admin area, which, right now, will not return much; but later on it will...

Using Laravel to set up a subscription site


So, you want to take memberships! I will show you how to add a subscription service to our site. We will use Stripe to take subscriptions and use Laravel's Cashier to make it rather easy. This will go into more template and Stripe details rather than Laravel docs.

Getting ready

The base install is fine. Also, make sure that you migrate your users so that we have this in place too.

How to do it…

  1. First, read the docs on Laravel at https://laravel.com/docs/master/billing and then follow along.

  2. Now, install the library in line with https://github.com/laravel/cashier and the main docs.

  3. I will set up my .env file to look like this:

    Make sure the keys are just like they are in the docs and making sure I put public key in the right place, which is prefixed by pk and secret key by sk.

  4. Then, I update config/services.php, which is needed to match the preceding keys:

  5. Then, I set up my routes to handle the traffic while I keep in mind that this is inside the default...

Creating an interface for the user to manage subscriptions


Alright, the preceding recipe made it possible for people to subscribe, but what happens when they want to change the plan or cancel it!

I will cover making an area where they can update or swap out their plan. You can take this much further at the UI level. I am keeping it very simple.

Getting ready

See the preceding recipes, as you really need to have the cashier set up to get this far.

How to do it…

  1. I will make a controller to keep our logic in one controller:

    > php artisan make:controller SubscriptionSwapController
    
  2. Then, I will make the route for this controller:

  3. Now, to add some logic to the repository class called app/Repositories/SubscribeRepository.php, the controller uses:

  4. Update the previous view for resources/views/stripe/status.blade.php:

  5. Now, the UI will look like this at /user/membership:

  6. When you press the button:

  7. That's it! It will swap out memberships for you and make a new invoice.

How it works…

Like I said at the start...

Creating an admin interface for subscriptions


In this section, I will cover making a place for an admin user to come in and see reports about members. This will need some seed data, as I will attempt to show the membership statuses in one place.

We will aim for something as follows:

Getting ready

If you have not followed this far, then you will need at least a base Laravel installed with the cashier and auth setups.

How to do it…

  1. Set up a route for the admin dashboard:

  2. Make a controller for the route:

    >php artisan make:controller AdminMembershipsDashboardController
    
  3. Let's protect the app/Http/Controllers/AdminMembershipsDashboardController.php controller:

  4. Now, we need to add middleware to check whether this user is an admin. I already added is_admin as a boolean field on the users table; see Chapter 5, Working with Data; we also created middleware using Chapter 7, Authentication, Security and Subscriptions to protect the user admin area, so we know this is protected.

  5. Seed some users with subscriptions...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Laravel 5.x Cookbook
Published in: Sep 2016Publisher: PacktISBN-13: 9781786462084
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Authors (2)

author image
Terry Matula

Terry Matula is a web developer and Laravel advocate based in Austin, TX. He's been a passionate computer enthusiast since he first played Oregon Trail on an Apple//e. He started programming in BASIC at a young age, making simple Scott Adams-like games on a Commodore Vic-20. Since then, he's worked as a developer using Flash/ActionScript, ASP.NET, PHP, and numerous PHP frameworks, with Laravel being his favorite by far. He blogs web development tips and tricks at his website http://terrymatula.com
Read more about Terry Matula

author image
Alfred Nutile

Alfred Nutile is an Enterprise Architect and Laravel lead based in Western Massachusetts. He's been working in the industry since the mid 90's. He started in PHP and MySQL back around that time and has worked with Ruby on Rails, Drupal, and Angular along the way. He introduced Laravel into an enterprise web stack, where he is currently contracted at, as Laravel proved itself as an amazing framework to build API's and Angular heavy application. You can read more about him and checkout his blog at http://www.alfrednutile.info/ or follow him on Twitter at https://twitter.com/alnutile Make sure to checkout the discount LaraCasts is offering those who buy the book! Get a coupon for 50% on your first bill. Make it a yearly subscription and save $43! Coupon Code: LaracastsLovesPackt https://laracasts.com/signup?plan=yearly&coupon=LaracastsLovesPackt.
Read more about Alfred Nutile