Midedlware class is not working in Laravel 5.3 - php

I have a laravel application in this application i have following function for login user
public function login() {
try {
$inputs = Input::except('_token');
$validator = Validator::make($inputs, User::$login);
if ($validator->fails()) {
return Redirect::to('/')->with('message', 'Please Enter Valid Credentials');
} else {
$respones = \UserHelper::processLogin($inputs);
if ($respones) {
return Redirect::to('/dashboard')->with('success_message', 'Welcome to Tressly Admin Dashboard');
} else {
return Redirect::to('/')->with('message', 'Please Enter Valid Information ');
}
}
} catch (Exception $ex) {
return CommonHelper::AdminExceptions($ex);
}
}
Now as user logout and presses the back button , browser show previous page as it is present in cache. Now on this page as user tries to access any protected route application It shows following error
I want to redirect it to '/'( home route)as logged out user tries to acess any protect routes following error comes
Class App\Illuminate\Auth\Middleware\AdminAuthenticate does not exist
I have made a custom Authentication Middle , handle function of the middleware is
public function handle($request, Closure $next, $guard = null) {
if (Auth::check()) {
return $next($request);
}
return redirect('/');
}
I have also registered it in kernal.php in $routeMiddleware like
'authAdmin' => \Illuminate\Auth\Middleware\AdminAuthenticate::class,
and protected my route like
Route::group(['middleware' => 'authAdmin'], function () {
///routes
});
Any ideas ?

use
'authAdmin' => \App\Http\Middleware\AdminAuthenticate::class,
Instead of
'authAdmin' =>\Illuminate\Auth\Middleware\AdminAuthenticate::class,
I hope it it will work

Is there a reason you made a custom middleware class that does exactly the same thing as the already present 'auth' middleware?
RedirectifAuthenticated.php does this;
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
return $next($request);
}
https://laravel.com/docs/5.3/authentication#protecting-routes

Related

How to redirect from google drive in laravel

I'm using google drive in my project for login with google.
It's working fine for me, but the problem is when user select email, in callback method user have to redirect to '/', but user will redirect to home, this is callback method :
public function callback(Request $request)
{
$googleUser = Socialite::driver('google')->stateless()->user();
$user = User::where('email', $googleUser->email)->first();
if (!$user) {
$user = User::create([
'name' => $googleUser->name,
'email' => $googleUser->email,
'password' => bcrypt(\Str::random(16))
]);
}
auth()->loginUsingId($user->id);
return $this->loggedIn($request, $user) ?: redirect(route('login'));
}
It's ok for next time user login with google, but for the first time redirect to home.
And in loggedIn function for the first time returned false because two_factor_type is off in default :
public function loggedIn(Request $request, $user)
{
if ($user->two_factor_type === 'on') {
auth()->logout();
$request->session()->flash('auth', [
'user_id' => $user->id,
'remember' => $request->has('remember')
]);
if ($user->two_factor_type === 'on') {
$code = ActiveCode::generateCode($user);
//TODO send sms
}
return redirect(route('login.twoFactor'));
}
return false;
}
Even in my LoginController or RegisterController i changed this :
protected $redirectTo = RouteServiceProvider::HOME;
To this :
protected $redirectTo = '/';
So why it will redirect to home ?
in app/Http/Controllers/Auth/LoginController check if the controller protected with middleware, e.g:
public function __construct()
{
$this->middleware('guest')->except('logout');
//meaning if there is user authenticated not guest,
//when he hit function other than logout()
//will be redirected to default landing, in code below
}
in app/Http/Middleware/RedirectIfAuthenticated will check if current auth()->user() is authenticated
change the default code to :
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/home'); // here change the default redirected
}
return $next($request);
}
please check route file maybe in route file your '/' path will return home page view like below...
Route::get('/', function ()
{
return view('welcome');
});
so please try to change this with your need.
or please remove below line from your callback function
return $this->loggedIn($request, $user)

My session and middleware is not working properly

Actually I wanted that my application will go to admin_panel.blade.php only if the user login. I don't want to go there directly. So I implemented middleware and session but it's not working because if I directly goes to 'admin_panel' then it does not restrict me. Without or with using login information it grants me to go to admin_panel.
Kindly solve my issue.
Web.php
Route::get('/admin_log', function () {
return view('Admin.admin_login');
});
Route::group(['middleware'=>'session_auth'],function(){
Route::get('/admin_panel','LoginController#admin_panel');
LoginController
public function admin_panel(){
return view('Admin.admin_panel');
}
public function admin_login(Request $req){
$login=AdminLogin::first();
if ($login->Admin_Name==$req->admin_name && $login->Admin_Password==$req->admin_password ){
$req->session()->put('session_name',$req->admin_name);
return redirect('admin_panel');
}
else{
return redirect('admin_log')->with('error','Invalid UserName or Password!');
}
}
Middleware
public function handle($request, Closure $next)
{
if(is_null($request->session()->get('session_name'))){
return redirect('/admin_log');
}
return $next($request);
}

Laravel 6 Error: Page not redirecting to the defined route

I've been stuck here for a while. I hope I can clearly explain the issue. I'm trying to have separate pages for admin and user. For that, I have created an admin middleware. Now when I login, it redirects me to the same page either its admin or user. I want it to go to admin dashboard when admin logs in and to the user home when user logs in. I hope the issue is clear.
Here is the AdminMiddleware code:
public function handle($request, Closure $next)
{
if(Auth::user()->user_type == 'admin') //If usertype is admin
{
return $next($request);
}
else {
return redirect('home');
}
}
Here are the routes code:
Route::get('/','HomeController#index');
//For Admin
Route::group(['middleware' => ['auth','admin']], function() {
Route::get('/admin','HomeController#home_page');
Route::get('/users-list', 'UserController#users_list');
});
Here is the HomeController code:
public function index()
{
return view('home', compact('currantWorkspace'));
}
I've added the Middleware path to kernel.php file.
I'll be happy to provide any other details if needed. Any solutions/suggestions will be highly appreciated.
Edit
I've tried this, but still issue.
protected function redirectTo(){
if (Auth::user()->user_type != 'admin') {
return 'admin';
//return redirect('/admin');
}
else {
return 'home';
//return redirect('/');
}
}
I think the redirectTo function is not working, or not checking the if/else conditions
Why don't you create an 'if, else' statement in your login function like:
if(Auth::user()->user_type == "Admin"){
return Redirect::route('dashboard');
}else if(Auth::user()->user_type == "Standard User"){
return Redirect::route('home');
}
Change the route as follows.
Route::get('/','HomeController#index')->name('home');
Route::group(['middleware' => ['auth','admin']], function()
{
Route::get('/admin','HomeController#home_page')->name('admin.home');
Route::get('/users-list', 'UserController#users_list');
});
Change the redirect statement in middleware as
public function handle($request, Closure $next)
{
if(Auth::user()->user_type == 'admin') //If usertype is admin
{
return $next($request);
}
else
{
return redirect()->route('home');
OR
return redirect('/');
}
}
There are a few problems, currently, the key thing is that the middleware you defined is not being called when anyone tries to log in.
To make it work I think you just need to add this to your LoginController.php
protected function authenticated()
{
if (Auth::user()->user_type == 'admin') {
return redirect('dashboard');
}
return redirect('home');
}
This method basically tells laravel what you want to do after the user is logged in.

How to check user Permissions using Custom Middleware in Laravel

I'm developing a Laravel ACL System. My base Table's are users,roles,permissions and pivot tables are role_user,role_permission,user_permission.
I want to check User Permissions using my custom middleware HasPermission. I have tried this way but it's not working properly. every user can access the all the permissions which have or have not.
Now, How can I solve the issue. Please see my code sample.
My Controller.
function __construct()
{
$this->middleware('auth');
$this->middleware('HasPermission:Role_Read|Role_Update|Role_Delete');
}
My Middleware.
class HasPermission
{
public function handle($request, Closure $next,$permissions)
{
$permissions_array = explode('|', $permissions);
// $user = $this->auth->user();
foreach($permissions_array as $permission){
if(!$request->user()->hasPermission($permission)){
return $next($request);
}
}
return redirect()->back();
}
}
and, my User Model method.
public function user_permissions()
{
return $this->belongsToMany(Permission::class,'user_permission');
}
public function hasPermission(string $permission)
{
if($this->user_permissions()->where('name', $permission)->first())
{
return true;
}
else
{
return false;
}
}
Best way to do is that you need to introduce an new service provider and in that you can check the authorization and permissions.
I made a test project (last year) for db driven permission and I used service provider.
That's the perfect way to implement.
Basically !$request->user()->hasPermission($permission) is saying if the user associated with the request does not have this permission the middleware passes, however this is not what you want. Here's what you should do:
If you need the user to have one of the stated permissions you need to do:
class HasPermission
{
public function handle($request, Closure $next,$permissions)
{
$permissions_array = explode('|', $permissions);
foreach($permissions_array as $permission){
if ($request->user()->hasPermission($permission)){
return $next($request);
}
}
return redirect()->back();
}
}
If you want the user to have all stated permissions you need to do:
class HasPermission
{
public function handle($request, Closure $next,$permissions)
{
$permissions_array = explode('|', $permissions);
foreach($permissions_array as $permission){
if (!$request->user()->hasPermission($permission)){
return redirect()->back();
}
}
return $next($request);
}
}
As an added note if you want to do this in a more elegant way you can do:
class HasPermission
{
public function handle($request, Closure $next, ...$permissions_array)
{
//Function body from above without the explode part
}
}
And
function __construct()
{
$this->middleware('auth');
$this->middleware('HasPermission:Role_Read,Role_Update,Role_Delete');
}
If you use commas then the framework will split the string into arguments for you .
In my case i just added simple function to get permissions from database and then check it Middleware. Check this code:
// Add new function to get permissions from database
public static function user_permissions($user) {
$permissions=DB::table('permissions')->where('user_id', $user)->first();
return $permissions;
}
// In Middleware check your permissions
if(Auth::guest())
{
return redirect('/');
}
elseif(Functions::user_permissions(Auth::user()->id)->user_managment != 1) {
return redirect('/');
} else {
return $next($request);
}
In web.php/api.php:
Route::middleware('hasPermission')->group(function() { // for all routes
Route::get('/article', [ArticleController::class, 'index'])->name('article.index');
});
in middleWare:
class HasPermission
{
public function handle($request, Closure $next)
{
$routeName = Request::route()->getName();
$permission = $user->permissions()->where('route_name', $routeName)->first();
if ( ! empty($permission)){
return redirect()->back();
}
return $next($request);
}
}

RedirectIfAuthenticated redirect if attempt to open other login form

I have two login forms with two different tables.One is default with /login route and the other has route /myportal. I have extra logincontroller
protected $redirectTo = '/student-home';
public function showLoginForm()
{
return view('my_portal');
}
public function logout(Request $request)
{
$this->guard()->logout();
$request->session()->flush();
$request->session()->regenerate();
return redirect('/my_portal');
}
protected function guard()
{
return Auth::guard('web_student');
}
public function username ()
{
return 'username';
}
This login is working fine. But, I am having problem with RedirectIfAuthenticated
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
else if(Auth::guard('web_student')->check())
{
return redirect('student-home');
}
return $next($request);
}
Now, if the user is already logged in, it is redirected to /student-home only if the route is /login and not /my-portal. i.e only if i click on regular form not this extra form I created. How can I redirect to student-home if user clicked on /my-portal?
You can connect a controller to the my-portal route with :
Route::get('test', 'exampleController#example') ;
Then in the controller function, you can check if the user is already logged in by
public function example() {
if(Auth::check()) {
//This condition will run if the user is logged in !
return redirect('student-home');
}
//Do whatever you want if user is not logged in!
}
Hopefully, this answers your question!
Please change your RedirectIfAuthenticated middleware like this
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
if(guard == 'web_student') {
return redirect('student-home');
}else return redirect('/home');
}
return $next($request);
}
The problem with your code is that the following segment will always true if a user is logged in. You have to check for whether or not a specific guard is set, inside this if statement if you want to redirect them accordingly.
if (Auth::guard($guard)->check()) {
return redirect('/home');
}

Categories