【问题标题】:Laravel , sessions just work for 1 online userLaravel,会话仅适用于 1 个在线用户
【发布时间】:2017-05-09 21:12:24
【问题描述】:

我是 laravel 新手

我编写了一个许多用户都可以使用的脚本

但我遇到的问题是:

当像“Helen”这样的用户登录时,她可以看到她的个人资料 但如果下一个像“Maria”这样的用户登录,Marias 面板将为他们俩显示

我认为这意味着只能同时激活一个会话,并且会话的值将针对最新用户 并且旧用户会话不会过期,只是会话中的值将被更改,因此她识别为另一个用户并且可以看到该用户的个人资料,并且当用户注销时,由于会话关闭,所有用户将被注销。 这是我的简单代码:

public function Login(){
        $this->Token();
        $pack=Input::all();
        try {
           $result=DB::table('user')->where('Email','=',$pack['email'])->get();
            if (Hash::check($pack['password'], $result[0]->Password)){
                session(['there' => $result['0']->Email]);
                return redirect('dashboard');
            }
            return redirect('dashboard')->with('does','wrong password');
        }catch(Exception $e){
            return redirect('dashboard')->with('does',.$e);
        }
}

public function UserType() {
        if(!session('there'))
            return "Not Logged";
        else {
            $result = DB::table('user')->where('Email', '=', session('there'))->get();

        if($result!=null)
            return "User";
}

public function ShowDashboard(){
        if($this->UserType()=="Not Logged")
        else
            return view('pages/dashboard');
}

【问题讨论】:

  • 似乎有些不对劲;为什么要完全避开 Laravel 的内置身份验证?我在您的方法中发现了一些可能返回未知值的逻辑漏洞。
  • 返回值为真...我试过dd(session),返回值为真

标签: php laravel session authentication


【解决方案1】:

我不知道你为什么要session() 来管理用户登录...此外,它们在很大程度上取决于用户从同一台计算机、同一浏览器登录的情况...cookie...等等。 . 也许这就是为什么您可能会同时获得 2 个不同的会话值...

无论如何.. 请尝试使用 Laravel 的预定义函数 Auth 来处理您的登录/注销过程。

public function Login()
{
  // What does this do? Check for a CSRF token? If yes, then
  // please understand then Laravel automatically checks
  // for the CSRF token on POST/PUT requests and therefore
  // there is no special need to use the below function...
  $this->Token();

  $pack = request()->only(['email', 'password']);

  // I don't really feel try catch is required here... but completely your choice...
  try {
    if(auth()->attempt($pack)) {
      return redirect('dashboard')
    }
    return redirect->back()->with('does', 'wrong password');
  } catch(Exception $e) {
    return redirect->back()->with('does', $e);
  }
}


public function ShowDashboard()
{
  // You can remove this if/else by adding the 'auth' middleware
  // to this route
  if(!auth()->check())
    return view('pages.dashboard');
  else
    return redirect(route('login'));
}

我发现你上面的代码有很多问题...

  1. 请使用 camelCase 命名函数...(我没有更改上面代码中的命名,因为我真的不知道您在工作场所或 idk 遵循什么规则.. .)
  2. 对于简单的 true/false 情况,请不要返回字符串
  3. 请尽可能使用Models。非常复杂和广泛的查询需要原始的 DB 命令

【讨论】:

    猜你喜欢
    • 2015-12-24
    • 2014-06-04
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多