2
votes

i have some problem with laravel v 5.2

i use ajax post request , server response 201 Ok, return data user, but when start redirect to

public function __construct()
{
    $this->middleware('auth');
}

public function index()
{
    return view('home');
}

i recive again login form ,,, and if i auth with blade form , work fine.

ajax send me success:function(){

               alert('okey all fine');      

             window.location.href = "/home";     

but /home page not see my session or ?? :) thanks

4
Your question is not clear. Describe your question - Praveen Srinivasan
after ajax login from /index i try redirect to /home, but route have auth middleware , and i see not /home , i recive /login , in /login i have login.blade not ajax form. and if i login with blade form, and go to /home all be fine - user3019569
If you want to login using ajax means you have to make login form using ajax. - Praveen Srinivasan
i have form, and i attache her to container <div id=login></div> - user3019569

4 Answers

0
votes

please update laravel/framework to 5.2.27 and backup your Auth\AuthController (in case you have make any changes) then issue a php artisan make:auth to replace the existing laravel generated auth features file with the latest bug fixed copy.

see if this solved your auth session not being persistent problem

0
votes

may be the error as there are 2 missing pieces of middleware on api route group. added the following 2 middlewares to the api middleware group and then added that group to API routes

 \App\Http\Middleware\EncryptCookies::class,
\Illuminate\Session\Middleware\StartSession::class,
0
votes

Okey lets see my files

kernel

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
        ],


        'api' => [
            'throttle:60,1',

        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFormToken::class,
    'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class,
    'role' => \Zizaco\Entrust\Middleware\EntrustRole::class,
        'permission' => \Zizaco\Entrust\Middleware\EntrustPermission::class,
        'ability' => \Zizaco\Entrust\Middleware\EntrustAbility::class,

    ];
}

routes

<?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 controller to call when that URI is requested.
|
*/

Route::group(['middleware' => ['web']], function () {

    Route::get('/', function () {
        return view('welcome');
    });



});

//Route::get('/register',array('as'=>'newRegister','uses'=>'MailController@index'));

Route::post('/auth', 'MailController@store');

Route::group(['prefix' => 'api', 'middleware' => 'auth:api'], function () {

    Route::resource('note', 'NoteController');
});

Route::group(['middleware' => 'web'], function () {
    Route::auth();    
    Route::get('/backoffice', 'HomeController@home');


});


Route::group(['middleware' => 'web'], function () {
    Route::auth();    
    Route::get('/home', 'LoginController@index');

});

request

<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class LoginRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }



    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
        ];
    }
}

controller

<?php

namespace App\Http\Controllers;

use Auth;
use Mail;
use Session;
use Redirect;
use App\Http\Requests;
Use App\Http\Requests\LoginRequest;
use Illuminate\Http\Request;



Use App\User;

class MailController extends Controller
{
   public function store(LoginRequest $request)
    {


     $credentials = $request->only('email', 'password');

     if (Auth::attempt($credentials)) {

    if (Auth::check()) {


        if (Auth::check()) return Redirect::to('/home');

     }
    }

       return response(['msg' => 'Error'], 401) // 401 Status Code: Forbidden, needs authentication
          ->header('Content-Type', 'application/json');

    }

     public function createRegister(Request $request)

    {
        $user = new User;
        $data['name']=$user->name=$request->username;
        $data['email']=$user->email=$request->email;
        $user->password=bcrypt($request->password);
        $user->remember_token=str_random(100);
        if ($request->password==$request->confirm_password){


        if ($user->save())
        {
            Mail::send('mail.register',['data'=>$data], function($mail) use ($data){
                $mail->to($data['email'],$data['name'])->from('[email protected]')->subject('Welcome to');
            });
        }}else { return "Password not match";}
        return back();
    }
}

and my form javascript

 var form1 = {
            view:"form", id:"log2", width:550, scroll:false,
            elements:[
                {  cols :[
                { view:"text", hidden:true, name:"_token", value:'{{ csrf_token() }}', labelWidth:50, label:"Email" },
                    { view:"text", name:"email", value:'', labelWidth:50, label:"Email" },
                    { view:"text", name:"password", value:'', type:"password", placeholder:"password" },
                    {view:"button",  width:100, label:"login", click:login}
                ]}
            ]
        };

  function login(){
            QW.message("Auth");
            var values = $$("log2").getValues();
            values = JSON.stringify(values);
            console.log(values)
            QW.ajax().sync().headers({'Content-Type':'application/json'}).post("/auth", values, {
                error:function(){
                             QW.alert('Oops');   

                },
                success:function(){




                    QW.alert('Thanks All fine');    

                     //    window.location.href = "/home";   
        }
            });

        }
0
votes

I'm found solution .

problem with routes... session not sign in my prev solution... but this correct.

Route::group(['middleware' => ['web']], function () {

    Route::get('/', function () {
        return view('welcome');
    });

    Route::get('/home', 'HomeController@index');
    Route::get('/redirect', 'SocialAuthController@redirect');
    Route::get('/callback', 'SocialAuthController@callback');
    Route::post('/auth', 'MailController@store');


});


Route::auth();

Route::get('/home', 'HomeController@index');