Laravel white screen when using Redirect Class - php

I am currently getting a white screen of death when I am trying to redirect my users using the Laravel Redirect class after handling data. If I use the native php-function header("location ...") the application responds correctly and sends the user on its merry way, but using Laravel's Redirect class the site crashes with a white screen of death. I have tried both the Redirect::action and Redirect::to functions, but they are both resulting in the same irritating white screen of death. The laravel.log shows nothing...
Does anyone have any ideas?
Here is the code for the data handler controller class:
<?php
class ManagerLayoutDataController extends BaseController
{
public function route($action, $moduleID) {
if(method_exists('ManagerLayoutDataController',$action)) {
$this->$action($moduleID);
}
// Invalid action (method not found)
else {
die('Action routing error');
//return Redirect::to('/');
}
}
public function updateHeaderBg($moduleID) {
$image = Input::file('img');
$user = Auth::user();
$siteID = $user->getSiteID();
$layoutDataMessage = null;
// Validate file upload (NOT FILE CHARACTERISTICS)
if(Input::hasFile('img') && $image->isValid() && isset($siteID) && $siteID !== "") {
$res = ManagerFileUpload::uploadImage($siteID, $image);
if($res->success) {
$fileName = $res->fileName;
$dbViewModule = ViewModuleRepository::getModule($moduleID);
if($dbViewModule->type === DBViewModule::MODULE_TYPE_HEADER) {
$headerModule = new HeaderModule($dbViewModule);
$headerModule->updateBgImage($fileName);
$layoutDataMessage = new LayoutDataMessage(LayoutDataMessage::STATUS_SUCCESS,"");
}
}
else {
$layoutDataMessage = new LayoutDataMessage(LayoutDataMessage::STATUS_FAIL,$res->message);
}
}
else {
$layoutDataMessage = new LayoutDataMessage(LayoutDataMessage::STATUS_FAIL, "Bilden kunde inte laddas upp.");
}
if($layoutDataMessage != null) {
return Redirect::action('ManagerLayoutController#main')->with('message',$layoutDataMessage);
//return Redirect::to('manager/layout/');
//header('location: */manager/layout');
}
else {
return Redirect::action('ManagerLayoutController#main')->with('message',LayoutDataMessage(LayoutDataMessage::STATUS_FAIL, "Bilden kunde inte laddas upp."));
//return Redirect::to('manager/layout/');
//header('location: */manager/layout');
}
}
}
The Main Controller
<?php
class ManagerLayoutController extends BaseController
{
public function main() {
$user = Auth::user();
$siteID = $user->getSiteID();
$moduleComposition = ViewModuleCompositionRepository::getCurrentInWorkModuleComposition($siteID);
$dbViewModules = ViewModuleRepository::getModulesFromComposition($moduleComposition->id);
$viewModules = array();
foreach($dbViewModules as $dbViewModule) {
switch($dbViewModule->getType()) {
case DBViewModule::MODULE_TYPE_HEADER:
$viewModules[] = new HeaderModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_TEXT_SECTION:
$viewModules[] = new TextSectionModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_KEY_METRICS:
$viewModules[] = new KeyMetricsModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_SLIDESHOW:
$viewModules[] = new SlideShowModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_VACANCIES:
$viewModules[] = new VacanciesModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_EMAIL_SUBSCRIPTION:
$viewModules[] = new EmailSubscriptionsModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_CO_WORKERS:
$viewModules[] = new CoworkersModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_NEWS_SECTION:
$viewModules[] = new NewsModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_INSTAGRAM_FEED:
$viewModules[] = new KeyMetricsModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_SOCIAL_MEDIA:
$viewModules[] = new KeyMetricsModule($dbViewModule);
break;
}
}
$data = array(
'siteID' => $siteID,
'viewModules' => $viewModules
);
return View::make('dashboard.pages.manager.layout_main',$data);
}
}
filters.php
<?php
/*
|--------------------------------------------------------------------------
| Application & Route Filters
|--------------------------------------------------------------------------
|
| Below you will find the "before" and "after" events for the application
| which may be used to do any work before or after a request into your
| application. Here you may also register your custom route filters.
|
*/
App::before(function($request)
{
//
});
App::after(function($request, $response)
{
//
});
/*
|--------------------------------------------------------------------------
| Authentication Filters
|--------------------------------------------------------------------------
|
| The following filters are used to verify that the user of the current
| session is logged into this application. The "basic" filter easily
| integrates HTTP Basic authentication for quick, simple checking.
|
*/
Route::filter('auth', function()
{
if (Auth::guest())
{
if (Request::ajax())
{
return Response::make('Unauthorized', 401);
}
else
{
return Redirect::guest('login');
}
}
});
Route::filter('auth.basic', function()
{
return Auth::basic();
});
/*
|--------------------------------------------------------------------------
| Guest Filter
|--------------------------------------------------------------------------
|
| The "guest" filter is the counterpart of the authentication filters as
| it simply checks that the current user is not logged in. A redirect
| response will be issued if they are, which you may freely change.
|
*/
Route::filter('guest', function()
{
if (Auth::check()) return Redirect::to('/');
});
/*
|--------------------------------------------------------------------------
| CSRF Protection Filter
|--------------------------------------------------------------------------
|
| The CSRF filter is responsible for protecting your application against
| cross-site request forgery attacks. If this special token in a user
| session does not match the one given in this request, we'll bail.
|
*/
Route::filter('csrf', function()
{
if (Session::token() != Input::get('_token'))
{
throw new Illuminate\Session\TokenMismatchException;
}
});
/** Admin pages */
Entrust::routeNeedsRole( 'admin*', 'Admin', Redirect::to('/login'));
/** Manage pages */
Entrust::routeNeedsRole( 'manager*', array('Super Manager','Manager'), Redirect::to('/login'), false );
/**
* Check view module ownership before editing data
*/
Route::filter('viewmodule.ownership', function($route) {
$user = Auth::user();
$siteID = $user->getSiteID();
$moduleID = $route->getParameter('moduleID');
// Check that the module with $moduleID belongs to $siteID
if(ViewModuleRepository::moduleBelongToSite($moduleID, $siteID)) {
}
// Unauthorized access
else {
die('Filter error');
//Redirect::to('/');
}
});
routes.php
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::get('/', 'FrontController#main');
Route::get('/manager', 'ManagerHomeController#home');
Route::get('/manager/statistics', 'ManagerStatisticsController#main');
Route::get('/manager/resume-manager', 'ManagerResumeController#main');
Route::get('/manager/resume-manager/pending', 'ManagerResumeController#resumesPending');
Route::get('/manager/resume-manager/approved', 'ManagerResumeController#resumesApproved');
Route::get('/manager/resume-manager/rejected', 'ManagerResumeController#resumesRejected');
Route::get('/manager/layout', 'ManagerLayoutController#main');
Route::get('/manager/layout-old', 'OLDManagerLayoutController#main');
Route::post('/manager/layout/data/{action}/{moduleID}/', array('before'=>'viewmodule.ownership', 'uses' => 'ManagerLayoutDataController#route'));
Route::get('/manager/setup', 'ManagerSetupController#setup');
Route::get('/admin', 'AdminHomeController#home');
Route::get('/login', 'UsersController#login');
Route::get('/test', 'TestController#testMail');
// Confide routes
Route::get('users/create', 'UsersController#create');
Route::post('users', 'UsersController#store');
Route::get('users/login', 'UsersController#login');
Route::post('users/login', 'UsersController#doLogin');
Route::get('users/confirm/{code}', 'UsersController#confirm');
Route::get('users/forgot_password', 'UsersController#forgotPassword');
Route::post('users/forgot_password', 'UsersController#doForgotPassword');
Route::get('users/reset_password/{token}', 'UsersController#resetPassword');
Route::post('users/reset_password', 'UsersController#doResetPassword');
Route::get('users/logout', 'UsersController#logout');

Try to add
ini_set('display_errors', 1);
It should at least tell you what is the actual error.
This is only for development mode, remove it when you go into production

Look if there is a "return" before the Redirect. For example:
// Unauthorized access
else {
die('Filter error');
//Redirect::to('/');
}
Here should be return Redirect::to('/');

Related

laravel login refresh page

My laravel project doesn`t working on the hosting.But everything works perfectly on the local server(
When i switch to mysite.com, the index page "login" and enter the data in login form, tpage just refreshed
At the same time, if I go to mysite.com/register, I will be able to register a new user and write this data to the Users table in my database
I try make routes for test
Route::get('/test', function(){
return User::All();
//this returned all users in DB(ill check connection with my DB)
});
Route::get('/test', function(){
$user = Auth::user();
print_r($user);
//this returned NULL
});
I understand the Auth::login function writes the authenticated user to a session and fills the memoer_token field into the database in the user table. In the table itself token is written, but in the session nothing is written.
But idk how to fix it, if it`s true
UPD:
I tried to step by step replace my project files with an earlier version (which works correctly).
I find were is my problem. In "resource" folder - file login.blade
In last version i changed standard input "email" to "username"
And now I write the field username
Judging from the above, the problem is that he is expecting a return email? Perhaps somewhere in the validation of data? And why then in the local version of the site everything works well?
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
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.
|
*/
protected $redirectTo = '/user';
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
// protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
protected function redirectTo()
{
if (Auth::user()->role === User::IS_ADMIN && Auth::user()->user_verify === 1) {
return '/admin';
}elseif(Auth::user()->role === User::IS_USER && Auth::user()->user_verify === 1 || Auth::user()->role === User::IS_USER && Auth::user()->user_verify === 0){
return '/user';
}
}
}
Route::get('/', function () {
if(Auth::check()){
$user = Auth::user();
if($user->role == 1 && $user->user_verify == 1){
return redirect('/admin');
}
elseif($user->role == 0 && $user->user_verify == 1
|| $user->role == 0 && $user->user_verify == NULL
|| $user->role == 0 && $user->user_verify == 2){
return redirect('/user');
}
}else{
return view('auth.login');
}
});
I found a solution to this problem!
In the LoginController.php file, override the username method by which field to log in. A small email and name input example
public function username(): string
{
$login = request()->input('email');
$field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'name';
request()->merge([$field => $login]);
return $field;
}

Laravel AuthController not working when ajax request pass

I am adapting the out-of-the-box AuthController in Laravel 5.2 to suit my needs. I want to implement login form using AJAX. For that I write the code. But when I click on login button then show 302 error and redirect. I don't know what is my mistake.
My JS
function do_login()
{
frm_name = 'userlogin';
username = $('#userlogin input[id=email]').val();
password = $('#userlogin input[id=password]').val();
_token = $('#userlogin input[id=_token]').val();
if(username == '' || password == '') {
$('#flashMessage').attr('class','alert alert-danger');
$('#flashMessage').html('Please specify Username and Password');
} else {
var param = 'username='+ username+ '&password='+ password +'&_token='+ _token;
$.ajax({
type : "POST",
datatype : "json",
url: "auth/login",
data : param,
success : function(data) {
data = JSON.parse(data);
if (data.status == 0) {
$('#myModallogin').modal('hide');
window.location.href = data.redirect_url;
}
if (data.status == 1) {
$('#flashMessage').attr('class','alert alert-danger');
$('#flashMessage').html(data.message);
} else {
onError(data.Error,'#'+ frm_name);
}
}
});
}
}
$(document).ready(function(){
$('#member_login').click(function() {
do_login();
});
});
My route
Route::auth();
Route::post('auth/login', 'Auth\AuthController#userLogin');
My AuthController
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
//protected $redirectTo = '/';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct() {
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
public function userLogin() {
$post_data = Request::all();
pr($post_data);exit;
}
}
My route is working properly because when I debug the routes for example Route::post('auth/login', function(){ echo 'aaaaaaaaaa'; }); so it display the aaaaaa. But when I called the function then show 302 error and redirect the page. I don't know what is my mistake. Please suggest me.

How to redirect a user to users page and admin to admin page in single login form laravel

I have this in my database
|username|password|type|
------------------------
|foo |12345 |1 |
|asd |adsdsd |0 |
Here 1 means that the user is an admin, 0 a normal user.
How can I redirect the admin to the admin page and the normal user to normal user page??
if($attempt)
{
$id = User::find($attempt);
$user = $id->type;
if($user === 0)
{
return Redirect::action('LoginUsersController#profile');
}
else
{
return Redirect::to('adminpage');
}
}
I created this in my UsersController page I don’t know if this is the proper way to do this, and my code is not working.
Are you using normal Laravel Authentication?
You will get Object Auth::user(), this will return current user Object.
It should look like this.
Controller (SessionsController#store)
public function store() {
$input = Input::all();
$attempt = Auth::attempt([
'username' => $input['username'],
'password' => $input['password']
]);
if($attempt) {
if(Auth::user()->type == 1) {
return Redirect::admin(); // If admin, redirect to admin
} else {
return Redirect::profile(); // Else, redirect to user profile
}
}
}
Route
Route::resource('sessions', 'SessionsController', ['only' => ['create','store','destroy']]);
Route::get('admin', 'AdminController#dashboard')->before('adminAuth');
Route::get('profile/{id}', 'UsersController#showProfile')->before('auth');
First of all you have to add a new field in your users table to check against, for example 'rank'. If rank for a user is '1' so he is an Admin,
else he is a normal user.
Then define all required routes in your routes file like this:
Route::get('login', 'adminController#login');
Route::post('login', 'adminController#checkuser');
Route::group(array('before' => 'auth'), function() {
Route::resource('admin', 'adminController');
Route::resource('normaluser', 'normaluserController');
} );
Then in your controller you have to define all actions:
public function login()
{
return View::make('loginview');
}
public function checkuser()
{
if (Auth::attempt(array('username'=>Input::get('username'), 'password'=>Input::get('password'))))
{
$user_data = Auth::getUser();
if ($user_data->rank == 1) //if true, so this user is an admin
{return Redirect::to('admin');} //go to adminController index action
else //if not, so he is a normal user
{return Redirect::to('normaluser');} // go to normaluserController index action
}
else
{
//return 'wrong user name or password';
Session::flash('mismatch', "Username and Password mismatch");
return Redirect::to('login'); // go again to login form to relogin
}
}
if any thing is not clear, don't hesitate to ask.
in the if statement use:
if($attempt)
{
$id = User::find($attempt);
$user = $id->type;
if($user === 0)
{
return Redirect::action('LoginUsersController#profile');
header('Location: http://www.example.com/userpahe.php');
}
else
{
return Redirect::to('adminpage');
header('Location: http://www.example.com/admin-page.php');
}
}

Laravel Multi Auth before not working

I'm using ollieread multiauth. I got the problem when at route i try to use
Route::group(['before' => 'auth'], function()
{
Route::get('/onlinetest', array('as'=>'onlinetest', 'uses'=>'HomeController#onlinetest'));
Route::get('/quiz', array( 'as'=>'quiz', 'uses'=>'HomeController#quiz'));
Route::get('/number', array( 'as'=>'number', 'uses'=>'HomeController#number'));
Route::get('/word', array( 'as'=>'word', 'uses'=>'HomeController#word'));
});
Here is my usercontroller:
public function handlelogin()
{
$today = date("Y-m-d H:i:s");
$userdata = array(
'email' => Input::get('username'),
'password' => Input::get('password')
);
if (Auth::check())
{
return Redirect::to('/');
}
if(Auth::user()->attempt($userdata, true))
{
$user = User::find(Auth::user()->get()->id);
// check if user has use his account for test
if ($user->status == '0')
{
Auth::logout();
Session::flush();
return Redirect::to('/login')->with('message', FlashMessage::DisplayAlert('Your Account has been used for test', 'warning'));
}
$datebirth = Date($user->BirthDate);
$dob = Date("Y") - $datebirth;
Session::put('current_user', Input::get('username'));
Session::put('full_name', $user->FullName);
Session::put('gender', $user->Sex);
Session::put('dob', $dob);
Session::put('user_id', $user->id);
// set the user last login
$user->last_login = $today;
$user->save();
return Redirect::to('/onlinetest')->with('message', 'Login Successfully.');
}
else
{
return Redirect::to('/login')->with('message', FlashMessage::DisplayAlert('Incorrect Username / Password', 'danger'));
}
}
My Filter:
<?php
/*
|--------------------------------------------------------------------------
| Application & Route Filters
|--------------------------------------------------------------------------
|
| Below you will find the "before" and "after" events for the application
| which may be used to do any work before or after a request into your
| application. Here you may also register your custom route filters.
|
*/
App::before(function($request)
{
//
});
App::after(function($request, $response)
{
//
});
/*
|--------------------------------------------------------------------------
| Authentication Filters
|--------------------------------------------------------------------------
|
| The following filters are used to verify that the user of the current
| session is logged into this application. The "basic" filter easily
| integrates HTTP Basic authentication for quick, simple checking.
|
*/
Route::filter('auth', function()
{
if (Auth::guest())
{
if (Request::ajax())
{
return Response::make('Unauthorized', 401);
}
else
{
return Redirect::guest('login');
}
}
});
Route::filter('auth.basic', function()
{
return Auth::basic();
});
/*
|--------------------------------------------------------------------------
| Guest Filter
|--------------------------------------------------------------------------
|
| The "guest" filter is the counterpart of the authentication filters as
| it simply checks that the current user is not logged in. A redirect
| response will be issued if they are, which you may freely change.
|
*/
Route::filter('guest', function()
{
if (Auth::check()) return Redirect::to('/');
});
/*
|--------------------------------------------------------------------------
| CSRF Protection Filter
|--------------------------------------------------------------------------
|
| The CSRF filter is responsible for protecting your application against
| cross-site request forgery attacks. If this special token in a user
| session does not match the one given in this request, we'll bail.
|
*/
Route::filter('csrf', function()
{
if (Session::token() !== Input::get('_token'))
{
throw new Illuminate\Session\TokenMismatchException;
}
});
apparently if I not using olliread this route is not working. I always can go to onlinetest even i'm not logging in.
Is there any solution for the route? or maybe I got it wrong at my controller?
Thanks.
You don't have a "user" filter which you specify in your Route group. Try swapping out "user" in your route group to "auth":
<?php
Route::group(['before' => 'auth'], function()
{
// ...
});

Slim PHP: Only catch valid routes with middleware

I'm writing a REST API with Slim. I have written a small middleware to protect the resources so only authenticated users will be able to access them:
<?php
class SecurityMiddleware extends \Slim\Middleware
{
protected $resource;
public function __construct($resource)
{
$this->resource = $resource;
}
public function call()
{
//get a reference to application
$app = $this->app;
//skip routes that are exceptionally allowed without an access token:
$publicRoutes = ["/","/login","/about"];
if (in_array($app->request()->getPathInfo(),publicRoutes)){
$this->next->call(); //let go
} else {
//Validate:
if ($this->resource->isValid()){
$this->next->call(); //validation passed, let go
} else {
$app->response->setStatus('403'); //validation failed
$app->response->body(json_encode(array("Error"=>"Access token problem")));
return;
}
}
}
}
This works, but the undesired side effect is the middleware does not make a distinction between existing routes and non-existing routes. For example, if a the user attempts to request a route like /dfghdfgh which does not exist, instead of getting an HTTP status code of 404 he'll get a 403 saying there is no access token. I would like to add an implementation similar to the following check on the middleware class:
if ($app->hasRoute($app->request->getPathInfo()){
$this->next->call(); //let go so user gets 404 from the app.
}
Any ideas how this can be achieved?
I use a hook to do what you're trying to do, as MamaWalter suggested, but you want to use slim.before.dispatch rather than an earlier hook. If the route your user is trying to visit doesn't exist, the hook will never be called and the 404 gets thrown.
I'm doing exactly that in my own Authorization Middleware. Works like a charm.
Maybe my implementation will work for you:
<?php
class CustomAuth extends \Slim\Middleware {
public function hasRoute() {
$dispatched = false;
// copied from Slim::call():1312
$matchedRoutes = $this->app->router->getMatchedRoutes($this->app->request->getMethod(), $this->app->request->getResourceUri());
foreach ($matchedRoutes as $route) {
try {
$this->app->applyHook('slim.before.dispatch');
$dispatched = $route->dispatch();
$this->app->applyHook('slim.after.dispatch');
if ($dispatched) {
break;
}
} catch (\Slim\Exception\Pass $e) {
continue;
}
}
return $dispatched;
}
public function call() {
if ($this->hasRoute()) {
if ($authorized) {
$this->next->call();
}
else {
$this->permissionDenied();
}
}
else {
$this->next->call();
}
}
}
Not exactly what you asking for, but personnaly when i need to check authentification on some routes i do it like this.
config:
$config = array(
...,
'user.secured.urls' => array(
array('path' => '/user'),
array('path' => '/user/'),
array('path' => '/user/.+'),
array('path' => '/api/user/.+')
),
...
);
middleware:
/**
* Uses 'slim.before.router' to check for authentication when visitor attempts
* to access a secured URI.
*/
public function call()
{
$app = $this->app;
$req = $app->request();
$auth = $this->auth;
$config = $this->config;
$checkAuth = function () use ($app, $auth, $req, $config) {
// User restriction
$userSecuredUrls = isset($config['user.secured.urls']) ? $config['user.secured.urls'] : array();
foreach ($userSecuredUrls as $url) {
$urlPattern = '#^' . $url['path'] . '$#';
if (preg_match($urlPattern, $req->getPathInfo()) === 1 && $auth->hasIdentity() === false) {
$errorData = array('status' => 401,'error' => 'Permission Denied');
$app->render('error.php', $errorData, 401);
$app->stop();
}
}
};
$app->hook('slim.before.router', $checkAuth);
$this->next->call();
}
but if almost all your routes need authentification maybe not the best solution.
great example: http://www.slideshare.net/jeremykendall/keeping-it-small-slim-php

Categories