用户不会保持登录状态 - laravel 5.7

问题描述 投票:0回答:1

我正面临我的问题,登录后网站上的用户将他重定向到主页,一切正常,但当用户访问任何其他页面时,他不再登录,我不知道什么是问题。

对不起,所以如果有什么需要更多,请告诉我

我正在使用:laravel:5.7 php:7.1.3

路线:

<?php

use App\Http\Controllers\PagesController;



Route::get('/','PagesController@index');

Route::get('/login','PagesController@login');
Route::post('/login','PagesController@validateLogin');

Route::post('/signup','PagesController@insert');
Route::get('/signup','PagesController@signup');


Route::get('/postRequest','PagesController@postRequest');
Route::post('/postRequest','PagesController@postuser');

Route::get('/session','PagesController@usession');

会话配置文件:

use Illuminate\Support\Str;

return [

    /*
    |--------------------------------------------------------------------------
    | Default Session Driver
    |--------------------------------------------------------------------------
    |
    | This option controls the default session "driver" that will be used on
    | requests. By default, we will use the lightweight native driver but
    | you may specify any of the other wonderful drivers provided here.
    |
    | Supported: "file", "cookie", "database", "apc",
    |            "memcached", "redis", "array"
    |
    */

    'driver' => env('SESSION_DRIVER', 'file'),

    /*
    |--------------------------------------------------------------------------
    | Session Lifetime
    |--------------------------------------------------------------------------
    |
    | Here you may specify the number of minutes that you wish the session
    | to be allowed to remain idle before it expires. If you want them
    | to immediately expire on the browser closing, set that option.
    |
    */

    'lifetime' => env('SESSION_LIFETIME', 120),

    'expire_on_close' => false,

    /*
    |--------------------------------------------------------------------------
    | Session Encryption
    |--------------------------------------------------------------------------
    |
    | This option allows you to easily specify that all of your session data
    | should be encrypted before it is stored. All encryption will be run
    | automatically by Laravel and you can use the Session like normal.
    |
    */

    'encrypt' => false,

    /*
    |--------------------------------------------------------------------------
    | Session File Location
    |--------------------------------------------------------------------------
    |
    | When using the native session driver, we need a location where session
    | files may be stored. A default has been set for you but a different
    | location may be specified. This is only needed for file sessions.
    |
    */

    'files' => storage_path('framework/sessions'),

    /*
    |--------------------------------------------------------------------------
    | Session Database Connection
    |--------------------------------------------------------------------------
    |
    | When using the "database" or "redis" session drivers, you may specify a
    | connection that should be used to manage these sessions. This should
    | correspond to a connection in your database configuration options.
    |
    */

    'connection' => env('SESSION_CONNECTION', null),

    /*
    |--------------------------------------------------------------------------
    | Session Database Table
    |--------------------------------------------------------------------------
    |
    | When using the "database" session driver, you may specify the table we
    | should use to manage the sessions. Of course, a sensible default is
    | provided for you; however, you are free to change this as needed.
    |
    */

    'table' => 'sessions',

    /*
    |--------------------------------------------------------------------------
    | Session Cache Store
    |--------------------------------------------------------------------------
    |
    | When using the "apc" or "memcached" session drivers, you may specify a
    | cache store that should be used for these sessions. This value must
    | correspond with one of the application's configured cache stores.
    |
    */

    'store' => env('SESSION_STORE', null),

    /*
    |--------------------------------------------------------------------------
    | Session Sweeping Lottery
    |--------------------------------------------------------------------------
    |
    | Some session drivers must manually sweep their storage location to get
    | rid of old sessions from storage. Here are the chances that it will
    | happen on a given request. By default, the odds are 2 out of 100.
    |
    */

    'lottery' => [2, 100],

    /*
    |--------------------------------------------------------------------------
    | Session Cookie Name
    |--------------------------------------------------------------------------
    |
    | Here you may change the name of the cookie used to identify a session
    | instance by ID. The name specified here will get used every time a
    | new session cookie is created by the framework for every driver.
    |
    */

    'cookie' => env(
        'SESSION_COOKIE',
        Str::slug(env('PHP', 'laravel'), '_').'_session'
    ),

    /*
    |--------------------------------------------------------------------------
    | Session Cookie Path
    |--------------------------------------------------------------------------
    |
    | The session cookie path determines the path for which the cookie will
    | be regarded as available. Typically, this will be the root path of
    | your application but you are free to change this when necessary.
    |
    */

    'path' => '/',

    /*
    |--------------------------------------------------------------------------
    | Session Cookie Domain
    |--------------------------------------------------------------------------
    |
    | Here you may change the domain of the cookie used to identify a session
    | in your application. This will determine which domains the cookie is
    | available to in your application. A sensible default has been set.
    |
    */

    'domain' => env('SESSION_DOMAIN', null),

    /*
    |--------------------------------------------------------------------------
    | HTTPS Only Cookies
    |--------------------------------------------------------------------------
    |
    | By setting this option to true, session cookies will only be sent back
    | to the server if the browser has a HTTPS connection. This will keep
    | the cookie from being sent to you if it can not be done securely.
    |
    */

    'secure' => env('SESSION_SECURE_COOKIE', false),

    /*
    |--------------------------------------------------------------------------
    | HTTP Access Only
    |--------------------------------------------------------------------------
    |
    | Setting this value to true will prevent JavaScript from accessing the
    | value of the cookie and the cookie will only be accessible through
    | the HTTP protocol. You are free to modify this option if needed.
    |
    */

    'http_only' => true,

    /*
    |--------------------------------------------------------------------------
    | Same-Site Cookies
    |--------------------------------------------------------------------------
    |
    | This option determines how your cookies behave when cross-site requests
    | take place, and can be used to mitigate CSRF attacks. By default, we
    | do not enable this as other CSRF protection services are in place.
    |
    | Supported: "lax", "strict"
    |
    */

    'same_site' => null,

];

PageController:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use database\migrations;
use DB;
use Validator;
use App\users;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
 //Abdulmalik
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
class PagesController extends Controller
{
    public function index() {

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

        return view('postRequest');
    }
    public function postuser() {
        $user1 = new users();
    $email = request('reqName');
    $pass = request('reqDesc');
    $fn = request('category');
    $ln = request('skills');
$user1->email =$email;
$user1->password=$pass;
$user1->firstName=$fn;
$user1->lastName=$ln;

$user1->save();

        return view('postRequest');
    }
    public function login() {
        return view('login');
    }
    public function validateLogin(Request $request)
    {
        $this->validate($request, [
           'email' => 'required',
            'password' => 'required',
        ]);
         if (Auth::attempt(['email' =>  request('email'), 'password' =>  request('password')])) {
             // Success
            // $message = "successfully login ";
            // echo "<script type='text/javascript'>alert('$message');</script>";

             //$value = $request->session()->all();//Session::get('laravel_session');
             //Session::put('userId', $value);
             //$request->session()->keep(['laravel_session']);
             //echo $value;
             return view('index');



         } else {
             return "something happened"/*redirect()->back()*/;
         };
    }
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }

    public function signup() {
        return view('signup');
    }


    protected function validator(array $data)
    {
        return Validator::make($data, [
            'firstName' => 'required|string|max:255',
            'lastName' => 'required|string|max:255',
            'email' => 'unique:users,email',
            'password' => 'required|string|min:6|confirmed',
        ]);
    }


    public function insert(){
        $errors="";
        $firstName = request('Fname');
        $lastName = request('Lname');
        $pass = request('password');
        $em = request('email');
        $conpass = request('conPassword');
        $validation = Validator::make(
            [ //parameters
                'firstName' => request('Fname'),
                'lastName' => request('Lname'),
                'password' => request('password'),
                'email' => request('email'),
                'password_confirmation' => request('conPassword'),
            ], //rule
            [
                'firstName' => ['required','string','max:255' ],
                'lastName' => ['required','string','max:255' ],
                'password' => ['required','string','min:6','confirmed' ],
                'password_confirmation' => [],
                'email' => ['required', 'email','unique:users'],
            ],//error messages
            ['firstName.required' =>"الرجاء إدخال الاسم الأول *",
                'lastName.required' =>"الرجاء إدخال اسم العائلة *",
                'password.required' =>"الرجاء إدخال كلمة المرور *",
                'password.min' =>"كلمة المرور يجب ان تتكون من ستة خانات على الأقل *",
                'password.confirmed' =>"كلمة المرور يجب ان تتطابق *",
                'email.required' =>"الرجاء إدخال البريد الالكتروني *",
                'email.unique' =>"البريد الالكتروني مسجل مسبقا *ً",
                'email.email' =>"البريد الالكتروني يجب ان يكون بالصيغة الصحيحة *ً",

            ]
        );

        if ( $validation->fails() ) {
            $errors = $validation->messages();
            return redirect()->back()->withErrors($errors);
        }
        else{
            if($pass!=null) {
                $pass = Hash::make(request('password'));
            }
            $user1 = new users();
            $user1->email =$em;
            $user1->password=$pass;
            $user1->firstName=$firstName;
            $user1->lastName=$lastName;
            $user1->save();
            /*$data = array("email" => $em, "password" => $pass, "firstName" => $firstName, "lastName" => $lastName);
            DB::table('users')->insert($data);*/
        }



        return redirect('/');
    }


    public function usession(Request $request){
      dd($request->session()->all());
    }
}

登录控制器:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

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.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    protected function authenticated()
    {
        // Update last_session after logged-in
        User::find(Auth::id())->update(['laravel_session'=>Session::getId()]);
    }

}

result of: php artisan route:list

php laravel laravel-5.7 web-development-server
1个回答
0
投票

如您的路径文件所示,对于您的登录路由,您在PagesController上调用login和validateLogin函数,并且在构造函数的PagesController中,您有一个保护此控制器上的函数的中间件,其中是来宾中间件。为了向你们证明这一点,这里的中间件就像是说这个控制器上存在的所有函数只能由guest虚拟机看到,这就是为什么当你登录并导航到在PagesController上调用函数的其他路由时,midleware会阻止你,因为这些路由仅适用于访客(未登录的用户)所以要解决此问题,您可以尝试以下解决方案之一:

  • 在PagesController中的构造方法中,将其更改为

$this->middleware('guest', ['only' => [ 'login', 'validateLogin' ]]);

  • 或者将登录和validateLogin移动到LoginController,这样您就可以将中间件设置为guest用户。 (这是组织代码的最佳解决方案)
© www.soinside.com 2019 - 2024. All rights reserved.