Ranjan Goyal
Ranjan Goyal

Reputation: 73

Laravel 5.0, Admin and front end users

I am new to Laravel and using version 5.0.

My website will have users on the front-end and obviously website will have admin.

Problem I am facing is that non admin users are also able to login into admin panel.

How to NOT ALLOW frontend users from entering into admin?

Please also see if I am doing the things in correct way and if not then what is the correct way.

My routes.php is given below

Route::get('home', 'HomeController@index');
Route::get('consign', 'HomeController@showConsignment');
Route::post('processConsignment', 'HomeController@processConsignment');

Route::get('login', array('uses' => 'HomeController@showLogin'));
Route::post('login', array('uses' => 'HomeController@doLogin'));
Route::get('logout', array('uses' => 'HomeController@doLogout'));

Route::controllers([
    'auth' => 'Auth\AuthController',
    'password' => 'Auth\PasswordController',
]);

// Admin area
get('admin', function () {
  return redirect('/admin/dashboard');
});

$router->group([
  'namespace' => 'Admin',
  'middleware' => 'auth',
], function () {
  resource('admin/dashboard', 'DashboardController');
  resource('admin/auction', 'AuctionController');
  resource('admin/auctionlot', 'AuctionLotController');
  resource('admin/video', 'VideoController');
});

// Logging in and out
get('/auth/login', 'Auth\AuthController@getLogin');
post('/auth/login', 'Auth\AuthController@postLogin');
get('/auth/logout', 'Auth\AuthController@getLogout');

The relevant portion of HomeController is given below

public function showLogin(){
    // show the form
    return View('home.login');

}

public function doLogin(){

    // validate the info, create rules for the inputs
    $rules = array(
        'email'    => 'required|email', // make sure the email is an actual email
        'password' => 'required|alphaNum|min:3' // password can only be alphanumeric and has to be greater than 3 characters
    );

    // run the validation rules on the inputs from the form
    $validator = Validator::make(Input::all(), $rules);

    // if the validator fails, redirect back to the form
    if ($validator->fails()) {
        return Redirect::to('login')
            ->withErrors($validator) // send back all errors to the login form
            ->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form
    } else {

        // create our user data for the authentication
        $userdata = array(
            'email'     => Input::get('email'),
            'password'  => Input::get('password'),
            'active'    => '1',
            'role'      => 'user'
        );

        // attempt to do the login

        if (Auth::attempt($userdata)) {
            // validation successful!
            // redirect them to the secure section or whatever
            // return Redirect::to('secure');
            // for now we'll just echo success (even though echoing in a controller is bad)

            return Redirect::to('home');

        } else {        

            // validation not successful, send back to form 
            return Redirect::to('login');

        }

    }
}//doLogin

This means I have separate forms for admin and front-end users

My USERS table structure is given below

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `role` enum('admin','user') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'user',
  `active` enum('1','0') COLLATE utf8_unicode_ci NOT NULL,
  `remember_token` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `users_email_unique` (`email`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=4 ;

Please help.

Thanks,

Upvotes: 1

Views: 4051

Answers (2)

Achraf Khouadja
Achraf Khouadja

Reputation: 6279

This can be solved pretty easily by using Middleware (http://laravel.com/docs/5.0/middleware) First lets create the middleware, you can call it whatever, let's say AdminMiddleware

php artisan make:middleware AdminMiddleware

Now that we have our middleware, we need to edit it and specify what we want it to do. In App\Http\Middleware you should see the newly created file

The AdminMiddleware we just created

<?php namespace App\Http\Middleware;

use Closure;

class AdminMiddleware {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->user()->type != 'admin') 
        {
            return redirect('home');
        }

        return $next($request);
    }

}

What we are doing here, is taking the user and checking to see if the type is A if not.. redirect home. Now that we have that, we need to use it in the routes.php file.

Routes file

Route::group(['middleware' => 'App\Http\Middleware\AdminMiddleware'], function()
{
    Route::get('/admin', function()
    {
        // can only access this if type == admin
    });

});

Hopefully that helps!

The answer is copied from HERE

Upvotes: 3

nothing123456
nothing123456

Reputation: 543

What I do in my applications is during the login process once they have been validated I will write some relevant information to the session and then create a middleware check on any relevant URL and check the session in the middleware.

In your case you would want to write their role to a session variable and check it in the middleware.

For example:

routes.php

I would put all endpoints I want to protect in a route group:

Route::group(['middleware' => 'auth'], function()
{
   resource('admin/dashboard', 'DashboardController');
   resource('admin/auction', 'AuctionController');
   resource('admin/auctionlot', 'AuctionLotController');
   resource('admin/video', 'VideoController');
});

Putting role into session in HomeController

    $sess_array = [
        'user_role'       => $user_role, // From what you got from DB 
        'user_email'      => $user->sup_email,
        'active'          => '1',
    ];
    $request->session()->put($sess_array);

auth middleware

  public function handle(Request $request, Closure $next)
{

           if($request->session()->get('user_role') ! == 'admin') {
               return $next($request);
           } else {
               return redirect('login');
           }

}

It's a little oversimplified example but I hope you get the gist?

Upvotes: 0

Related Questions