Laravel,会议仅适用于1位在线用户

时间:2016-12-24 13:31:44

标签: php laravel session authentication

我是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');
}

1 个答案:

答案 0 :(得分: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命令