Simple Example of Laravel 5 Login System Using Sentry

I will be demonstrate simple Laravel authentication using sentry.Already I have shared Simple theming with laravel 5 and introduction of Authorization and Authentication of Users in laravel 5 Using Sentry.

I got huge response and request about full register and login system using laravel 5 with sentry, so let’s start entire process of authorization and authentication of users.

We will go through following steps :

  • Configure Sentry with Laravel 5
  • I will create authorization sentry package tables using migration
  • Created Login/register and thanks ui pages using Gentellela Admin bootstrap theme, you can get more information from theming in laravel 5 this tutorial
  • .

  • Routing using sentry methods and laravel 5.
  • Created login/register and forgot_password action method in controller and render UI.

How to configure Sentry with Laravel 5:

Step 1: You need to add dependency in composer.php file like below,

Select Code
1
2
3
4
5
"require": {
        ....,
        ....,
    "cartalyst/sentry": "dev-feature/laravel-5"
    }

Step 2: Add providers and aliases in config/app.php file.

Added senetry in provider array

Select Code
1
2
3
4
'providers' => [ 
  .....
  Cartalyst\Sentry\SentryServiceProvider::class
 ]

Added in aliases array

Select Code
1
2
3
'aliases' => [
      'Sentry' => Cartalyst\Sentry\Facades\Laravel\Sentry::class,
    ]

You can also check other recommended tutorials of Lumen/Laravel,

Step 3: in command line run composer update or install composer command to install sentry dependency.

D:\xampp\htdocs\testlogin> composer update

Now you have configured sentry with your project.

How to Migrate Database table of Sentry package in Laravel 5

Please make sure your database connected with laravel projects,if not please check config/database.php or you can configure using .env file.

php artisan vendor:publish --provider="Cartalyst\Sentry\SentryServiceProvider"

Now added theme and layout for login and register view,You can get more information from Simple Laravel Layouts using Blade Template and Bootstrap Theme tutorial.

Defining routemiddleware class to verify logged-in user and guest.We need to add below lines in Http/kernel.php file.

Select Code
1
2
'Sentry_isGuest' => \App\Http\Middleware\VerifySentryGuest::class,
'Sentry_isLoggedIn' => \App\Http\Middleware\VerifySentryLoggedIn::class,

Created VerifySentryGuest.php file in App\Http\Middleware\ folder and put below code into this file.

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php

namespace App\Http\Middleware;

use Closure;
use Sentry;

class VerifySentryGuest
{
    
    public function handle($request, Closure $next)
    {
        if (!Sentry::check()) 
        {           
          return $next($request);           
        }

        return redirect('user/home');
    }
}

Created VerifySentryLoggedIn.php file in App\Http\Middleware\ folder and put below code into this file.

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php

namespace App\Http\Middleware;

use Closure;
use Sentry;

class VerifySentryLoggedIn
{
    
    public function handle($request, Closure $next)
    {
        if (Sentry::check()) 
        {           
          return $next($request);           
        }

        return redirect('user/login');
    }
}

We will refine User model , we need to open app/User.php file and delete all content, We need to add below code into this file.

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php

namespace App;

use Cartalyst\Sentry\Users\Eloquent\User as SentryModel;

class User extends SentryModel
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Here we are using SentryModel User model class that can be later use in user controller file.

We will create new user controller in Laravel 5 using below command

D:\XAMPP\htdocs\test_login>php artisan make:controller UserController

Above command will create UserController.php file in controller directory.

Define Routing In laraval 5 Using Sentry

Now added routes in /app/http/route.php file

Select Code
1
2
3
4
5
6
7
8
9
10
// Guest Access
Route::group(array('middleware' => 'Sentry_isGuest'), function()
{
  Route::match(array('get', 'post'), 'user/login', 'UserController@login');
  Route::match(array('get', 'post'), 'user/register', 'UserController@register');
  Route::get('user/register_thanks', 'UserController@registerThanks');
  Route::get('/', function(){
        return redirect('user/login');
    });
});

Here we have added guest route, The Guest user can access login,register and thanks page.We are redirecting user to login page if user haven’t logged in system or guest.

Now we will defined Logged-in user access page, we can add more route which can be accesses by logged-in user.

Select Code
1
2
3
4
5
6
7
8
9
// Authenticated 
Route::group(array('middleware' => 'Sentry_isLoggedIn'), function()
{
  Route::get('user/dashboard', 'UserController@dashboard');
  Route::get('user/logout', 'UserController@logout');
  Route::get('/', function(){
        return redirect('user/dashboard');
    }); 
});

So we have defined all routes that need for authenticate user.

We will create new Register view file register.blade.php in resources/views/user/guest/ folder and use below code.

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
@extends('layouts.default')
@section('content')

<?php if(!empty($error_msg)): ?>
        <div class="alert alert-danger alert-dismissible" role="alert">
          <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">×</span>
          </button>
          <?php echo $error_msg; ?>
        </div>
        <?php endif; ?>

        <?php if (count($errors) > 0): ?>
        <div class="alert alert-danger">
          <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">×</span>
          </button>
          <ul>
             <?php foreach ($errors as $error): ?>
              <li><?php echo $error; ?></li>
              <?php endforeach; ?>
          </ul>
        </div>
       <?php endif; ?>
<form action="<?php echo url('user/register'); ?>" method="post" id="registrationForm" novalidate>
   <input type="hidden" name="_method" value="POST">
          <input type="hidden" name="_token" value="{{ csrf_token() }}">
  <div id="signup-box" class="signup-box widget-box no-border visible">
                  <div class="widget-body">
                    <div class="widget-main">
                      <h4 class="header green lighter bigger">
                        <i class="ace-icon fa fa-users blue"></i>
                        New User Registration
                      </h4>

                      <div class="space-6"></div>
                      <p> Enter your details to begin: </p>

                      
                        <fieldset>
                          <label class="block clearfix">
                            <span class="block input-icon input-icon-right">
                              <input type="email" class="form-control" placeholder="Email" id="email" name="email" value="<?php echo isset($input['email']) ? $input['email'] : ''; ?>">
                              <i class="ace-icon fa fa-envelope"></i>
                            </span>
                          </label>
                          
                          <label class="block clearfix">
                            <span class="block input-icon input-icon-right">
                              <input type="text" class="form-control" placeholder="First Name" id="first_name" name="first_name" value="<?php echo isset($input['first_name']) ? $input['first_name'] : ''; ?>">
                              <i class="ace-icon fa fa-user"></i>
                            </span>
                          </label>
                          
                          <label class="block clearfix">
                            <span class="block input-icon input-icon-right">
                              <input type="text" class="form-control" placeholder="Last Name" id="last_name" name="last_name" value="<?php echo isset($input['last_name']) ? $input['last_name'] : ''; ?>">
                              <i class="ace-icon fa fa-user"></i>
                            </span>
                          </label>

                          <label class="block clearfix">
                            <span class="block input-icon input-icon-right">
                              <input type="password" class="form-control" placeholder="Password" id="password" name="password">
                              <i class="ace-icon fa fa-lock"></i>
                            </span>
                          </label>

                          <label class="block clearfix">
                            <span class="block input-icon input-icon-right">
                              <input type="password" class="form-control" placeholder="Repeat password" id="confirm_password" name="confirm_password">
                              <i class="ace-icon fa fa-retweet"></i>
                            </span>
                          </label>

                          <label class="block">
                            <input type="checkbox" class="ace">
                            <span class="lbl">
                              I accept the
                              <a href="#">User Agreement</a>
                            </span>
                          </label>

                          <div class="space-24"></div>

                          <div class="clearfix">
                            <button type="reset" class="width-30 pull-left btn btn-sm">
                              <i class="ace-icon fa fa-refresh"></i>
                              <span class="bigger-110">Reset</span>
                            </button>

                            <button type="submit" class="width-65 pull-right btn btn-sm btn-success">
                              <span class="bigger-110">Register</span>

                              <i class="ace-icon fa fa-arrow-right icon-on-right"></i>
                            </button>
                          </div>
                        </fieldset>
                      </form>
                    </div>

                    <div class="toolbar center">
                      <a href="<?php echo url('user/login'); ?>" class="back-to-login-link">
                        <i class="ace-icon fa fa-arrow-left"></i>
                        Back to login
                      </a>
                    </div>
                  </div><!-- /.widget-body -->
                </div>
                
              

@stop

Added controller method in UserController.php file to register user,

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
public function register(Request $Request){
      
      $input = array();
      $error_msg = '';
      $errors = array();
      
      if($Request->isMethod('post')){
        
        $input = $Request->all();
      

        $rules = array(
          'first_name' => 'required|string|min:2',
        'last_name' => 'required|string|min:2',
            'email'    => 'required|email|unique:users,email', 
            'password' => 'required|min:5',
            'confirm_password' => 'required|min:5|same:password',

        );

        $validator = Validator::make($input, $rules);

        if ($validator->fails()){
        $errors = $validator->errors()->all();
        }
        else{
          try
        {
           
            $user = Sentry::register(array(
            'first_name'    => $input['first_name'],
                'last_name'     => $input['last_name'],
                'email'     => $input['email'],
                'password'    => $input['password'],
                'activated'    => 1,
            ));
          

          
          $Request->session()->flash('activation_email', $input['email']);

          return redirect('user/register_thanks');

        }
        catch (\Cartalyst\Sentry\Users\LoginRequiredException $e)
        {
            $error_msg =  'Login field is required.';
        }
        catch (\Cartalyst\Sentry\Users\PasswordRequiredException $e)
        {
            $error_msg = 'Password field is required.';
        }
        catch (\Cartalyst\Sentry\Users\UserExistsException $e)
        {
            $error_msg = 'User with this login already exists.';
        } 
        catch (\Cartalyst\Sentry\Groups\GroupNotFoundException $e)
        {
            
        }                 
        }
      }

      return view('user.guest.register', array(
          'input' => $input,
          'error_msg' => $error_msg,
          'errors' => $errors,          
        ));
    }

Now open http://localhost/laraveltest/user/register on browser,You can see register page.You need to fill all details and click submit button after successfully validate all fields you will redirected on Thankspage which is not created yet, now we will create thanks page.

laravel register

We will create register.blade.php file in resources/view/pages/ folder and added below code

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@extends('layouts.default')

@section('title', 'Thanks for registration')

 
@section('content')
    <div class="register-box" style="width:auto;margin-left:20px;margin-right:20px;">
      <div class="register-logo">
         <a href="<?php echo url('/'); ?>"><b>Test </b></a>
      </div>

      <div class="alert alert-success" role="alert">
        <h1>Thanks for registration!</h1>
        <h3>An email has been sent to your email address "<?php echo $email; ?>" for activating account. If account is not activated within one month then it will be deleted automatically.</h3>
      </div>
    </div><!-- /.register-box -->    
@endsection

thanks page

Added action in UserController.php file

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public function registerThanks(Request $Request){   
    $email = $Request->session()->pull('activation_email');
            
      if(!empty($email)){

        $Request->session()->forget('activation_email');

        return view('pages.register_thanks', array(
          'email' => $email
        ));
      } 
      else{
        return redirect('/');
      }  
         
      
    }

Now we will create login page and controller action,create Login view file login.blade.php in resources/views/user/guest/ folder and add below code into this file.

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
@extends('layouts.default')
@section('content')
 <?php if(!empty($message)): ?>
          <div class="alert alert-success alert-dismissible" role="alert">
          <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">×</span>
          </button>
          <?php echo $message; ?>
        </div>
       <?php endif; ?>
       
       <?php if(!empty($error_msg)): ?>
        <div class="alert alert-danger alert-dismissible" role="alert">
          <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">×</span>
          </button>
          <?php echo $error_msg; ?>
        </div>
        <?php endif; ?>
<form action="<?php echo url('user/login'); ?>" method="post" id="loginForm" novalidate>
    <input type="hidden" name="_method" value="POST">
          <input type="hidden" name="_token" value="{{ csrf_token() }}">
  <div id="login-box" class="login-box visible widget-box no-border">
                  <div class="widget-body">
                    <div class="widget-main">
                      <h4 class="header blue lighter bigger">
                        <i class="ace-icon fa fa-coffee green"></i>
                        Please Enter Your Information
                      </h4>

                      <div class="space-6"></div>

                      <form>
                        <fieldset>
                          <label class="block clearfix">
                            <span class="block input-icon input-icon-right">
                              <input type="text" class="form-control" placeholder="Username" id="email" name="email">
                              <i class="ace-icon fa fa-user"></i>
                            </span>
                          </label>

                          <label class="block clearfix">
                            <span class="block input-icon input-icon-right">
                              <input type="password" class="form-control" placeholder="Password" id="password" name="password">
                              <i class="ace-icon fa fa-lock"></i>
                            </span>
                          </label>

                          <div class="space"></div>

                          <div class="clearfix">
                            <label class="inline">
                              <input type="checkbox" class="ace">
                              <span class="lbl"> Remember Me</span>
                            </label>

                            <button type="submit" class="width-35 pull-right btn btn-sm btn-primary">
                              <i class="ace-icon fa fa-key"></i>
                              <span class="bigger-110">Login</span>
                            </button>
                          </div>

                          <div class="space-4"></div>
                        </fieldset>
                      </form>

                      <div class="social-or-login center">
                        <span class="bigger-110">Or Login Using</span>
                      </div>

                      <div class="space-6"></div>

                      <div class="social-login center">
                        <a class="btn btn-primary">
                          <i class="ace-icon fa fa-facebook"></i>
                        </a>

                        <a class="btn btn-info">
                          <i class="ace-icon fa fa-twitter"></i>
                        </a>

                        <a class="btn btn-danger">
                          <i class="ace-icon fa fa-google-plus"></i>
                        </a>
                      </div>
                    </div><!-- /.widget-main -->

                    <div class="toolbar clearfix">
                      <div>
                        <a href="<?php echo url('user/forgot_password'); ?>" class="forgot-password-link">
                          <i class="ace-icon fa fa-arrow-left"></i>
                          I forgot my password
                        </a>
                      </div>

                      <div>
                        <a href="<?php echo url('user/register'); ?>" class="user-signup-link">
                          I want to register
                          <i class="ace-icon fa fa-arrow-right"></i>
                        </a>
                      </div>
                    </div>
                  </div><!-- /.widget-body -->
                </div><!-- /.login-box -->
              </form>

@stop

Added login() controller method in UserController.php file to login user,

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
public function login(Request $Request){
    //print_R($Request);
      $error_msg = '';
      $errors = array();
      $message  = '';
    
      $message = $Request->session()->pull('message');

      if(!empty($message)){         
        $Request->session()->forget('message');
      }

      if($Request->isMethod('post')){

        $input = $Request->all();

        $rules = array(
            'email'    => 'required|email', 
            'password' => 'required'
        );

        $validator = Validator::make($input, $rules);

        if ($validator->fails()){

          $errors = $validator->errors()->all();      
        }
        else{

          try
        {
            $credentials = array(
                'email'    => $input['email'],
                'password' => $input['password'],
            );

            $user = Sentry::authenticate($credentials, false);
            
            if(Sentry::check()){

              return redirect('user/dashboard');
            }
        }
        catch (\Cartalyst\Sentry\Users\LoginRequiredException $e)
        {
            $error_msg =  'Login field is required.';
        }
        catch (\Cartalyst\Sentry\Users\PasswordRequiredException $e)
        {
            $error_msg = 'Password field is required.';
        }
        catch (\Cartalyst\Sentry\Users\WrongPasswordException $e)
        {
            $error_msg = 'Wrong password, try again.';
        }
        catch (\Cartalyst\Sentry\Users\UserNotFoundException $e)
        {
            $error_msg = 'User was not found.';
        }
        catch (\Cartalyst\Sentry\Users\UserNotActivatedException $e)
        {
            $error_msg = 'User is not activated.';
        }
        // The following is only required if the throttling is enabled
        catch (\Cartalyst\Sentry\Throttling\UserSuspendedException $e)
        {
            $error_msg = 'User is suspended.';
        }
        catch (\Cartalyst\Sentry\Throttling\UserBannedException $e)
        {
            $error_msg = 'User is banned.';
        } 
        catch(\Exception $e)
        {
          $error_msg = $e->getMessage();
        }
        }
    }
      
    return view('user.guest.login', array(
        'error_msg' => $error_msg,
        'errors' => $errors,
        'message' => $message
      ));
    }

Now open http://localhost/laraveltest/user/login on browser,You can see login page.You need to fill email and password and click login button after successfully validate all fields you will redirected on Dashboard page which is not created yet, now we will create Welcome Dashboard page.

login laravel

We will create new dashboard.blade.php file in resources/views/member/ folder and put below code into this file,

Select Code
1
2
3
4
@extends('layouts.master')
@section('content')
  <div class="page-content">this is my home page</div>
@stop

Now we will create Dashbord action methos in UserController.php file,

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
public function dashboard(){  

      $user = Sentry::getUser();

      $params = array(
          'id' => $user->id,
          'name' => $user->name,
          'last_login' => $user->last_login,
        );  
      
      return view('user.member.dashboard', $params);
    }

Finally define logout controller action, We need to add new below method in UserController.php file.

Select Code
1
2
3
4
5
6
7
8
9
public function logout(Request $Request){

      Sentry::logout();

      $Request->session()->flash('message', 'You have been sign out.');

      return redirect('user/login');

    }

Conclusion

This laravel 5 tutorial help to understand login,register and logout functionality using sentry package.You can authenticate user using this laravel 5 tutorial and redirect user to dashboard.We have also learnt about add layout using blade template in laravel 5 with database migration script.