Laravel Redirect from Different Function - php

I'm trying to make an authorization code validator that can be used throughout multiple instances of my website... I want to make it so if the validation fails, it will redirect the user from within the validation function (but this is not working) (similar to how laravels native validation system works for form data). Here are snippets of my code showing the issue.
// From a custom controller (AccountController.php)
public function requestValidate(Request $request, $token)
{
$user = Auth::user();
// This call should redirect to the homepage if the verification fails...
// but instead... it does not redirect and executes return view('verified');
$user->verifyAuthToken($request, $token);
return view('verified');
}
// From User.php
public function verifyAuthToken(Request $request, $token)
{
if (trim($this->auth_code) === '' || trim($token) === '' || $this->auth_code !== $token) {
$request->session()->flash('error', 'Sorry, an error occurred. Please try again.');
// THIS DOES NOT REDIRECT
return redirect()->route('profile');
}
$this->auth_code = "";
$this->save();
}

in your code
return redirect()->route('profile');
this only break the process in your verifyAuthToken function, but not your requestValidate. So basically after the page is redirected to profile, it will redirected again to verified page.
So, maybe you can give a return True in authentication success, then in requestValidate you can do like this:
if($user->verifyAuthToken($request, $token)){
return view('verified');
}

Related

login page in two places. for each other redirect

I make an online store in which I have two login places. /checkout (in cart) and /login.
Can i do it in the existing method to make redirect look like this?
if i login in /checkout ->redirect('/checkout').
(for loggin in /login) it stays like it is /redirect('/')
I would solve that by using the redirectTo() method in the Login Controller and checking which route is sending the request through the path() method. You have to name the routes for it to work though. So in your login Controller you'll have this;
use Illuminate\Support\Facades\Route;
protected function redirectTo(){
if(Route::currentRouteName() == 'login'){
return '/';
}else if(Route::currentRouteName() == 'checkout'){
return '/checkout';
}
}
more info on how to get the route name here
and info on the redirectTo() function here
Try it out, tell me what happens..
only this solution works:
protected function redirectTo() {
if(strpos(URL::previous(), 'checkout')) {
return '/checkout';
} elseif(strpos(URL::previous(), 'login')) {
return '/';
}
}

Symfony redirect in helper service does not work

Introduction
For my personal project i am using
Symfony v4.2 with
XAMPP and
Widows 10 Pro
In order to not to display route parameters in URL i save them in the table.
Then in the controller i check if there is variable (that keeps UUID that corresponds to route parameters) in the session.
If i get no variable in session it should redirect to section start page, where UUID and initial data in the table are setup.
Redirect logic is extracted to helper service. In order to redirect to work there are copied functions redirectToRoute and redirect
I test this functionalit by deleting php session variables in temp folder and PHPSESSID cookie in the browser.
Problem
The prolem is - it does not redirect to secton start page.
I can see that correct if branch is selected, but then it "just stops" and does not execute redirect.
Code
public function checkWhereaboutsExist()
{
$em = $this->entityManager;
$repo_whereabouts = $em->getRepository(Whereabouts::class);
$whereabouts = $this->session->get('whereabouts');
if (($whereabouts === null) || ($whereabouts === ''))
{
$data = 'whereabouts === '.$whereabouts;
dump($data);
/*
HERE IT STOPS
*/
return $this->redirectToRoute('section_start');
}
else
{
$my_whereabouts = $repo_whereabouts->getWhereabouts($whereabouts);
if (!$my_whereabouts)
{
return $this->redirectToRoute('section_start');
}
}
}
Question
Does enyone have some ideas about what is the culprit in this case?
You could try to inject the router into your service class:
use Symfony\Component\Routing\RouterInterface;
class MyService
{
private $router;
public function __construct(RouterInterface $router)
{
$this->router = $router;
}
public function checkWhereaboutsExist()
{
// your code ...
return new RedirectResponse($this->router->generate('section_start'));
}
}
Hummmm, i suppose that your code is in a service and not in your controller ?
You can't redirect from a service but only from controller as controller send the final response.
You have to return a boolean from your service and redirect from your controller :
public function hasToGoToStart()
{
$em = $this->entityManager;
$repo_whereabouts = $em->getRepository(Whereabouts::class);
$whereabouts = $this->session->get('whereabouts');
if (($whereabouts === null) || ($whereabouts === ''))
{
return true;
}
else
{
$my_whereabouts = $repo_whereabouts->getWhereabouts($whereabouts);
if (!$my_whereabouts)
{
return true;
}
}
return false;
}
and in your controller :
if ($myService->hasToGoToStart()) {
// redirect
}

Laravel 5.4 Redirect back to intended url

Im trying to setup the ability to redirect the user to the original intended url.
If a user visits a url and is required to login, it should redirect them to the original url they visited. Ive been doing some reading on Stackoverflow and have come to these solutions, however I cant get it to function as intended (no intended pun :) )
Any ideas on what I am doing wrong?
I am on Laravel 5.4.36
My LoginController.php
if (Auth::attempt($credentials, $remember_me, $user->status == 'Confirmed')) {
if ($control_panel->auth_throttle == "on") {
$this->clearLoginAttempts($request);
}
// Added if statement if user is super admin we'll direct to their
// dashboard
if ($user->superadmin == true) {
return redirect()->intended("/admin");
}
// if user is not superadmin we'll direct them to their
// dashboard
else {
return redirect()->intended("v1");
}
}
My RedirectIfAuthenticated.php
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
return redirect()->intended();
//return redirect('/admin');
}
return $next($request);
}
From my understanding of reading your question, you want to redirect a user BACK to the previous route after authentication?
Laravel has a back helper.
https://laravel.com/docs/5.4/redirects#creating-redirects

Laravel 5.5 Getting 302 redirect error when redirecting user to homepage after login

I have searched a lot of forums and didn't find my mistake here.
I'm not very good in laravel so I'm sure I'm doing a mistake which would be obvious to more advanced developers.
My page works like this.
When new user first comes to the website there will be no need to login and user can view the home page.
Then User registers and will be redirected to an email validation page with a link to the home page but the user isn't logged in automatically.
After user confirms her email, she can go and log in.
After login I want the user to be redirected to the home page if the user is a normal user and to the dashboard if the user is an Admin.
Here is where the problem comes.
After login I get the 302 redirection error.
Below you can see my routes and different controllers I've edited.
Hope I've been able to explain the problem.
Thanks for any help in advance.
My web.php file
Route::get('/', ['middleware'=>'web','uses'=>'HomeController#index']);
Route::get('/home', ['middleware'=>'auth','uses'=>'HomeController#after_login']);
Route::get('/search',['middleware'=>'web','uses'=>'HomeController#search']);
Route::get('/search-all-category',['middleware'=>'web','uses'=>'HomeController#search_all_category']);
Route::get('/register/register-search-cities',['middleware'=>'web','uses'=>'HomeController#register_search_cities']);
Route::post('/company-results',['middleware'=>'web','uses'=>'HomeController#search_companies']);
Route::get('/validate-email',function(){
return view('validate-email');
});
Route::get('/all', ['middleware'=>'guest','uses'=>'HomeController#index']);
Auth::routes();
My LoginController.php controller, where I've overwritten the authenticated function from the AuthenticatesUsers.php :
// protected $redirectTo = '/home';
protected function authenticated( Request $request, $user ) {
if($user->isAdmin == '0'){
return redirect()->intended('/home');
}else if($user->isAdmin == '1'){
return redirect()->intended('dashboard.dashhome');
}else{
return redirect()->intended('/home');
}
}
And here is my HomeController.php which handles the routes:
public function index() {
$country = Country::all();
return view('/home',compact('country'));
}
public function after_login(){
$country = Country::all();
return view('/home',compact('country'));
}
Your code
if($user->isAdmin == '0'){
return redirect()->intended('/home');
}else if($user->isAdmin == '1'){
return redirect()->intended('dashboard.dashhome');
}else{
return redirect()->intended('/home');
}
can be simplified like so (and after your comments, redirect non admins to / because otherwise they'll be stuck in a loop
if ($user->isAdmin){
return redirect()->intended('dashboard.dashhome');
} else {
return redirect()->intended('/'); // return to a route not behind auth middleware to avoid loop
}

yii2 login page redirection looping with cancelled status

After spending so many days, am trying to get some help from experts.
I am stuck with login redirection in my yii2 application only in chrome browser,
This is my controller class,
class InvitationsController extends Controller
{
public function beforeAction($action)
{ $array=array('index','imageupload','template','category','subcategory','slug','chooseanotherdesign');
if(!in_array($action->id, $array))
{
if (\Yii::$app->getUser()->isGuest &&
\Yii::$app->getRequest()->url !== Url::to(\Yii::$app->getUser()->loginUrl)
) {
\Yii::$app->getResponse()->redirect(\Yii::$app->getUser()->loginUrl,FALSE);
}
}
return parent::beforeAction($action);
}
public function actionGenerateevent(){
$redirectUrl="";
if(Yii::$app->request->post()){
unset(Yii::$app->session['copyinvitation']);
unset(Yii::$app->session['eventform']);
Yii::$app->session['eventform']=Yii::$app->request->post();
}
if (!Yii::$app->user->isGuest)
{
$eventid=$this->invitation->savecontinue(Yii::$app->session['eventform']);
$eventdata=$this->invitation->getEventById($eventid);
$refurl=Yii::$app->session['eventform']['refererurl'];
$aa['Events']=$eventdata;
$aa['refererurl']=$refurl;
Yii::$app->session['eventform']=$aa;
$redirectUrl = Yii::$app->urlManager->createAbsoluteUrl(['invitations/event/'.$eventdata['event_token']]);
return $this->redirect($redirectUrl);
}
}
}
My workflow
step1: submitting formdata to controller xx-action
step2: If user login it will proceed further action
Else
am trying to store the values in session then redirecting the page to login
step 3: after successful login am return back to same xx-action
This workflow is working fine in firefox but chrome it's making infinitive loop its not going through the login page.
Please refer am attached the screenshot
Please help me to solve this issue.
I can't infere how are you calling your actionGenerateevent() but you seems to have an error there:
$redirectUrl=""; //empty
...
return $this->redirect($redirectUrl); //still empty
Since you are not setting your $redirectUrl, your redirect is redirecting you to the current (same) url again and again, causing the loop.
This is the function used by redirectUrl() method: Url::to(). Its docs says:
an empty string: the currently requested URL will be returned;

Categories