Manually setting url.intended and wrong browser history - laravel

Based on a eloquent created event I set url.intended in the session to a special page.
$this->request->session()->put('url.intended', '/my-special-page');
So when a user creates a row on a specific table (via a form), and is not logged in, it redirects them to login (after middleware) and upon successful login, redirects them to /my-special-page.
All of this is working, but when I create the row, login, get redirected to /my-special-page and hit back, I'm presented with the page users would see if they login normally.
Why is this happening and how can, if the user hits back, got back to the page they were previously on?
What is happening:
form submit -> login -> special-page -> user hits back -> normal page for logged in users
What should be happening:
form submit -> login -> special-page -> user hits back -> form page

You can achieve what you want by editing RedirectIfAuthenticated middleware:
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
return $next($request);
}
Just edit the redirect line so it becomes return redirect('/my-special-page');

Related

Return to calling page instead of dashboard after Login (Laravel 8)

In my Laravel 8 Application link to login route is provided on different locations, i.e., user can login from multiple pages. By default, after login user is redirected to the dashboard. I am looing for a way to return the user to same page from where he clicked on the login button.
I am using Laravel with Jetstream and Livewire. The documentation says that I can do this by changing "public const HOME = '/ dashboard';" to the desired destination, but in my case the destination can be more than a single url.
I tried 'redirect()->back()' in place of '/ dashboard' but it does not work. Please help what change is required.
Save previous url when you redirect user to login page and after authentication of user redirect him on same page with the session you saved. Try this:
public function showLoginForm()
{
session(['link' => url()->previous()]);
return view('auth.login');
}
protected function authenticated(Request $request, $user)
{
return redirect(session('link'));
}

Laravel stuck on email/verify

I just applied the laravel email-verification and wanted to make sure my users are verified, before entering page behind the login.
I added the follwing code:
class User extends Authenticatable implements MustVerifyEmail
...
Auth::routes(['verify' => true]);
...
Route::get('management', function () {
// Only verified users may enter...
})->middleware('verified');
If a user registers he gets a note and an email to verify his mail. He clicks the button in the mail, gets verified and everything works perfectly well.
But I discovered another case:
If the user registers and won't verify his mail, he will always get redirected to email/verify.
For example if accidentally having entered a wrong email, he can't even visit the register page, because even on mypage.com/register he gets redirected to mypage.com/email/verify!
Is this done on purpose by Laravel? Did I miss something? Do I have to / is it possible to exclude the login/register pages from verification?
Thank you in advance
I have this issue before, I have this way to resolve that, if you want to customize it you can consider this way.
In LoginController.php you can add this a little bit code, I overwriting the default login method:
public function login(Request $request)
{
$this->validateLogin($request);
$user = User::where($this->username(), $request->{$this->username()})->first();
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if (method_exists($this, 'hasTooManyLoginAttempts') &&
$this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($user->hasVerifiedEmail()) {
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
})
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
You can overwrite and add a new parameter to the sendFailedLoginResponse too to let the method know when to redirect to email/verify page or just add else in $user->hasVerifiedEmail() if block to redirect him to email/verify page
EDIT:
You can delete $this->middleware('guest') in LoginController and RegisterController to make logged in user can go to register and login page, but it will be weird if someone who already logged in can login or register again.
I had the same problem and I solved it very user friendly... (I think!)
First: Inside View/Auth/verify.blade.php put a link to the new route that will clear the cookie:
My mail was wrong, I want to try another one
Second: On your routes/web.php file add a route that will clear the session cookie:
// Clear session exception
Route::get('/clear-session', function(){
Cookie::queue(Cookie::forget(strtolower(config('app.name')) . '_session'));
return redirect('/');
});
This will clear the cookie if the user press the button, and redirect to home page.
If this doesn't work, just make sure that the cookie name you are trying to forget is correct. (Use your chrome console to inspect: Application -> cookies)
For example:
Cookie::queue(Cookie::forget('myapp_session'));

How to validate routes if a user is admin or not?

//This is the middle ware
public function handle($request, Closure $next)
{
if(auth()->user()->isAdmin()) //isAdmin is a function in the User model which checks if the user is admin or not
{
return redirect('/admin');
} else {
return redirect('/home');
}
return $next($request);
}
//I already registered this middleware in kernel as well as verifyUser
Route::middleware(['auth', 'verifyUser'])->group(function() {
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/admin', 'AdminController#index')->name('admin');
Route::get('/users/profile', 'UserController#view')->name('users.view-profile');
Route::get('/users/edit_profile', 'UserController#edit')->name('users.edit-profile');
});
Th main problem here is it shows this error in the browser
The page isn’t redirecting properly
Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
This problem can sometimes be caused by disabling or refusing to accept cookies.
You're telling Laravel to redirect admins to /admin, and non-admins to /home.
However, you've made /admin and /home subject to that middleware, too, so when the user gets to /home it redirect them to /home again (and again, and again, and again, forever).
You likely need two changes:
A new middleware, applied only to admin routes, that only redirects non-admins away from those routes.
Put your home/admin logic as a one-off post-login step instead of on every pageview. See the path customization section of the Authentication docs.

How to redirect a user to login page(if not logged in already) to authenticate and back to the same controller to perform the remaining operation?

I have the Create-Group functionality where the user clicks a button and fills the form and submits. While submitting, if the user is not logged in then it should redirect to the login page, get him authenticated, and redirect back to the Create-Group controller where the submit Group action is done after authentication. How do I redirect a user to the login controller and back to the same Create-Group Controller to submit the form? I'm using spring-boot-(Java Configs), spring-security-customSuccessHandler, JSP.
I have tried googling many blogs and other stack overflows but didn't get a clear idea.
#PostMapping("/group/create")
public String singleFileUpload(#RequestParam("title") String title, #RequestParam("groupDescription") String groupDescription, Model theModel){
blah..blah..blah..
if(currentPrincipalName.equals("anonymousUser")) {
System.err.println("User admin name is null so redirecting him to the login page");
theModel.addAttribute("returnToGroup","returnToGroup");
return "redirect:/showMyLoginPage";
}else {
System.err.println("The user logged in is "+currentPrincipalName);
}
theGroup.setAdminName(currentPrincipalName);
etc...etc...

In laravel when user is logged in and hit /login it redirects to root homepage

In my laravel site, users can log in.
When a user is logged in, and hit /login, it redirects to root homepage at /.
I want this redirect to hit /dashboard instead of /.
The routes were created using make:auth.
This is a problem when im using WebView in my android app. The standard page in the android WebApp is /login - but if the user is logged in and then exits the app and open it again, they hit / instead of fx /dashboard.
How do I redirect users from /login to /dashboard, if they hit /login while already logged in?
How do I redirect users from /login to /dashboard, if they hit /login while already logged in?
At app/http/Middleware/RedirectIfAuthenticated.php :
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect('/dashboard'); // redirect path wherever to redirect users when they already login
}
return $next($request);
}
In your LoginController, set :
protected $redirectTo = '/dashboard';

Resources