Reference site : https://medium.com/hello-laravel/multiple-authentication-system-laravel-5-4-ac94c759638a
CIAA Project reference
Admin login controller:
CIAA Project reference
Admin login controller:
public function __construct(){ $this->middleware('guest:admin')->except('logout');}
Logout of normal user
function logout(Request $request){ {// dd('test'); $this->guard('admin')->logout(); $activeGuards = 0; foreach (config('auth.guards') as $guard => $guardConfig) { if ($guardConfig['driver'] === 'session') { $guardName = Auth::guard($guard)->getName(); if ($request->session()->has($guardName) && $request->session()->get($guardName) === Auth::guard($guard)->user()->getAuthIdentifier()) { $activeGuards++; } } } if ($activeGuards === 0) { $request->session()->flush(); $request->session()->regenerate(); } $count=Issue::count(); $progress=Issue::where('status','=',1)->count(); $resolved=Issue::where('status','=',2)->count(); $closed=Issue::where('status','=',3)->count(); // $blogs=Blog::where('status','=',1)->orderBy('rank')->get(); return view('front.index',compact('count','progress','resolved','closed')); // return redirect('/admin/login'); } }
Default logout fn :go through login controller bta redirect
function logout(Request $request){ {// dd('test'); $this->guard('web')->logout(); $activeGuards = 0; foreach (config('auth.guards') as $guard => $guardConfig) { if ($guardConfig['driver'] === 'session') { $guardName = Auth::guard($guard)->getName(); if ($request->session()->has($guardName) && $request->session()->get($guardName) === Auth::guard($guard)->user()->getAuthIdentifier()) { $activeGuards++; } } } if ($activeGuards === 0) { $request->session()->flush(); $request->session()->regenerate(); } return redirect('/login'); } }
Admin Model : it extends Authenicable
<?php namespace App; use Illuminate\Notifications\Notifiable;use Illuminate\Foundation\Auth\User as Authenticatable; class Admin extends Authenticatable{ use Notifiable; protected $guard = 'admin'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', 'phone','address', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ];}create admin model vie and controller -mcr garera
$table->string('name');$table->string('email')->unique();$table->string('phone')->unique()->nullable();$table->string('address')->nullable();$table->string('password');$table->rememberToken();
//in migration
Admin model
<?php namespace App; use Illuminate\Notifications\Notifiable;use Illuminate\Foundation\Auth\User as Authenticatable; class Admin extends Authenticatable{ use Notifiable; protected $guard = 'admin'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', 'phone','address', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ];}
Handler.php
<?phpnamespace App\Exceptions;use Exception;use Illuminate\Auth\AuthenticationException;use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;class Handler extends ExceptionHandler{ /** * A list of the exception types that should not be reported. * * @var array */ protected $dontReport = [ \Illuminate\Auth\AuthenticationException::class, \Illuminate\Auth\Access\AuthorizationException::class, \Symfony\Component\HttpKernel\Exception\HttpException::class, \Illuminate\Database\Eloquent\ModelNotFoundException::class, \Illuminate\Session\TokenMismatchException::class, \Illuminate\Validation\ValidationException::class, ]; /** * Report or log an exception. * * This is a great spot to send exceptions to Sentry, Bugsnag, etc. * * @param \Exception $exception * @return void */ public function report(Exception $exception) { parent::report($exception); } /** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $exception * @return \Illuminate\Http\Response */ /* public function render($request, Exception $exception) { return parent::render($request, $exception); }*/ public function render($request, Exception $exception) { if ($this->isHttpException($exception)) { $message = $exception->getMessage(); // dd($message); switch ($exception->getStatusCode()) { // not authorized case '403': return \Response::view('errors.403',array(compact('message')),403); break; case '202': return \Response::view('errors.202',array(compact('message')),202); break; // not found case '404': return \Response::view('errors.404',array(compact('message')),404); break; // internal error case '500': return \Response::view('backend.errors.500',array(compact('message')),500); break; default: return $this->renderHttpException($exception); break; } } else { return parent::render($request, $exception); } return parent::render($request, $exception); } /** * Convert an authentication exception into an unauthenticated response. * * @param \Illuminate\Http\Request $request * @param \Illuminate\Auth\AuthenticationException $exception * @return \Illuminate\Http\Response */ protected function unauthenticated($request, AuthenticationException $exception) { if ($request->expectsJson()) { return response()->json(['error' => 'Unauthenticated.'], 401); } $guard = array_get($exception->guards(), 0); switch ($guard) { case 'admin': $login = 'admin.login'; break; default: $login = 'login'; break; } return redirect()->guest(route($login)); }}
Http/Middleware/RedirectIfAuthenticated
*inside handle function redirect to admin.dashboard.... replace this route to any where you want to redirect after login
<?phpnamespace App\Http\Middleware;use Closure;use Illuminate\Support\Facades\Auth;class RedirectIfAuthenticated{ /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @param string|null $guard * @return mixed */ public function handle($request, Closure $next, $guard = null) { switch ($guard) { case 'admin': if (Auth::guard($guard)->check()) { return redirect()->route('admin.dashboard'); } break; default: if (Auth::guard($guard)->check()) { return redirect('/home'); } break; } return $next($request); }}
admincontroller
<?php namespace App\Http\Controllers; use App\Admin;use App\Issue;use Illuminate\Http\Request; class AdminController extends Controller{ public function __construct() { $this->middleware('auth:admin'); } /** * Show the application dashboard. * * @return \Illuminate\Http\Response */ public function index() { return view('front.index');// return view('front.login'); }}
Auth/adminlogincontroller
<?phpnamespace App\Http\Controllers\Auth;use App\Admin;use App\Issue;use Illuminate\Http\Request;use App\Http\Controllers\Controller;use Auth;use Illuminate\Support\Facades\DB; class AdminLoginController extends Controller{ public function __construct() { $this->middleware('guest:admin')->except('logout'); } /* public function showLoginForm() { return view('auth.admin-login'); }*/ public function login(Request $request) { // Validate the form data $this->validate($request, [ 'email' => 'required', 'password' => 'required|min:6' ]); $eml=''; $phone=$request->email; if (strpos($phone, '@') !== false) { if (Auth::guard('admin')->attempt(['email' => $phone, 'password' => $request->password], $request->remember)) { // if successful, then redirect to their intended location// return redirect()->intended(route('admin.dashboard')); $count=Issue::count(); $progress=Issue::where('status','=',1)->count(); $resolved=Issue::where('status','=',2)->count(); $closed=Issue::where('status','=',3)->count(); // $blogs=Blog::where('status','=',1)->orderBy('rank')->get(); return view('front.index',compact('count','progress','resolved','closed')); } return redirect()->back()->withInput($request->only('email', 'remember')); } else { $email=DB::table('admins')->where('phone',$phone)->get(); foreach ($email as $email) { $eml=$email->email; } if (Auth::guard('admin')->attempt(['email' => $eml, 'password' => $request->password], $request->remember)) { // if successful, then redirect to their intended location// return redirect()->intended(route('admin.dashboard')); $count=Issue::count(); $progress=Issue::where('status','=',1)->count(); $resolved=Issue::where('status','=',2)->count(); $closed=Issue::where('status','=',3)->count(); // $blogs=Blog::where('status','=',1)->orderBy('rank')->get(); return view('front.index',compact('count','progress','resolved','closed')); } return redirect()->back()->withInput($request->only('email', 'remember')); } // dd($eml); // Attempt to log the user in // if unsuccessful, then redirect back to the login with the form data } function logout(Request $request){ {// dd('test'); $this->guard('admin')->logout(); $activeGuards = 0; foreach (config('auth.guards') as $guard => $guardConfig) { if ($guardConfig['driver'] === 'session') { $guardName = Auth::guard($guard)->getName(); if ($request->session()->has($guardName) && $request->session()->get($guardName) === Auth::guard($guard)->user()->getAuthIdentifier()) { $activeGuards++; } } } if ($activeGuards === 0) { $request->session()->flush(); $request->session()->regenerate(); } $count=Issue::count(); $progress=Issue::where('status','=',1)->count(); $resolved=Issue::where('status','=',2)->count(); $closed=Issue::where('status','=',3)->count(); // $blogs=Blog::where('status','=',1)->orderBy('rank')->get(); return view('front.index',compact('count','progress','resolved','closed')); // return redirect('/admin/login'); } } function guard(){ return Auth::guard('admin'); }}
adminregistercontroller inside auth
<?php namespace App\Http\Controllers\auth; use App\Admin;use Illuminate\Http\Request;use App\Http\Controllers\Controller;use Illuminate\Support\Facades\Auth;use Illuminate\Support\Facades\Hash;use Illuminate\Support\Facades\Session;use Illuminate\Support\Facades\Validator;use Illuminate\Foundation\Auth\RegistersUsers; class AdminRegisterController extends Controller{ use RegistersUsers; // protected $redirectTo = '/admin/'; /** protected $redirectTo = '/home'; * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest'); } public function showRegisterForm() { return view('front.register'); } /** * Get a validator for an incoming registration request. * * @param array $data * @returnphp \Illuminate\Contracts\Validation\Validator */ protected function validator(Request $request) { return Validator::make($request, [ 'name' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:admins', 'password' => 'required|string|min:6|confirmed',// 'g-recaptcha-response' => 'required|captcha', ]); } /** * Create a new user instance after a valid registration. * * @param array $data * @return \App\User */ protected function register(Request $request) { $pw=$request->input('password'); $request->validate( [ 'name' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:admins', 'phone' => 'required|max:10|unique:admins', 'password' => 'required|string|min:6|confirmed', ] ); $status=Admin::create([ 'name'=>$request->input('name'), 'email'=>$request->input('email'), 'phone'=>$request->input('phone'), 'address'=>$request->input('address'), 'password'=> bcrypt($pw), ]); if($status){ Session::flash('success','Registration success ... Now Login to continue Please!!!'); }else{ Session::flash('error','issue cannot be added.'); } return view('front.login'); } protected function showpwreset() { return view('front.pwreset'); } protected function pwreset(Request $request) { $request->validate( [ 'email' => 'required|string|email|max:255', 'phone' => 'required|max:10|min:10', ] ); $email=$request->input('email'); $phone=$request->input('phone'); $check=Admin::where('email',$email)->where('phone',$phone)->get(); foreach ($check as $c) { $id=$c->id; } if (empty($id)) { return Redirect::back()->withErrors(['Sorry Email Or Phone Number is not in Database']); } else{ $admin=Admin::find($id); return view('front.editpassword',compact('admin'));// dd($id); } } public function updatepassword(Request $request, $id) { $request->validate( [ 'password' => 'required|string|min:6|confirmed', ] ); $pw=$request->input('password'); $admin = Admin::find($id); $admin->password= bcrypt($pw); $status=$admin->update(); if($status){ Session::flash('success','Updated Successfully!! Now Try Login Using New Password'); }else{ Session::flash('error','Sorry couldnot be updated '); } return view('front.login'); } }
Config/auth.php
<?phpreturn [ /* |-------------------------------------------------------------------------- | Authentication Defaults |-------------------------------------------------------------------------- | | This option controls the default authentication "guard" and password | reset options for your application. You may change these defaults | as required, but they're a perfect start for most applications. | */ 'defaults' => [ 'guard' => 'web', 'passwords' => 'users', ], /* |-------------------------------------------------------------------------- | Authentication Guards |-------------------------------------------------------------------------- | | Next, you may define every authentication guard for your application. | Of course, a great default configuration has been defined for you | here which uses session storage and the Eloquent user provider. | | All authentication drivers have a user provider. This defines how the | users are actually retrieved out of your database or other storage | mechanisms used by this application to persist your user's data. | | Supported: "session", "token" | */ 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'token', 'provider' => 'users', ], 'admin' => [ 'driver' => 'session', 'provider' => 'admins', ], 'admin-api' => [ 'driver' => 'token', 'provider' => 'admins', ], ], /* |-------------------------------------------------------------------------- | User Providers |-------------------------------------------------------------------------- | | All authentication drivers have a user provider. This defines how the | users are actually retrieved out of your database or other storage | mechanisms used by this application to persist your user's data. | | If you have multiple user tables or models you may configure multiple | sources which represent each model / table. These sources may then | be assigned to any extra authentication guards you have defined. | | Supported: "database", "eloquent" | */ 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\User::class, ], 'admins' => [ 'driver' => 'eloquent', 'model' => App\Admin::class, ], // 'users' => [ // 'driver' => 'database', // 'table' => 'users', // ], ], /* |-------------------------------------------------------------------------- | Resetting Passwords |-------------------------------------------------------------------------- | | You may specify multiple password reset configurations if you have more | than one user table or model in the application and you want to have | separate password reset settings based on the specific user types. | | The expire time is the number of minutes that the reset token should be | considered valid. This security feature keeps tokens short-lived so | they have less time to be guessed. You may change this as needed. | */ 'passwords' => [ 'users' => [ 'provider' => 'users', 'table' => 'password_resets', 'expire' => 90, ], 'admins' => [ 'provider' => 'admins', 'table' => 'password_resets', 'expire' => 90, ], ],];
login.blade.php
<html><body> <section class="login-innerpage"> <div class="container"> <div class="row"> @if ($errors->any()) <hr/> <ul class="alert alert-danger"> @foreach($errors->all() as $key => $error) <li>{{ $error }}</li> @endforeach </ul> @endif @if(Session::has('success')) <div class="alert alert-success"> {{ Session::get('success') }} </div> @endif @if(Session::has('error')) <div class="alert alert-danger"> {{ Session::get('error') }} </div> @endif <div class="col-md-4"></div> <div class="col-sm-4"> <section class="login-form"> @if(isset(Auth::guard('admin')->user()->name)) <h3>Hi {{ Auth::guard('admin')->user()->name }} .. You are Already Logged In</h3> <a data-toggle="tooltip" data-placement="top" title="Logout" href="{{ route('admin.logout.submit') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> <span class="glyphicon glyphicon-off" aria-hidden="true"></span> </a> <form id="logout-form" action="{{ route('admin.logout.submit') }}" method="POST" style="display: none;"> {{--{{ csrf_field() }}--}} </form> @else <form method="post" action="{{ route('admin.login.submit') }}" role="login"> <h3 class="text-center">User Login</h3> <input type="text" name="email" id="email" placeholder="Email" value="{{old('email')}}" class="form-control input-lg" /> <input type="password" name="password" class="form-control input-lg" id="password" placeholder="Password" /> <div class="checkbox"> <label> <input type="checkbox" name="remember" {{ old('remember') ? 'checked' : '' }}> Remember Me </label> </div> <button type="submit" name="go" class="btn btn-lg btn-primary btn-block btn-def">Sign in</button> <div> <a href="{{route('admin.register')}}">Create account</a> or <a class="btn btn-link" href="{{ route('front.pwreset') }}"> Forgot Your Password? </a> </div> </form> @endif </section> </div> <div class="col-md-4"></div> </div> </div> </section></body></html>
Register.blade.php<html>
<body> <section class="login-innerpage"> <div class="container"> <div class="row"> @if ($errors->any()) <hr/> <ul class="alert alert-danger"> @foreach($errors->all() as $key => $error) <li>{{ $error }}</li> @endforeach </ul> @endif <div class="col-md-4"></div> <div class="col-sm-4"> <section class="login-form"> <form method="post" action="{{ route('admin.register.submit') }}" role="login"> <h3 class="text-center">Create an account</h3> <input type="text" name="name" id="name" placeholder="Full Name" value="{{old('name')}}" class="form-control input-lg" /> <input type="text" name="phone" id="phone" placeholder="Mobile Number" class="form-control input-lg" value="{{old('phone')}}" /> <input type="text" name="email" id="email" placeholder="Email Address" class="form-control input-lg" value="{{old('email')}}" /> <input type="text" name="address" id="address" placeholder="Address" class="form-control input-lg" value="{{old('address')}}" /> <input type="password" name="password" id="password" value="" class="form-control input-lg" placeholder="Password" /> <input id="password-confirm" type="password" class="form-control" placeholder="confirm Password" name="password_confirmation" required> <button type="submit" name="submit" class="btn btn-lg btn-primary btn-block btn-def">Register</button> <div> <a href="{{route('front.login')}}">Login</a> </div> </form> </section> </div> <div class="col-md-4"></div> </div> </div> </section> </body></html>
web.php route file
//multi login//Auth::routes();Route::prefix('admin')->group(function() { Route::get('/login', 'Auth\AdminLoginController@showLoginForm')->name('admin.login'); Route::get('/register', 'Auth\AdminRegisterController@showRegisterForm')->name('admin.register');// Route::post('/login', 'Auth\AdminLoginController@login')->name('admin.login.submit'); Route::post('/logout', 'Auth\AdminLoginController@logout')->name('admin.logout.submit'); Route::post('/register', 'Auth\AdminRegisterController@register')->name('admin.register.submit'); Route::post('/login', 'Auth\AdminLoginController@login')->name('admin.login.submit'); Route::get('/', 'AdminController@index');});//multi login
PASSWORD RESET
web.php
//password resetRoute::get('/pwreset', 'Auth\AdminRegisterController@showpwreset')->name('front.pwreset');Route::post('/pwreset', 'Auth\AdminRegisterController@pwreset')->name('front.pwreset.submit');//Route::get('/pwedit', 'FrontController@editpassword')->name('front.pwreset.edit');//Route::get('front/editpassword/{id}','FrontController@editpassword')->name('front.editpassword');Route::put('/updatepassword/{admin}','Auth\AdminRegisterController@updatepassword')->name('front.updatepassword'); //password reset
Admin login controller ----- mathi nai xa sabai code
pwreset.blade.php
<html><body> <section class="login-innerpage"> <div class="container"> <div class="row"> @if ($errors->any()) <hr/> <ul class="alert alert-danger"> @foreach($errors->all() as $key => $error) <li>{{ $error }}</li> @endforeach </ul> @endif @if(Session::has('success')) <div class="alert alert-success"> {{ Session::get('success') }} </div> @endif @if(Session::has('error')) <div class="alert alert-danger"> {{ Session::get('error') }} </div> @endif <div class="col-md-4"></div> <div class="col-sm-4"> <section class="login-form"> @if(isset(Auth::guard('admin')->user()->name)) <h3>Hi {{ Auth::guard('admin')->user()->name }} .. You are Already Logged In</h3> <a data-toggle="tooltip" data-placement="top" title="Logout" href="{{ route('admin.logout.submit') }}" onclick="event.preventDefault(); document.getElementById('logout-form').submit();"> <span class="glyphicon glyphicon-off" aria-hidden="true"></span> </a> <form id="logout-form" action="{{ route('admin.logout.submit') }}" method="POST" style="display: none;"> {{--{{ csrf_field() }}--}} </form> @else <form method="post" action="{{ route('front.pwreset.submit') }}" role="login"> {{ csrf_field() }} <h3 class="text-center">Password Reset Form</h3> <input type="text" name="email" id="email" placeholder="Email" value="{{old('email')}}" class="form-control input-lg" /> <input type="text" name="phone" id="phone" placeholder="phone" value="{{old('phone')}}" class="form-control input-lg" /> <button type="submit" name="go" class="btn btn-lg btn-primary btn-block btn-def">Submit</button> </form> @endif </section> </div> <div class="col-md-4"></div> </div> </div> </section> </body></html>
editpassword.blade.php
<html><body> <section class="login-innerpage"> <div class="container"> <div class="row"> @if ($errors->any()) <hr/> <ul class="alert alert-danger"> @foreach($errors->all() as $key => $error) <li>{{ $error }}</li> @endforeach </ul> @endif <div class="col-md-4"></div> <div class="col-sm-4"> <section class="login-form"> <form action="{{route('front.updatepassword',$admin->id)}}" method="post" enctype="multipart/form-data" id="valid_form"> <input type="hidden" name="_method" value="put"> {{csrf_field()}} <h3 class="text-center">Update an Account</h3> <input type="text" name="name" id="name" placeholder="Full Name" value="{{$admin->name}}" readonly class="form-control input-lg" /> <input type="text" name="phone" id="phone" placeholder="Mobile Number" class="form-control input-lg" readonly value="{{$admin->phone}}" /> <input type="text" name="email" id="email" placeholder="Email Address" class="form-control input-lg" readonly value="{{$admin->email}}" /> <input type="text" name="address" id="address" placeholder="Address" class="form-control input-lg" readonly value="{{$admin->address}}" /> <input type="password" name="password" id="password" value="" class="form-control input-lg" placeholder="Password" /> <input id="password-confirm" type="password" class="form-control" placeholder="confirm Password" name="password_confirmation" required> <button type="submit" name="submit" class="btn btn-lg btn-primary btn-block btn-def">Update</button> <div> <a href="{{route('admin.login')}}">Login</a> </div> </form> </section> </div> <div class="col-md-4"></div> </div> </div> </section></body></html>
Comments
Post a Comment