4elements, web design and consultancy

  1. Setting Up User Authentication in Laravel Using Confide

    User authentication is part of almost every web application. Although it is common, a deeper look shows that it’s not as simple as it may seem. Remember that validation, password recovery, and email confirmation are vital to any decent authentication form.

    Confide is an authentication solution for Laravel made to reduce the repetitive work involving the management of users. It's a DRY approach on features like account creation, login, logout, confirmation by e-mail, password reset, etc.

    Since the early versions, Confide always had good adoption among developers and a wide presence in Laravel projects. With a recent update, the package is now compatible with Laravel 4.2 which is the latest stable release of Laravel at the time of this writing.

    What We Are Going to Do

    In this tutorial, we’ll start from the very beginning by creating our Laravel app using Composer and then:

    • create a signup form with a full set of validation rules
    • a login form with a "forgot my password" option that will send a link for the user to redefine his password
    • use Laravel filters to only allow logged users can access a specific route.

    Creating the Application

    First of all, let's create the application using Composer.

    $ composer create-project laravel/laravel myapp

    Installing Confide

    Now, with inside the project directory, edit the require key of composer.json file and include confide entry:

    "require": { "laravel/framework": "~4.2", "zizaco/confide": "~4.0@dev" },

    Then run composer update on our new dependency:

    $ composer update zizaco/confide

    In config/app.php of our project, add 'Zizaco\Confide\ServiceProvider' to the end of the providers array:

    ... 'providers' => array( 'Illuminate\Foundation\Providers\ArtisanServiceProvider', 'Illuminate\Auth\AuthServiceProvider', ... 'Zizaco\Confide\ServiceProvider', ), ...

    Also add 'Confide' => 'Zizaco\Confide\Facade' to the aliases array in the same file:

    ... 'aliases' => array( 'App' => 'Illuminate\Support\Facades\App', 'Artisan' => 'Illuminate\Support\Facades\Artisan', ... 'Confide' => 'Zizaco\Confide\Facade', ),

    Set the address and name in config/mail.php. This config will be used to send account confirmation and password reset emails to the users. For this tutorial, you can use your personal SMTP server to get things working

    For example, if you use Gmail you can do the following:

    'driver' => 'smtp', 'host' => 'smtp.gmail.com', // For testing purposes 
    'from' => array( 'address' => 'youremail@gmail.com', 'name' => 'MyApp' ), ... 'username' => 'youremail@gmail.com', 'password' => '<password>, ...

    User model

    Now generate the Confide migrations by running:

    $ php artisan confide:migration $ php artisan migrate

    This will setup a table containing email, password, remember_token, confirmation_code and confirmed columns. These are the default fields needed for Confide. Feel free to add more columns to the table later.

    Replace all the code in app/models/User.php to:

    <?php 
    use Zizaco\Confide\ConfideUser; 
    use Zizaco\Confide\ConfideUserInterface; 
    
    class User extends Eloquent implements ConfideUserInterface { 
        use ConfideUser; 
    }

    Zizaco\Confide\ConfideUser trait will take care of most behaviors of the user model.

    UsersController and Routes

    Confide contains a generator tool that will create a controller and write the routes for us. To create the UsersController and to register the routes let's run these commands:

    $ php artisan confide:controller 
    $ php artisan confide:routes

    Since new classes have been created, we will need to refresh the autoload files.

    $ composer dump-autoload

    Ready to Use

    We are done! Our application now has all of the features that Confide offers. Run the application server by calling php artisan serve in the terminal.

    The following GET routes are available in our application:

    http://localhost:8000/users/create 
    http://localhost:8000/users/login 
    http://localhost:8000/users/forgot_password

    To access the current user we can call Confide::user(). Therefore, to show the name of the current user we need to replace the content of app/views/hello.php with:

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>User auth with Confide</title>
    </head>
    <body>
        <h1>Hello Confide</h1>
        <p>
            Hi
            <?php echo (Confide::user() ?: 'visitor') ?>
        </p>
    </body>
    </html>
    

    Now go ahead and access http://localhost:8000/users/create to create our first user. You will receive a confirmation email right after submitting the form (if you have filled the config/mail.php with the correct values). Log-in and you will see the username on the screen.

    Displaying the username on the page

    Improving Visuals

    The default forms of Confide are compatible with Bootstrap. So don't be intimidated by the "ugliness" of them on a page without any CSS. Edit the controller generated by Confide (UserController.php) and update the create method to:

    <?php
    
    public function create() { 
        return View::make('users.signup'); 
    }

    Thus our application will render the View users.signup. Let's create this view in app/views/users as signup.blade.php with the following content:

    <!doctype html> 
    <html lang="en"> 
        <head> 
            	<meta charset="UTF-8"> 
            	<title>User auth with Confide</title> 
            	{{-- Imports twitter bootstrap and set some styling --}} 
            	<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"> 
    		<style> 
    		body { background-color: #EEE; } ‘
    		.maincontent { 
    			background-color: #FFF; 
    			margin: auto; 
    			padding: 20px; 
    			width: 300px; 
    			box-shadow: 0 0 20px #AAA;
    		} 
    		</style> 
    	</head> 
    	<body> 
    		<div class="maincontent"> 
    			<h1>Signup</h1> 
    			{{-- Renders the signup form of Confide --}}
    			{{ Confide::makeSignupForm()->render(); }} 
    		</div> 
    	</body> 
    </html>

    After this, we will have a much more elegant result in the user creation form on http://localhost:8000/user/create:

    Improved Signup form

    You don't have to use the forms generated by Confide. You can create your own view that sends data to the POST routes.

    Restricting Access

    Open app/routes.php and add the code below to the bottom of the file:

    // Dashboard route 
    Route::get('userpanel/dashboard', function(){ return View::make('userpanel.dashboard'); }); 
    
    // Applies auth filter to the routes within admin/ 
    Route::when('userpanel/*', 'auth');

    Create the view file app/views/userpanel/dashboard.blade.php:

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>User auth with Confide</title>
        {{-- Imports twitter bootstrap and set some styling --}}
        <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
        <style>
            body { background-color: #EEE; }
            .maincontent {
                background-color: #FFF;
                margin: 30px auto;
                padding: 20px;
                width: 300px;
                box-shadow: 0 0 20px #AAA;
            }
        </style>
    </head>
    <body>
        <div class="maincontent">
            <h1>{{ Confide::user()->username }}</h1>
            <div class="well">
                <b>email:</b> {{ Confide::user()->email }}
            </div>
         </div>
    </body>
    </html>

    Now that we have applied the filter to all routes within userpanel. We will need a small tweak to ensure that the auth filter will redirect the user to the correct login URL. Edit app/filters.php on line 46 in order to replace return Redirect::guest('login'); with:

    ... return Redirect::guest('users/login'); ...

    That done, the userpanel/dashboard page will only be available for users who are logged into the application. The filter will redirect guest users to the login form and then back to the dashboard once they are logged in.

    Conclusion

    It is possible to note that we were able to quickly set up user authentication for our app. Also, the generated controller, migration and routes can be edited to customize how we will handle each detail.

    We have not focused much on the ConfideUser trait, but I believe it's important to clear things up. Once your model uses the ConfideUser trait, you don't need to worry about implementing the basic logic. At the same time, you still can overwrite the methods and customize them, if necessary.

    We can say that Confide is a DRY approach to user authentication. It offers the convenience of having the functionality out-of-the-box while still allows high customization.

    Check out Confide on GitHub. If you had any issue while following this tutorial, feel free to contact me.

     

    0 Comments

    Leave a comment › Posted in: Daily

0 Comments

Got anything to add?

(Basic HTML is fine)