I'm getting this TokenMismatchException with Laravel 4.2.
TokenMismatchException will show up when I trying to post request.
For example Login Page.
If I submit that form TokenMismatchException will show up.
Is there any way I can validate all post request submitted ?
Here's the error :
Route::filter('csrf', function()
{
if (Session::token() != Input::get('_token'))
{
throw new Illuminate\Session\TokenMismatchException;
}
});
Here's my code :
route.php
Route::get('login',array('as' => 'login', 'uses' => 'AuthController#getLogin'))->before('guest');
Route::post('login',array('uses' => 'AuthController#postLogin'))->before('csrf');
Route::group(array('before' => 'auth'), function(){
Route::get('dashboard', array('as' => 'panel', 'uses' => 'DashboardController#view_dashboard'));
});
AuthController.php
class AuthController extends Controller {
public function getLogin(){
return View::make('users.login');
}
public function postLogin(){
$rules = array('username' => 'required', 'password' => 'required');
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()){
return Redirect::route('login')->withErrors($validator);
}
$auth = Auth::attempt(array(
'username' => Input::get('username'),
'password' => Input::get('password')
), false);
if(!$auth){
return Redirect::route('login')->withErrors(array(
'Maaf anda bukan sebagai admin..'
));
}
//return "Success";
return Redirect::to('dashboard');
}
}
DashboardController.php
class DashboardController extends Controller {
public function view_dashboard(){
return View::make('dashboard.view_home_admin');
}
}
seems like you don't have hidden csrf field in your form.
try to add this in your form
{{ Form::token() }}
Related
I do not understand the following problem.
Here are me routes:
Route::get('events', array('as' => 'events' ,'uses' => 'EventController#index'));
Route::get('event/{id}', array('as' => 'event' ,'uses' => 'EventController#view'));
Route::get('event/new_event', array('as'=> 'new_event', 'uses' => 'EventController#newEvent'));
Route::post('event/create', array('uses' => 'EventController#create'));
Route::get('event/{id}/edit', array('as' => 'edit_event', 'uses' => 'EventController#edit'));
Route::post('event/update', array('uses' => 'EventController#update'));
Route::delete('event/delete', array('uses' => 'EventController#destroy'));
I can not create a new event, because when I click on the 'New Event' button, it uses EventController#view instead of EventController#newEvent.
Here is the EventController:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use App\EventModel;
class EventController extends Controller
{
public function index()
{
$events = EventModel::all();
return \View::make('event/index')->with('events', $events);
}
public function view($id)
{
return \View::make('event/view')
->with('event', EventModel::find($id));
}
public function newEvent()
{
dd("dd");
return \View::make('event/create');
}
public function create()
{
$validator = EventModel::validate(Input::all());
if($validator->fails())
{
$messages = $validator->messages();
return redirect()->action('EventController#newEvent')
->withErrors($validator)
->withinput();
}
else
{
EventModel::create(array(
'title'=>Input::get('title'),
'start'=>Input::get('start'),
'end'=>Input::get('end'),
'userID'=>\Auth::user()->id,
));
//Session::flash('message', 'New event has been created!');
flash()->overlay('New event has been created!', 'Success');
return redirect()->back();
}
}
public function edit($id)
{
return \View::make('event/edit')
->with('event', EventModel::find($id));
}
public function update()
{
$event = EventModel::find(Input::get('event_id'));
$validator = EventModel::validate(Input::all());
if($validator->fails())
{
$messages = $validator->messages();
return redirect()->back()
->withErrors($validator)
->withinput();
}
else
{
$event->title = Input::get('title');
$event->start = Input::get('start');
$event->end = Input::get('end');
$event->save();
//Session::flash('message', 'Successfully updated!');
flash()->overlay('Event has been sucessfully updated!', 'Success');
return redirect()->back();
}
}
public function destroy()
{
$id = Input::get('event_id');
dd("$id");
}
}
Why does this problem occur?
You have to sort your routes because laravel checks the order of the routes.
Try:
Route::get('events', array('as' => 'events' ,'uses' => 'EventController#index'));
Route::get('event/new_event', array('as'=> 'new_event', 'uses' => 'EventController#newEvent'));
Route::post('event/create', array('uses' => 'EventController#create'));
Route::post('event/update', array('uses' => 'EventController#update'));
Route::delete('event/delete', array('uses' => 'EventController#destroy'));
Route::get('event/{id}', array('as' => 'event' ,'uses' => 'EventController#view'));
Route::get('event/{id}/edit', array('as' => 'edit_event', 'uses' => 'EventController#edit'));
Laravel route checks in the order they were defined.
event/new_event and event/{id} both have same route structure and so it is going to view action.
Change the order -
Route::get('event/new_event', array('as'=> 'new_event', 'uses' => 'EventController#newEvent'));
Route::get('event/{id}', array('as' => 'event' ,'uses' => 'EventController#view'));
I'm facing problem in my Laravel 5.3 custom auth want to use my own functions or pages when I check Auth::check() it returns false.
Here is User controller:
namespace App\Http\Controllers;
use App\User;
use Illuminate\Support\Facades\Session;
use validatior;
use Auth;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function postSignUp(Request $request)
{
$validation = \Validator::make($request->all(), [
'email' => 'email|required|unique:users',
'password' => 'required|min:4'
]);
if ($validation->fails()) {
return redirect()->back()->withErrors($validation->errors());
} else {
$user = new User();
$user->email = $request->get("email");
$user->password = bcrypt($request->get['password']);
$user->save();
}
return redirect('signupPage');
}
public function postSignIn(Request $request)
{
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
if (Auth::attempt(['email' => $request['email'], 'password' => $request['password']])) {
return redirect('users/profile');
}
dd(Auth::check());
exit;
}
}
After sign in I want to redirect at profile page but my condition is not working. My routes are:
Route::group(['prefix' => 'users'], function(){
Route::group(['middleware' => 'guest'], function(){
Route::get('/signupPage','UserController#getSignUp');
Route::post('/register',array ('as'=>'signup', 'uses' =>'UserController#postSignUp', ));
Route::get('signInPage', array('as' => 'signInPage', 'uses' => 'UserController#getSignIn'));
Route::post('/postLogin', array('as' => 'postLogin', 'uses' => 'UserController#postSignIn'));
});
Route::group(['middleware' => 'auth'], function(){
Route::get('/profile', array('as' => 'profile', 'uses' => 'UserController#getProfile'));
Route::get('/logout', array('as'=>'logout', 'uses'=> 'UserController#logout'));
});
});
Here are some Modifications of your code
public function postSignUp(Request $request)
{
$email = $request->input('email');
$pass = $request->input('password');
$validation = \Validator::make($request->all(), [
'email' => 'email|required|unique:users',
'password' => 'required|min:4'
]);
if ($validation->fails()) {
return redirect()->back()->withErrors($validation->errors());
} else {
$pas = bcrypt($pass);
$user = new User();
$user->email = $email;
$user->password = $pas;
$user->save();
}
return redirect('users/signInPage');
}
Do use bcrypt while registering your User as this function is by default used by Auth Attempt function
public function postSignIn(Request $request)
{
$this->validate($request, [
'email' => 'required',
'password' => 'required',
]);
$email= $request->input['email'];
$password= $request->input['password'];
if (Auth::attempt(['email'=>$email,'password'=>$password']))
{
return redirect('users/profile');
}
return redirect('users/signInPage')->withErrors(['failure' => 'The credentials you entered did not match our records. Try again!',]);
}
finally this will give you too many redirects error as you using default middlewares, because your logic is now differ from the default one that's why you have to write your custom middleware, for this run this command
php artisan make:middleware CutomAuth
this will create your custom middleware now write code in it by your logic and after registering in app/Http/Kernel.php as \n
'customauth' => \Illuminate\Auth\Middleware\CutomAuth::class, you are good to go
to login I'm using laravel with an external validation of user credentials, after redirection data stored in Auth::user() doesn't persist and Auth::check() = false, but the session data saved correctly. After the login if I enter to the dashboard I 'm redirected to the login.
Routes.php
Route::group(['middleware' => ['web']], function () {
Route::get('/test', [
'as' => 'test',
function () {
echo "Session------>";
var_dump(\Illuminate\Support\Facades\Session::get('user'));//Returns user data
echo "User------>";
var_dump(\Illuminate\Support\Facades\Auth::user());// Returns null
echo "\ncheck user.------->";
var_dump(\Illuminate\Support\Facades\Auth::check());//Returns false
}
]);
});
//Login
Route::group(['middleware' =>[ 'web']], function () {
Route::get('/login', ['as' => 'login', 'uses' => 'AuthController#login']);
Route::post('/login', ['as' => 'login', 'uses' => 'AuthController#loginpost']);
Route::get('/logout', ['as' => 'logout', 'uses' => 'AuthController#logout']);
});
Route::group(['middleware' => ['auth', 'web']], function () {
Route::get('/', ['as' => 'home', 'uses' => 'DashboardController#index']);
//Dashboard
Route::get("/dashboard", ['as' => 'dashboard', 'uses' => 'DashboardController#index']);
}
AuthController.php
class AuthController extends Controller
{
public function login()
{
return view('auth/login');
}
public function loginpost(LoginRequest $request)
{
$credentials = $request->only('username', 'password');
$loginRequest = new LoginUserRequest($credentials['username'], md5($credentials['password']));
$userRepo = new MongoUserRepository();
$service = new GetUserByCredentialsService($userRepo, $loginRequest);
$authUser = $service->handle(new UserObjectPresenter());
var_dump($authUser);
if (isset($authUser)) {
$us = new User();
$us->id = $authUser->id;
$us->email = $authUser->email;
$us->fullname = $authUser->fullname;
Auth::login($us);
$user = Auth::user();
Session::put('user', $user);
Session::save();
echo "----saved user------";
var_dump(Auth::user()); //Returns correct user data
echo "Auth::check()->";
var_dump(Auth::check()); //Returns true
return redirect()->route('test');
} else {
return redirect()->route('login')->withInput()->withErrors(['Invalid email or password.']);
}
}
}
$service->handle(new UserObjectPresenter()); returns null or user data if login is correct.
Use Auth::attempt after login we you actually starting your session, otherwise Auth::check always returns false,
use following code
$userdata = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
if (Auth::attempt($userdata)) {
return view('dashboard');
}
You aren't passing an 'existing' user record to Auth::login. It has no id so it won't be able to be pulled back up on the next request.
Save that user record or use an existing one to pass to Auth::login
If I use Auth::user()->username in a Blade file laravel returns me an empty String but Auth::user()->email is filled. I use my own AuthController and my Login,Register and Logout work perfectly but I can't get the username.
Routes.php
<?php
Route::group(['middleware' => ['web']] , function () {
Route::get('/', function () {
return view('welcome');
})->name('home');
});
Route::group(['middleware' => ['web','guest']], function () {
Route::auth();
#Sign up Routes
Route::get('/signup', function () {
return view('auth.signup');
})->name('auth.signup');
Route::post('/signup', 'AuthController#signup');
#Sign in Routes
Route::get('/signin', function () {
return view('auth.signin');
})->name('auth.signin');
Route::post('/signin', 'AuthController#signin');
});
Route::group(['middleware' => ['web','auth']], function () {
Route::auth();
#Sign out Routes
Route::get('/signout', 'AuthController#signout')->name('auth.signout');
});
And my custom Auth Controller is:
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
class AuthController extends Controller
{
public function signup(Request $request) {
$this->validate($request, [
'email' => 'required|unique:users|email|max:255',
'username' => 'required|unique:users|alpha_dash|min:2|max:20',
'password' => 'required|min:6'
]);
User::create([
'email' => $request->input('email'),
'username' => $request->input('username'),
'password' => bcrypt($request->input('password')),
]);
return redirect()->route('home');
}
public function signin(Request $request) {
$this->validate($request, [
'email' => 'required',
'password' => 'required'
]);
if(!Auth::attempt($request->only(['email', 'password']), $request->has('remember'))) {
return redirect()->back()->with('flash-message','We can not sign you in with this data!');
}
return redirect()->route('home');
}
public function signout() {
Auth::logout();
return redirect()->route('home');
}
}
Maybe someone can help me
.
Note:
I added the username into User.php under the filled array.
Most likely you are missing username in $fillable of your User model.
The create method only accept fields coming from $fillable.
Please edit your User model like this:
protected $fillable = [
'email', 'username', 'password',
];
Only $fillable fields insert by Create method.
I tried to create a login, after I tried successfully identified,
return "Success Login";
but when I replace with
return Redirect::to('dashboard');
always returned to Login page
can you help me ? what's wrong with my code...
here is my code :
route.php
Route::get('login',array('as' => 'login', 'uses' => 'AuthController#getLogin'))->before('guest');
Route::post('login',array('uses' => 'AuthController#postLogin'))->before('csrf');
Route::group(array('before' => 'auth'), function(){
Route::get('dashboard', array('as' => 'panel', 'uses' => 'DashboardController#view_dashboard'));
});
AuthController.php
class AuthController extends Controller {
public function getLogin(){
return View::make('users.login');
}
public function postLogin(){
$rules = array('username' => 'required', 'password' => 'required');
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()){
return Redirect::route('login')->withErrors($validator);
}
$auth = Auth::attempt(array(
'username' => Input::get('username'),
'password' => Input::get('password')
), false);
if(!$auth){
return Redirect::route('login')->withErrors(array(
'Maaf anda bukan sebagai admin..'
));
}
//return "Success";
return Redirect::to('dashboard');
}
}
DashboardController.php
class DashboardController extends Controller {
public function view_dashboard(){
return View::make('dashboard.view_home_admin');
}
}
view_home_admin.blade.php
<h1>Welcome <small>{{ ucwords(Auth::user()->username) }}</small></h1>