dongpo2340
dongpo2340
2016-10-19 08:04

不好的做法? 按用户名排序,然后在密码匹配时进行验证然后添加到会话中?

已采纳
$user = \App\User::where("name", $req->us)->firstOrFail();

then:

if(Hash::check($plain_text_password, $user->password)){
   //add user to session
}
else{
  //bad credentials
}

I'm aware of other methods available in Laravel, I'm asking about this specific situation.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • doulin3510 doulin3510 5年前

    There are two approaches.

    Approach 1. You can add both username password in the where condition.

    If the username and password not matching, The error message will be like "Invalid Username and password"

    Approach 2. (Your approach). Get the user record from the user table using where("name", $req->us) and validate the password if(Hash::check($user->password, $user->password)). The advantage in this approach is you can show the error message like below.

    • If the username is not in the table, you can display error like "Invalid Username".
    • If the password is not matching, you can display error like "Invalid Password".

    You can use any approach and from a security perspective you can go with the approach 1.

    点赞 评论 复制链接分享
  • duanha3539 duanha3539 5年前

    Why not using following code since it is more cleaner approach to check if username exists in database and then login ?

    // do validation 
    $validator = Validator::make($request->all(), [
        'username'    =>    'required|exists:users',
        'password'    =>    'required' 
    ]);
    
    if($validator->fails()) {
         return redirect()->back()->withErrors($validator); 
    }
    
    // try login using given credentials 
    if (Auth::attempt(['username' => $request->input('username'), 'password' =>   $request->input('password')])) {
           // Authentication passed...
           return redirect()->intended('dashboard'); 
    }
    
    点赞 评论 复制链接分享

相关推荐