I have middleware that redirects the user if it it not logged in. The user is not prevented from filling in the form, only when he submits the data my middleware comes in to check if he is authenticated. It seems like it is not passing throught the middleware at all when the submit button is clicked.
My route
Route::group(['middleware' => 'allow.access'], function(){
Route::post('houses', [ //I wonder if I defined this
'as' => 'houses.store', //route correctly because
'uses' => 'HousesController#store' //it seems Laravel is ignoring it
]);
Route::get('houses/{id}/edit', [
'as' => 'houses.edit',
'uses' => 'HousesController#edit'
]);
});
My middleware works if I use this route inside the group:
Route::get('houses/create/{zip}', [
'as' => 'houses.create',
'uses' => 'HousesController#create'
]);
my middleware
public function handle($request, Closure $next)
{
if(!$request->session()->has('loginInfo'))
{
return redirect()->route('register.login');
}
return $next($request);
}
I am using the code below to create a user in Laravel. When I log in with this user, it does not appear to be "authenticated" (even though the ID, password, and tenanted information has been entered correctly). Authenticated users go to a "home" page. This just goes back to the login page.
I noticed that when the user was created the "remember_token" of the "user" table was not filled out.
How can I fill out this field? How can I fix this so that users created using PHP are authenticated?
TIA
$user = User::create([
'name' => $contractor->getFirstName() . ' ' . $contractor->getLastName(),
'email' => $contractor->getAsgnLogonID(),
'password' => bcrypt($contractor->getAsgnPassword()),
'tenantid' => $TENANTREFNO,
'wavemakerid'=> $contractor->getKeyID(),
]);
Here is the web.php file:
Route::get('/', function () {
return redirect()->route('login.showform');
});
Route::post('/login/custom', [
'uses' => 'Auth\LoginController#login',
'as' => 'login.custom'
]);
Route::get('/login/showform', [
'uses' => 'Auth\LoginController#showLoginForm',
'as' => 'login.showform'
]);
Route::get('/home', 'HomeController#index');
Route::get('/logout', 'Auth\LoginController#logout');
Route::get('/dashboard', 'DashboardController#index');
Auth::routes();
I made the changes below and was able to have the user logged in:
if ( $password == $local_password )
{
Auth::login($user);
return redirect('/home');
}
When the user log in or register, he is supposed to go the dashboard, but instead of it, it is being located to the /login page, which is not even there and hence error occours:
Sorry, the page you are looking for could not be found.
1/1
NotFoundHttpException in RouteCollection.php line 161:
Routes:
Route::get('/', function () {
return view('welcome');
})->name('home');
Route::group(['middleware' => ['web']], function(){
Route::get('upload',function(){
return view('files.upload');
});
Route::get('/wallet',[
'uses' => 'WalletController#getwallet',
'as' => 'wallet'
]);
Route::post('/addmoney',[
'uses' => 'WalletController#addmoney',
'as' => 'addmoney'
]);
Route::post('/signup',[
'uses' => 'UserController#postSignUp',
'as' => 'signup'
]);
Route::post('/signin',[
'uses' => 'UserController#postSignIn',
'as' => 'signin'
]);
Route::get('/dashboard',[
'uses' => 'UserController#getDashboard',
'as' => 'dashboard',
'middleware' => 'auth'
]);
Route::post('/handleUpload','FilesController#handleUpload');
Route::get('/pay', ['as' => 'pay', 'uses' => 'PaymentController#pay']);
# You will need one more.
Route::get('/payment/status', ['as' => 'payment_status', 'uses' => 'PaymentController#status']);
/**
* Using Named Routs to demonstrate all the possibilities.
*/
});
User controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Input;
use InvalidConfirmationCodeException;
use Flash;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class UserController extends Controller
{
public function getDashboard(){
return view('files.dashboard');
}
public function postSignUp(Request $request)
{
$this -> validate($request,[
'email' => 'required|email|unique:users',
'name' => 'required|max:20',
'password' => 'required|min:4'
]);
$email = $request['email'];
$name = $request['name'];
$password = bcrypt($request['password']);
$user = new User();
$user->email =$email;
$user->name = $name;
$user->password = $password;
$user->save();
return redirect()->route('dashboard');
//Auth::login($user);
}
public function postSignIn(Request $request)
{
$this -> validate($request,[
'email' => 'required',
'password' => 'required'
]);
if (Auth::attempt(['email' => $request['email'], 'password' => $request['password']])) {
return redirect()->route('dashboard');
}
return redirect()->back();
}
}
WalletController
public function getwallet(){
return view('files.wallet');
}
public function addmoney(Request $request){
$this->validate($request,[
'amount'=>'required'
]);
$amount = $request['amount'];
$wallet = new Wallet();
$wallet->amount=$amount;
$wallet->save();
return redirect()->route('/addmoney');
}
Even when I try localhost:8000/dashboard , it loads as localhost:8000/login as shows same error.Also, same problem occurs when I try to load /addmoney page, when the user submit amount and redirect to the next addmoney page.
I see your dashboard view view is in file.controller but you use the auth middleware. Put your dashboard view in your dashboard view in the auth folder.
Default in Laravel: resources/views/auth/yourviewhere
Here is the code.If sign in it goes to /dashboard route. but after I go to other route user session is not persisting(by dd I found this).thanks in advance if you solve, I spent hours on this.
Route::group(['middleware' => 'web'],function(){
Route::get('/', function () {
return view('welcome');
})->name('home');
Route::get('/dashboard' , [
'uses' => 'UserController#GetDashboard',
'as' => 'dashboard'
]);
Route::post('/signin' , [
'uses' => 'UserController#postSignin',
'as' => 'signin'
]);
});
in my login controller
public function postSignin(Request $request)
{
if(Auth::attempt(['email' => $request['email'],'password' => $request['password']])) {
return redirect()->route('dashboard');
}
return redirect()->back();
}
$request is an object, not an array. Try using $request->get('email').
what is the difference between:
Route::post('insert/{slug}/{page_number}/{person_type_id}/{user_id}', function($slug) {
return Response::json(
[
'success' => false,
'slug' => $slug
]);
});
and this:
Route::post(
'{slug}/users/page/{page_number}/insert-ben/{person_type_id}/user/{user_id}',
'PersonsController#insertBen'
);
The first one works. The latter used to work but it's no longer working now. I tried stepping through the code and the latter ends up going to the UsersController#login rather than to PersonsConroller#insertBen. So odd. This was working about a month ago. I'm trying to see what I changed with my version control but it's so strange that it's not working all of a sudden.
My posts are working fine as I can login and the post call to UsersController#doLogin is being called.
I even tested with this call:
Route::post(
'{slug}/users/page/{page_number}/insert-ben/{person_type_id}/user/{user_id}',
'UsersController#insertTest'
);
/controllers/UsersController.php
public function insertTest($slug)
{
if ( Request::ajax() ) {
return Response::json( [
'success' => false,
'slug' => $slug
] );
}
}
But the PersonsController#insertBen doesn't work. My PersonsController is working fine as I can update using this controller. So what could be the problem? Anyone encounter something similar? Why does the route.php call the post on some of Controller#method but not on others? Why does the closure function work but not the Controller#method?
UPDATE
Here's the entire file. I even tested by putting that line close to the top of the file too.
/** ------------------------------------------
* Route binding
* ------------------------------------------
*/
App::bind('Acme\Repositories\Interfaces\IPersonRepository', 'Acme\Repositories\Person\DbPersonRepository');
App::bind('Acme\Repositories\Interfaces\IUserRepository', 'Acme\Repositories\User\DbUserRepository');
App::bind('Acme\Repositories\Interfaces\IPage15Repository', 'Acme\Repositories\Pages\Page15Repository');
/** ------------------------------------------
* Route model binding
* ------------------------------------------
*/
Route::model('user', 'User');
Route::model('comment', 'Comment');
Route::model('post', 'Post');
Route::model('role', 'Role');
/** ------------------------------------------
* Route constraint patterns
* ------------------------------------------
*/
Route::pattern('comment', '[0-9]+');
Route::pattern('post', '[0-9]+');
Route::pattern('user', '[0-9]+');
Route::pattern('role', '[0-9]+');
Route::pattern('token', '[0-9a-z]+');
/** ------------------------------------------
* Admin Routes
* ------------------------------------------
*/
Route::group(array('prefix' => 'admin', 'before' => 'auth'), function()
{
# User Management
Route::get('users/', ['as' => 'admin.users.get.index', 'uses' => 'AdminUsersController#getIndex']);
Route::get('users/index', ['as' => 'admin.users.get.index_page', 'uses' => 'AdminUsersController#getIndex']);
Route::get('users/data', ['as' => 'admin.users.get.data', 'uses' => 'AdminUsersController#getData']);
Route::get('users/{user}/edit_user_by_page/{page_number}', ['as' => 'admin.users.get.edit_user_by_page', 'uses' => 'AdminUsersController#getEditUserByPage']);
# Admin Dashboard
Route::get('/', 'AdminDashboardController#getIndex' );
});
// Confide routes
Route::get('users/create', ['as' => 'confide.users.get.create', 'uses' => 'UsersController#create']);
Route::post('users', ['as' => 'confide.users.post.store', 'uses' => 'UsersController#store']);
Route::get('users/login', ['as' => 'confide.users.get.login', 'uses' => 'UsersController#login']);
Route::post('users/login', ['as' => 'users.login', 'uses' => 'UsersController#doLogin']);
Route::get('users/confirm/{code}', ['as' => 'confide.users.get.confirm', 'uses' => 'UsersController#confirm']);
Route::get('users/forgot_password', [ 'as' => 'users.forgot_password', 'uses' => 'UsersController#forgotPassword' ]);
Route::post('users/forgot_password', ['as' => 'confide.users.post.forgot_password', 'uses' => 'UsersController#doForgotPassword']);
Route::get('users/reset_password/{token}', ['as' => 'confide.users.get.reset_password', 'uses' => 'UsersController#resetPassword']);
Route::post('users/reset_password', ['as' => 'confide.users.post.reset_password', 'uses' => 'UsersController#doResetPassword']);
Route::get('users/resendconfirmationemail', [ 'as' => 'users.resendconfirmationemail', 'uses' => 'UsersController#getResendConfirmationEmail' ]);
Route::post('users/resendconfirmationemail', ['as' => 'confide.users.post.resendconfirmationemail', 'uses' => 'UsersController#postResendConfirmationEmail']);
Route::get('users/logout', ['as' => 'confide.users.get.logout', 'uses' => 'UsersController#logout'])->after('invalidate-browser-cache');
/** ------------------------------------------
* Frontend Routes
* ------------------------------------------
*/
Route::get('{slug}/users/page', ['as' => 'users.page.path', 'uses' => 'UsersController#getPage'])->where('slug', '^\b(ir){0,1}(revocable){1}\b$');
//get page_number
Route::get('{slug}/users/page/{page_number}', ['before' => 'auth', 'as' => 'users.page.page_number', 'uses' => 'PersonsController#index'])->where('slug', '^\b(ir){0,1}(revocable){1}\b$');
//get edit
Route::get('{slug}/users/page/{page_number}/edit', ['before' => ['auth', 'slug' ], 'as' => 'users.page.page_number.edit', 'uses' => 'PersonsController#edit'])->where('slug', '^\b(ir){0,1}(revocable){1}\b$');
//post insert-ben
Route::post('{slug}/users/page/{page_number}/insert-ben/{person_type_id}/user/{user_id}', ['before' => 'auth', 'as' => 'users.page.page_number.insert', 'uses' => 'PersonsController#insertBen'])->where('slug', '^\b(ir){0,1}(revocable){1}\b$');
//post delete-ben
Route::post('{slug}/users/page/{page_number}/delete-ben/{person_type_id}/user/{user_id}/person_id/{person_id}/address_id/{address_id}/ben_id/{ben_id}', ['before' => 'auth', 'as' => 'users.page.page_number.delete', 'uses' => 'PersonsController#deleteBen'])->where('slug', '^\b(ir){0,1}(revocable){1}\b$');
//put update
Route::put('{slug}/users/page/{page_number}/update', ['before' => 'auth', 'as' => 'users.page.page_number.update', 'uses' => 'PersonsController#update'])->where('slug', '^\b(ir){0,1}(revocable){1}\b$');
//get upgrade page when user goes to a page like (page 17 or other pages like page 9 and 10 I think) reserved only for irrevocable registered plans. TODO: get the upgrade View model
Route::get('{slug}/users/upgrade/{_meta}', [ 'as' => 'users.ugprade', 'uses' => 'PersonsController#upgrade' ] )->where('slug', '^\b(irrevocable){1}\b$');
//Paypal post Paypal info to tables paypals, paypal_transactions, pricings and getPaypalBtn
Route::put('paypal_transactions/{slug}/{page_number}/returnpaypalbtn', ['before' => 'auth', 'as' => 'paypal_transactions.returnpaypalbtn', 'uses' => 'PaypalTransactionsController#returnPaypalBtn'])->where('slug', '^\b(ir){0,1}(revocable){1}\b$');
/** ------------------------------------------
* Tests:
* ------------------------------------------
*/
Route::get('users/{username}/page', ['as' => 'users.page.test', 'uses' => 'UsersController#getPageTest']);
Route::get('{slug}/users/show_sql', ['as' => 'users.page.show_sql', 'uses' => 'PersonsController#showSql'])->where('slug', '^\b(ir){0,1}(revocable){1}\b$');
# Index Page - Last route, no matches
Route::get('/', array('before' => 'detectLang', 'uses' => 'UsersController#login'));
Boy, this took a long time to figure out. Thank God! What happened was that I had this line in my Route::filter('csrf', function().
This filter is called before your other Route::[method] so if there are any Route calls in your filter like I had in mine then your defined Route::[method] won't be called. I think by default but not 100% sure:
/app/filters.php
$token = Request::ajax() ? ( Request::header('X-CSRF-Token') ) : Input::get('_token');
Which I ended up getting from http://words.weareloring.com/development/laravel/laravel-4-csrf-tokens-when-using-jquerys-ajax/
It was an ajax call but this Request::header('X-CSRF-Token') was always null.
So I changed that to something more readable and that works.
if ( Request::ajax() )
{
$sRequestHeaderCSRF = Request::header('X-CSRF-Token');
if ( Request::header('X-CSRF-Token') === null || Request::header('X-CSRF-Token') === '' )
{
$token = Input::get('_token');
} else
{
$token = Request::header('X-CSRF-Token');
}
} else
{
$token = Input::get('_token');
}
The other snag was this Input::get('_token') which was returning null too.
I had to pass and, explicitly, name the _token in the data. I was, previously,
passing a serialized array as the data in the jQuery $.ajax. But the calls to
get the _token key name from this data in public function input($key = null, $default = null)
(see below) was not retrieving it from the serialized array; hence, the explicit key being passed as
'_token': oSerializeArray._token.
var oSerializeArray['_token'] = $('input[name="_token"]').val();
$.ajax({
type: action,
cache: false,
dataType: 'json',
url: sUrl,
data: {
'oSerializeArray': oSerializeArray,
'_token': oSerializeArray._token
},
beforeSend: function() {
}
})
.done( function( data, text, jqxhr ) {
data.success;
//data.iPersonsPK;
window.location.replace(sUrlEdit);
})
.fail( function ( data, jqxhr ) {
data.success;
})
.always( function ( data ) {
data.success;
});
Just fyi, Input::get('_token') is called from:
/vendor/illuminate/support/Illuminate/Support/Facades/Input.php
in this function:
public static function get($key = null, $default = null)
{
return static::$app['request']->input($key, $default);
}
and here:
/vendor/laravel/framework/src/Illuminate/Http/Request.php:248
in this function:
public function input($key = null, $default = null)
{
$input = $this->getInputSource()->all() + $this->query->all();
return array_get($input, $key, $default);
}
I had to step through the code.
This is my updated Route::filter('csrf', function():
Route::filter('csrf', function()
{
if ( Request::ajax() )
{
$sRequestHeaderCSRF = Request::header('X-CSRF-Token');
if ( Request::header('X-CSRF-Token') === null || Request::header('X-CSRF-Token') === '' )
{
$token = Input::get('_token');
} else
{
$token = Request::header('X-CSRF-Token');
}
} else
{
$token = Input::get('_token');
}
$sSessionToken = Session::token();
//if the tokens do not match then send to the login page
if (Session::token() != $token) {
return Redirect::to( 'users/login' );
}
});
Also, more fyi, for problems with your routes.php one may look at these files:
/vendor/laravel/framework/src/Illuminate/Routing/Router.php
/vendor/laravel/framework/src/Illuminate/Routing/Route.php
and set break points while looking at your stack calls during debugging.
BTW, I read that one can use this to set the X-CSRF token in the headers of your ajax calls with this:
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="_token"]').attr('content')
}
});
The above is referenced from http://words.weareloring.com/development/laravel/laravel-4-csrf-tokens-when-using-jquerys-ajax/
I'm wondering if Taylor Otwell has some info on the architechtural design and explanations of the framework.
I was going to read about Symfony but not sure if will help me more thoroughly understand the underpinnings of Laravel.
I know there is the Laravel API docs which is helpful but something more like a study of the design. Any ideas?