After I logout of my laravel application, in the browser I press the button to backward (go back) and then I see the dashboard.
I want to eliminate this "session" that laravel mantein if I go back.
can anyone help me?
EDIT: I have two login files, one is inside the Controllers/Auth and another is inside the Controller/. I'm sure this is not a good practice, but it's keeping my system up and running. how to solve this?
Controllers/Auth/LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Session;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new controller instance.
*
* #return void
*/
private $user;
}
my Login Controllers/LoginController.php ->
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Session;
class LoginController extends Controller
{
private $user;
public function logout(){
Auth::logout();
\Session::flash('success',"logout");
return redirect()->route('login');
}
}
my DashboardController ->
use App\Authorization;
use App\BackLog;
use App\Key;
use App\isKeyInUse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
class DashboardController extends Controller
{
public function index() {
return view('dashboard');
}
}
my web.php ->
<?php
Route::get('/', 'LoginController#login')->name('login');
Route::get('auth/logout', 'Auth\LoginController#logout')->name('logout');
Route::get('/dashboard', 'DashboardController#index')->name('dashboard')->middleware('auth');
Route::post('/dashboard/getKey', 'DashboardController#getKey')->name('dashboard.key')->middleware('auth');
This is happening because caching. to prevent that we can create a middleware that intercepts every request and set the cache to expire in0 time and thus it will force the page to reload when the user press the back button here's the steps to create the middleware :
first
create a middleware i will call it MyAuth:
php artisan make:middleware MyAuth
second
register the middleware in app/Http/kernel.php
protected $routeMiddleware = [
...,
'my_auth' => \App\Http\Middleware\MyAuth::class,
];
third
in the newly created middleware app/Http/Middleware/MyAuth.php
public function handle($request, Closure $next, $guard = null)
{
$response = $next($request);
return $response
->withHeaders([
'Cache-Control' => 'no-store, no-cache, must-revalidate',
'Pragma'=> 'no-cache',
'Expires' => '0'
]);
}
}
Then
you can add your middleware like so:
Route::group(['middleware' => 'my_auth'], function() {
// All your routes you want to be secure
});
This code has been derived from this video
You are missing Request in logout function
public function logout(Request $request){
Auth::logout();
\Session::flash('success',"logout");
return redirect()->route('login');
}
And write in your dashboard controller
public function __construct()
{
$this->middleware('auth');
}
Insert these lines to your Dashboard controller and then check:
public function __contruct()
{
$this->middleware('auth');
}
This will check user is logged in or not? If user is loggedout, then it send to specific login page as you defined in auth middleware.
Pressing the Back button of your browser will load the previously loaded document. It is just visible but will not work for sure. For this you just have to override back press event from javascript.
See link How to Detect Browser Back Button event - Cross Browser
In Laravel 7.x, you can logout from the controller by using the following command:
Auth::logout()
Related
I have a column in my User table named role with 2 possible values--"Admin" and
"Driver".
All my crud routes are protected with Auth middleware, but I'd like to further secure a few of those routes.
For example I'd like to have the "Create" routes only accessible by Users with the role column equalling "Admin". I wasn't sure how to go about this, so I can't provide examples of what I've tried.
web.php
...
Route::middleware(['auth', 'verified'])->group(function () {
Route::get('/users', App\Http\Livewire\User\Index::class)->name('users.index');
Route::get('/user/{user}/edit', App\Http\Livewire\User\Edit::class)->name('user.edit');
/* This is the route I want to protect to just "Admin" role */
Route::get('/user/create', App\Http\Livewire\User\Create::class)->name('user.create');
...
You can create a middleware with the artisan command
php artisan make:middleware IsAdminMiddleware
Then add something like this in the handle function of your middleware.
public function handle(Request $request, Closure $next)
{
// This validation assumes you can access role from User Model
if ($request->user()->role != "Admin") {
return response()->json(['error' => 'you are not an admin!'], 403);
}
return $next($request);
}
Finally add the middleware on your Routes
Route::get('/user/create', App\Http\Livewire\User\Create::class)
->middleware(IsAdminMiddleware::class) // <<----
->name('user.create');
For more info refer to middleware the docs at laravel.
You can use authorization in laravel for your case
in laravel you can use gate or policy for further feature
https://laravel.com/docs/9.x/authorization
Gate
define gate in App\Providers\AuthServiceProvider on method boot
use Illuminate\Support\Facades\Gate;
use Illuminate\Auth\Access\Response;
use App\Models\User;
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
Gate::define('create', function (User $user) {
return ($user->role == 'Admin')
? Response::allow()
: Response::deny('You must be an administrator.');
});
}
On your controller
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
class CreateController extends Controller
{
public function create(Request $request)
{
$user = Auth::user();
if (Gate::allows('create', $user)) {
//create
}
}
}
I have a middleware that redirects to the Login page and everything works fine:
*If I try to enter a page restricted by this middleware I am sent to login page and then I'm sent to that page.
*If I type /login directly, I will be redirected to /about.
I'm using a custom guard called "client".
Here is my code:
<?php
namespace App\Http\Middleware;
use Illuminate\Support\Facades\Auth;
use Closure;
class ClientLoggedIn
{
public function handle($request, Closure $next)
{
if (!Auth::guard('client')->check()) {
session(['url.intended' => url()->full()]);
return redirect()->route('login');
}
return $next($request);
}
}
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected function redirectTo()
{
$intendedURL = request()->session()->get('url.intended');
if (isset($intendedURL)) {
return $intendedURL;
}
return '/about';
}
public function __construct()
{
$this->middleware('guest:client')->except('logout');
}
protected function guard()
{
return Auth::guard('client');
}
public function showLoginForm()
{
return view('auth.login');
}
}
Whenever I click the back button after the authentication, however, a redirect to the site home (localhost:8000/) occurs (the back button refers to /login)
My question is: is there some configuration or callback that sets it to the home? I thought it would be the redirectTo, but it doesn't seem to be it since it is already set to /about. For what I know, when I click back doesn't occur a request to the server, so, how it works and how to change it?
Thanks in advance.
When I try to destroy a record with resource controller, laravel redirects to login page
although I applied auth middleware in the controller.
Laravel Version is 6.x.
Web.php
<?php
Auth::routes();
Route::resource('sliders', 'Admin\SliderController');
SliderController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Slider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Storage;
use Validator;
class SliderController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
...other methods
public function destroy(Slider $slider)
{
Slider::destroy($slider->id);
Session::flush('status', 'success');
return redirect('sliders');
}
}
}
I couldn't understand why it redirects to login page.
Help please
Thanks
Session flush is to delete all data https://laravel.com/docs/master/session#deleting-data
Use
$request->session()->flash('status', 'success');
I am trying to integrate Socialite in my Laravel project. I am trying to store a session in buyerSignup.blade.php file and then trying to get that session value in Socialite's handleProviderCallback() method. But it is not showing any value don't know why. Although the other method
redirectToProvider() showing the session value.
I need that session value in handleProviderCallback() method to process it and take actions based upon the value of session. Below is a actual of code that I am using.
Storing a session value in buyerSignup.blade.php
#php
\Session::put('buyerSignupFb','true');
#endphp
Trying to get the above stored value in LoginController's handleProviderCallback() method.
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Auth;
use App\sellerData;
use App\buyerData;
use App\sellerDealCat;
use App\subCatData;
use App\Session;
use App\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Socialite;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest')->except('logout');
$this->middleware('guest:seller')->except('logout');
$this->middleware('guest:buyer')->except('logout');
}
public function redirectToProvider()
{
return Socialite::driver('facebook')->redirect();
}
public function handleProviderCallback()
{
//cant get the value of the session defined in buyerSignup.blade.php
// echo doesn't work too
return \Session()->get('buyerSignupFb');
}
}
Any suggestion what I am doing wrong or how to make it work. TIA
U doing all good, but not enought, first u set a redirect provider
public function redirectToProvider()
{
return Socialite::driver('facebook')->stateless()->redirect();
}
it's good, when user will give access to his token, u need to handle callback in handleProviderCallback(), where u need to exchange user auth code to acces token. All of this socialite makes automatically, all what u need its just call it
public function handleProviderCallback()
{
$externalUser = Socialite::driver('facebook')->stateless()->user();
\\check if user exists, if not create
$auth->login($user, true);
if ($user->type = 'seller'){$this->redirectTo = '/forSellers'} else {$this->redirectTo = '/forOtherGroup'}
return redirect($this->redirectPath());
}
I have a small dilema, i'm trying to make a login system that differentiates normal users from admin users using the laravel auth scaffolding.
The problem is it goes in a infinite redirect loop in the middleware.
After I press the login button it constantly redirects to a route and the question is, how can I solve this issue the "laravel way" or any other way for that matter.
Here are my controllers:
1. The basic home controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('home');
}
}
The main admin controller - entry controller:
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class Start extends Controller
{
public function index(){
return view('admin/index');
}
}
Login Controller(the default one from the auth scaffolding- modified by me, I removed the constructor):
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $redirectTo = '/home';
}
The Middleware(redirect if RedirectIfAuthenticated):
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
if(Auth::user()->type == 2){//if user type is 1 then it's an admin.
return redirect()->route('web-admin');
}else{
return redirect()->route('home');
}
}
return $next($request);
}
}
The route file(web routes)
Route::get('/', function () {
return view('index');
});
Auth::routes();
Route::middleware(['auth','guest'])->group(function() {
Route::get('home',['as'=>'home', 'uses'=>'HomeController#index']);
Route::get('web-admin',['as'=>'web-admin', 'uses'=>'Admin\Start#index']);
});
The guest/RedirectIfAuthenticated redirects any request to corresponding home route for authenticated users. The problem is that admin home route is behind this middleware as well, that's why it keeps redirecting to the same page.
You need to remove the guest middleware from the route group - it should only be applied to routes that should be available to unauthenticated users only.
For sure this is an infinite loop because you applied both guest and auth middle ware to your routes, so also authenticated users will be redirected and this is an infinite loop.
Keep the RedirectIfAuthenticated.php as its original code and redirect authenticated users inside your main controller based on their type:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
// if type 1 is admin, why did you redirect type 2 to web-admin?!
if($request->user()->type == 2) { //if user type is 1 then it's an admin.
return redirect()->route('web-admin');
}
return view('home');
}
}
You may do same redirection in your admin controller for normal users to redirect them back in case they try to access admin page.
Additionally modify web.php routes as following:
Route::get('/', function () {
if(auth()->user()->type == 2) { //if user type is 1 then it's an admin.
return redirect()->route('web-admin');
} else {
return redirect()->route('home');
}
})->middleware('auth');
Auth::routes();
Route::middleware('auth')->group(function() {
Route::get('home',['as'=>'home', 'uses'=>'HomeController#index']);
Route::get('web-admin',['as'=>'web-admin', 'uses'=>'Admin\Start#index']);
});