Laravel(5.0) Basic Acl

By ukmodak | March 31st 2024 10:38:02 AM | viewed 984 times

Laravel(5.0) Basic Acl

Step-1:

Create a controller with the following command in the location app/Http/Controllers/Auth/

	d/xampp/htdocs/projectname> php artisan make:controller Auth\AuthController 
	d/xampp/htdocs/projectname> php artisan make:controller Auth\PasswordController  	

Replace whole following code in the location app/Http/Controllers/Auth/AuthController.php

 

<?php namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\Registrar;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\User;
use Carbon\Carbon;
use Session;
use Auth;

class AuthController extends Controller {

	/*
	|--------------------------------------------------------------------------
	| Registration & Login Controller
	|--------------------------------------------------------------------------
	|
	| This controller handles the registration of new users, as well as the
	| authentication of existing users. By default, this controller uses
	| a simple trait to add these behaviors. Why don't you explore it?
	|
	*/

	use AuthenticatesAndRegistersUsers;

	public function __construct(Guard $auth, Registrar $registrar)
	{
		$this->auth = $auth;
		$this->registrar = $registrar;
		
                
	}

	public function getLogin()
	{
		return view('auth.login');
	}


	public function postLogin(Request $request)
	{
		$this->validate($request, [
			'email' => 'required|email', 'password' => 'required',
		]);

		$credentials = $request->only('email', 'password');

		if ($this->auth->attempt($credentials, $request->has('remember')))
		{
			return redirect()->intended($this->redirectPath());
		}

		return redirect($this->loginPath())
					->withInput($request->only('email', 'remember'))
					->withErrors([
						'email' => $this->getFailedLoginMessage(),
					]);
	}

	protected function getFailedLoginMessage()
	{
		return 'These credentials do not match our records.';
	}

	public function getLogout()
	{
		$this->auth->logout();

		return redirect(property_exists($this, 'redirectAfterLogout') ? $this->redirectAfterLogout : '/');
	}

	public function redirectPath()
	{          
		if (property_exists($this, 'redirectPath'))
		{
                    return $this->redirectPath;
                     			
		}
                
		       //return property_exists($this, 'redirectTo') ? $this->redirectTo : '/';
                
                if(property_exists($this, 'redirectTo')){
                    
                    return $this->redirectTo;  
                    
                }else{
                    
                     if(Auth::user()->hasAnyRole(['superadmin','admin'])){
                                               
                         return 'admin/dashboard';
                  
                      }else if(Auth::user()->hasAnyRole(['user'])){
                           
                          return 'user/index';
                    
                     }else{					 
                          return '/';
                      } 
                    
                }
         
	}


	public function loginPath()
	{
		return property_exists($this, 'loginPath') ? $this->loginPath : '/auth/login';
	}
          
    public function regi()
	{
	    return view('auth.register');
           
	}

	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store(Request $request,$ct)
	{
       
                   $this->validate($request, [
                     'user_name'       => 'regex:/^[A-Za-z0-9-_]{5,20}/',
                     'email' => 'required | email | unique:users',
                     'mobile' => 'required | unique:users',
                    ]);
                   
                   
                  
                   if($ct == $request->input('_token')){
                       
                                                
                        if($request->input('password')==$request->input('password_confirmation')){  
                            
                            $insert = User::create([
                              'first_name'=> $request->input('first_name'),
                              'last_name'=> $request->input('last_name'),
                              'user_name'=> $request->input('user_name'),
                              'email'=> $request->input('email'),
                              'mobile'=> $request->input('mobile'),
                              'password'=> bcrypt($request->input('password')),
                              'remember_token'=> $request->input('_token'),
                              'create_date'=> Carbon::now(),
                              'active' => 1                      
                               ]);
                            
                                  
                              return redirect()->route('/')->with('success','Your Registration successfull');  
                        }else{
                             
                              $request->session()->flash('fail','Your Registration Fail');
                              return redirect()->route('auth/regi');  
                        }

                    }else{
                        
                        $request->session()->flash('fail','Session out, please try again');
                        
                        return redirect()->route('auth/regi'); 
                    }    
                
	}
       
 }
	

Note:Above all code copy from \vendor\laravel\framework\src\Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers.php and customize

Replace whole following code in the location app/Http/Controllers/Auth/PasswordController.php

 

<?php namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Contracts\Auth\PasswordBroker;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Http\Request;

class PasswordController extends Controller {

	/*
	|--------------------------------------------------------------------------
	| Password Reset Controller
	|--------------------------------------------------------------------------
	|
	| This controller is responsible for handling password reset requests
	| and uses a simple trait to include this behavior. You're free to
	| explore this trait and override any methods you wish to tweak.
	|
	*/

	use ResetsPasswords;
 
	public function __construct(Guard $auth, PasswordBroker $passwords)
	{
		$this->auth = $auth;
		$this->passwords = $passwords;
		//$this->middleware('guest');  // put on route.php 
	}
        
        public function getEmail()
	{
		return view('auth.password');
	}

	/**
	 * Send a reset link to the given user.
	 *
	 * @param  Request  $request
	 * @return Response
	 */
	public function postEmail(Request $request)
	{
		$this->validate($request, ['email' => 'required|email']);

		$response = $this->passwords->sendResetLink($request->only('email'), function($m)
		{
			$m->subject($this->getEmailSubject());
		});
                
                print_r($response);die;

		switch ($response)
		{
			case PasswordBroker::RESET_LINK_SENT:
				return redirect()->back()->with('status', trans($response));

			case PasswordBroker::INVALID_USER:
				return redirect()->back()->withErrors(['email' => trans($response)]);
		}
	}

	/**
	 * Get the e-mail subject line to be used for the reset link email.
	 *
	 * @return string
	 */
	protected function getEmailSubject()
	{
		return isset($this->subject) ? $this->subject : 'Your Password Reset Link';
	}

	/**
	 * Display the password reset view for the given token.
	 *
	 * @param  string  $token
	 * @return Response
	 */
	public function getReset($token = null)
	{
		if (is_null($token))
		{
			throw new NotFoundHttpException;
		}

		return view('auth.reset')->with('token', $token);
	}

	/**
	 * Reset the given user's password.
	 *
	 * @param  Request  $request
	 * @return Response
	 */
	public function postReset(Request $request)
	{
		$this->validate($request, [
			'token' => 'required',
			'email' => 'required|email',
			'password' => 'required|confirmed',
		]);

		$credentials = $request->only(
			'email', 'password', 'password_confirmation', 'token'
		);

		$response = $this->passwords->reset($credentials, function($user, $password)
		{
			$user->password = bcrypt($password);

			$user->save();

			$this->auth->login($user);
		});

		switch ($response)
		{
			case PasswordBroker::PASSWORD_RESET:
				return redirect($this->redirectPath());

			default:
				return redirect()->back()
							->withInput($request->only('email'))
							->withErrors(['email' => trans($response)]);
		}
	}

	/**
	 * Get the post register / login redirect path.
	 *
	 * @return string
	 */
	public function redirectPath()
	{
		if (property_exists($this, 'redirectPath'))
		{
			return $this->redirectPath;
		}

		return property_exists($this, 'redirectTo') ? $this->redirectTo : 'admin/dashboard';
	}

}

Note:Above all code copy from \vendor\laravel\framework\src\Illuminate\Foundation\Auth\ResetsPasswords and customize

Step-2:

Create a file login.blade.php in the location Resources/views/auth/ and the following code

@extends('layouts.admin')
@section('content')
<div class="content contentPadding contentBg">
<div class="container-fluid">
	<div class="row">
		<div class="col-md-8 col-md-offset-2">
			<div class="panel panel-default">
				<div class="panel-heading">Login</div>
				<div class="panel-body">
					@if (count($errors) > 0)
						<div class="alert alert-danger">
							
							<ul>
								@foreach ($errors->all() as $error)
									<li>{{ $error }}</li>
								@endforeach
							</ul>
						</div>
					@endif

					<form class="form-horizontal" role="form" method="POST" action="{{route('auth/login')}}">
						<input type="hidden" name="_token" value="{{ csrf_token() }}">

						<div class="form-group">
							<label class="col-md-4 control-label">E-Mail Address</label>
							<div class="col-md-6">
								<input type="email" class="form-control" name="email" value="{{ old('email') }}">
							</div>
						</div>

						<div class="form-group">
							<label class="col-md-4 control-label">Password</label>
							<div class="col-md-6">
								<input type="password" class="form-control" name="password">
							</div>
						</div>

						<div class="form-group">
							<div class="col-md-6 col-md-offset-4">
								<div class="checkbox">
									<label>
										<input type="checkbox" name="remember"> Remember Me
									</label>
								</div>
							</div>
						</div>

						<div class="form-group">
							<div class="col-md-6 col-md-offset-4">
								<button type="submit" class="btn btn-primary" style="margin-right: 15px;">
									Login
								</button>

								<a href="{{route('pass/email')}}">Forgot Your Password?</a>
                                                                @if(Auth::user())
                                                                <a href="{{route('pass/reset')}}">Reset Password</a>
                                                                @endif
							</div>
						</div>
					</form>
				</div>
			</div>
		</div>
	</div>
</div>
</div>
@endsection

 

Create a file register.blade.php in the location Resources/views/auth/ and the following code

@extends('layouts.admin')
@section('content')
<div class="content contentPadding contentBg">
<div class="container-fluid">
	<div class="row">
		<div class="col-md-8 col-md-offset-2">
			<div class="panel panel-default">
				<div class="panel-heading">Register</div>
                                
                               
                                @if(session('success'))
                                <div class="alert alert-success alert-dismissable">
                                 <p>{{{ session('success') }}}</p>
                                </div>
                                @endif
                                @if(session('fail'))
                                <div class="alert alert-success alert-dismissable">    
                                  <p>{{{ session('fail') }}}</p>
                                 </div>
                                @endif
                               
				   <div class="panel-body">
					@if (count($errors) > 0)
						<div class="alert alert-danger">
							<strong>Whoops!</strong> There were some problems with your input.<br>
							<ul>
								@foreach ($errors->all() as $error)
									<li>{{ $error }}</li>
								@endforeach
							</ul>
						</div>
					@endif
                   <div class="panel-body">
					<form class="form-horizontal" role="form" method="POST" action="{{route('auth/store/ct/uk',['ct'=>csrf_token(),'uk'=>''])}}">
						<input type="hidden" name="_token" value="{{ csrf_token()}}">

						<div class="form-group col-md-4">
							<label>First Name</label>
							<div>
								<input type="text" pattern="^[A-Za-z\s]{0,20}" class="form-control" name="first_name" value="{{ old('first_name') }}">
							</div>
						</div>
                        <div class="form-group col-md-4">
							<label>Last Name</label>
							<div>
								<input type="text" pattern="^[A-Za-z\s]{0,20}" class="form-control" name="last_name" value="{{ old('last_name') }}">
							</div>
						</div>
                                                
                        <div class="form-group col-md-4">
							<label>User Name</label>
							<div>
								<input type="text" pattern="^[A-Za-z0-9_-]{5,20}" class="form-control" name="user_name" value="{{ old('user_name') }}">
							</div>
						</div>

						<div class="form-group col-md-4">
							<label>E-Mail</label>
							<div>
								<input type="email" class="form-control" name="email" value="{{ old('email') }}">
							</div>
						</div>
                                                
                        <div class="form-group col-md-4">
							<label>Mobile</label>
							<div>
								<input type="text" pattern="^[(017)|(018)|(016)||(015)]{3}[0-9]{8}" required="required"  class="form-control" name="mobile" value="{{ old('mobile') }}">
							</div>
						</div>
                                                
                        <div class="form-group col-md-4">
							<label>Password</label>
							<div>
								<input type="password" required="required"  class="form-control" name="password">
							</div>
						</div>

						<div class="form-group col-md-4">
							<label>Confirm Password</label>
							<div>
								<input type="password" required="required"  class="form-control" name="password_confirmation">
							</div>
						</div>

						

						<div class="form-group">
							<div class="col-md-12" align="center">
								<button type="submit" class="btn btn-primary">
									Register
								</button>
							</div>
						</div>
					</form>
				</div>
				
			</div>
		</div>
	</div>
</div>
</div>
@endsection

 

Create a file password.blade.php in the location Resources/views/auth/ and the following code

@extends('layouts.admin')
@section('content')
<div class="content contentPadding contentBg">
<div class="container-fluid">
	<div class="row">
		<div class="col-md-8 col-md-offset-2">
			<div class="panel panel-default">
				<div class="panel-heading">Reset Password</div>
				<div class="panel-body">
					@if (session('status'))
						<div class="alert alert-success">
							{{ session('status') }}
						</div>
					@endif
					@if (count($errors) > 0)
						<div class="alert alert-danger">
							<strong>Whoops!</strong> There were some problems with your input.<br>
							<ul>
								@foreach ($errors->all() as $error)
									<li>{{ $error }}</li>
								@endforeach
							</ul>
						</div>
					@endif
					<form class="form-horizontal" role="form" method="POST" action="{{route('pass/email')}}">
						<input type="hidden" name="_token" value="{{ csrf_token() }}">

						<div class="form-group">
							<label class="col-md-4 control-label">E-Mail Address</label>
							<div class="col-md-6">
								<input type="email" class="form-control" name="email" value="{{ old('email') }}">
							</div>
						</div>
						<div class="form-group">
							<div class="col-md-6 col-md-offset-4">
								<button type="submit" class="btn btn-primary">
									Send Password Reset Link
								</button>
							</div>
						</div>
					</form>
				</div>
			</div>
		</div>
	</div>
</div>
</div>
@endsection

Step-3:

Add the following code in Http/routes.php

          
Route::get('auth/login',['uses'=>'Auth\AuthController@getLogin', 'as'=>'auth/login']);    
Route::post('auth/login',['uses'=>'Auth\AuthController@postLogin', 'as'=>'auth/login']); 
Route::get('auth/logout',['uses'=>'Auth\AuthController@getLogout', 'as'=>'auth/logout']);    
Route::get('pass/email',['uses'=>'Auth\PasswordController@getEmail', 'as'=>'pass/email']);   
Route::post('pass/email',['uses'=>'Auth\PasswordController@postEmail', 'as'=>'pass/email']);    
Route::get('pass/reset',['middleware' => 'roles','roles' => ['administrator', 'user'],'uses'=>'Auth\PasswordController@getReset', 'as'=>'pass/reset']);    
Route::post('pass/reset',['middleware' => 'roles','roles' => ['administrator', 'user'],'uses'=>'Auth\PasswordController@postReset', 'as'=>'pass/reset']);    

Route::get('auth/regi',['middleware' => 'guest','uses' => 'Auth\AuthController@regi', 'as' => 'auth/regi']);
Route::post('auth/store/{ct}/{uk?}',['middleware' => ['crsf','guest'],'uses' => 'Auth\AuthController@store', 'as' => 'auth/store/ct/uk']);

Step-4:

Add a new middleware file CheckRole.php in the location in Http/Middleware/ and add whole of the following code

<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\RedirectResponse;
class CheckRole
{
    
    public function handle($request, Closure $next)     // this method will hit when call this middleware on url submit
	{
		$roles = $this->getRequiredRoleForRoute($request->route());                                                     	
		if($request->user()->hasAnyRole($roles))                
		{                                                                                              
			return $next($request);
		}else{
                    $request->session()->flash('success','You are welcome to public dashboard');
                    return new RedirectResponse(url('/'));                       
                }      
	}
	private function getRequiredRoleForRoute($route)
	{
		$actions = $route->getAction();
		return isset($actions['roles']) ? $actions['roles'] : null;
	}
}

Replace all of the following code in the location Http/Middleware/Authenticate.php

<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;

class Authenticate {

	/**
	 * The Guard implementation.
	 *
	 * @var Guard
	 */
	protected $auth;

	/**
	 * Create a new filter instance.
	 *
	 * @param  Guard  $auth
	 * @return void
	 */
	public function __construct(Guard $auth)
	{
		$this->auth = $auth;
	}

	/**
	 * Handle an incoming request.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 * @return mixed
	 */
	public function handle($request, Closure $next)
	{
		if ($this->auth->guest())
		{
			if ($request->ajax())
			{
				return response('Unauthorized.', 401);
			}
			else
			{
				return redirect()->guest('auth/login');
			}
                    
                        
		}

		return $next($request);
	}

}

Replace all of the following code in the location Http/Middleware/RedirectIfAuthenticated.php

<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\RedirectResponse;

use App\User;
use App\Models\Auth\Role;

class RedirectIfAuthenticated {

	/**
	 * The Guard implementation.
	 *
	 * @var Guard
	 */
	protected $auth;

	/**
	 * Create a new filter instance.
	 *
	 * @param  Guard  $auth
	 * @return void
	 */
	public function __construct(Guard $auth)
	{
		$this->auth = $auth;
	}

	/**
	 * Handle an incoming request.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 * @return mixed
	 */
	public function handle($request, Closure $next)
	{
		if ($this->auth->check())
		{                    
           return $next($request);  
                   
		}
		return $next($request);
	}

}

Replace all of the following code in the location Http/Middleware/VerifyCsrfToken.php

<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier {

	/**
	 * Handle an incoming request.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 * @return mixed
	 */
	public function handle($request, Closure $next)
	{
      return parent::handle($request, $next);

	}

}

Step-5:

Replace the following array in the file in Http/kernel.php

protected $routeMiddleware = [
		'auth' => 'App\Http\Middleware\Authenticate',
		'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
		'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
        'crsf'  => 'App\Http\Middleware\VerifyCsrfToken',
        'roles'	=> 'App\Http\Middleware\CheckRole',          
	];

Step-6:

Now browse the url http://localhost/auth/login and login

bONEandALL
Visitor

Total : 26654

Today :3

Today Visit Country :

  • France
  • United States