【问题标题】:Laravel 5 - How to check username & password is match with table?Laravel 5 - 如何检查用户名和密码是否与表匹配?
【发布时间】:2015-12-06 10:50:06
【问题描述】:

我在Laravel 5 中创建了以下登录表单,我只想检查用户名和密码是否与数据库表的匹配,如果匹配,则重定向到仪表板页面,否则留在登录页面。我也在尝试自己找到解决方案,但我发布这个问题是为了了解如何在Laravel 5 中做这些事情。

有什么想法吗??

2015_09_10_050324_admin_details.php(迁移)

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AdminDetails extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('admin_details', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('username')->unique();
            $table->string('email')->unique();
            $table->string('password', 60);
            $table->integer('status');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('admin_details');
    }
}

数据库结构

login.blade.php(查看)

<form name="frmLogin" action="{{ URL::to('administrator/userAuthentication') }}" method="post">
    <input name="_token" type="hidden" value="{{ csrf_token() }}"/>
    <div class="form-group has-feedback">
        <input type="text" name="username" id="username"class="form-control" placeholder="Username">
        <span class="glyphicon glyphicon-envelope form-control-feedback"></span>
    </div>
    <div class="form-group has-feedback">
        <input type="password" name="password" id="password" class="form-control" placeholder="Password">
        <span class="glyphicon glyphicon-lock form-control-feedback"></span>
    </div>
    <div class="row">
        <div class="col-xs-4">
            <button type="submit" class="btn btn-primary btn-block btn-flat">Login</button>
        </div><!-- /.col -->
    </div>
</form>

AdminLoginController.php(控制器)

    <?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use Auth;
use App\Http\Controllers\Controller;
use App\AdminLoginModel;


class AdminLoginController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        return view('backend.login');
    }

    /**
     * Handle an authentication attempt for admin user.
     *
     */
    public function userAuthentication(Request $request)
    {

        if (Auth::attempt(array('username' => $request->username, 'password' => $request->password))){
            return "success";
        }else{
            return "Wrong Credentials";
        }
        die;
    }
}

AdminLoginModel.php(模型)

    <?php
/*namespace App;
use DB;
use Illuminate\Database\Eloquent\Model;*/

namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class AdminLoginModel extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    use Authenticatable, CanResetPassword;

    protected $table = 'admin_details';
    protected $fillable = ['username', 'password'];
}

routes.php

<?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::get('/', function () {
    return view('welcome');
});

Route::resource('dashboard','DashboardController');
Route::resource('administrator','AdminLoginController');
Route::resource('users','AdminLoginController');
Route::resource('administrator/userAuthentication', 'AdminLoginController@userAuthentication');

【问题讨论】:

  • 我可以看看你的路线吗?

标签: php laravel laravel-5


【解决方案1】:

如果不是模型,则为这个

public function login(Request $request)
{
   $email = $request->input('email');
   $password = $request->input('password');

   $user = DB::table('user')->where('email',$email)->first();

   if (Hash::check($password, $user->password)){
       $apiToken = base64_encode(Str::random(40));

       DB::table('user')->where('email',$email)->update([
            'api_token' => $apiToken
       ]);

       return response()->json([
        'success' => true,
        'message' => 'Login Success!',
        'data' => [
            'user' => $user,
            'api_token' => $apiToken
        ]
        ], 201);
   } else {
    return response()->json([
        'success' => false,
        'message' => 'Login  fail!',
    ], 400);
   }

}

【讨论】:

    【解决方案2】:

    第一次导入

    use Hash;
    

    然后用哈希编码你的密码

    Hash::make($input['password']);
    

    最后像这样检查你的密码和电子邮件

    $model = YourModelHere::where('email', $request->email)->first();
    if (Hash::check($request->password, $model->password, [])) {
        // success
    }
    //failed 
    

    【讨论】:

    • 试图获取非对象的属性。为什么?
    【解决方案3】:

    这样试试

    login.blade.php

    <!DOCTYPE html>
    <html>
    <head>
        <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
    </head>
    <body>
    <div class="container">
    <h3>Login Form</h3>  
    
    {!! Form::open(array('url' => 'login', 'method' => 'post')) !!}
    <div class="form-group">
        {!! Form::label('UserName') !!}
        {!! Form::text('username', null,
            array(
                  'class'=>'form-control',
                  'placeholder'=>'Your UserName')) !!}
    </div> 
    <div class="form-group">
        {!! Form::label('password') !!}
        {!! Form::text('password', null,
            array(
                  'class'=>'form-control',
                  'placeholder'=>'Your Password')) !!}
    </div>
    
    <div class="form-group">
        {!! Form::submit('Login',
          array('class'=>'btn btn-primary')) !!}
    </div>
    {!! Form::close() !!}
    
    </div>
    </body>
    </html>
    

    型号:-

    <?php namespace App;
    
    use Illuminate\Auth\Authenticatable;
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Auth\Passwords\CanResetPassword;
    use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
    use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
    
    class UserRegisters extends Model implements AuthenticatableContract, CanResetPasswordContract { 
        use Authenticatable, CanResetPassword;
        protected $table = 'userregisters';
        protected $fillable = ['user_name', 'password'];
    }
    ?>
    

    控制器:-

    <?php namespace App\Http\Controllers;
    use Input;
    use App\Http\Requests;
    use App\User;
    use App\UserRegisters;
    use App\UserProfiles;
    use Validator;
    use View;
    use Auth;
    use App\Http\Controllers\Redirect;
    use Session;
    use Hash;
    use DB;
    
    class UserRegisterController extends Controller
    {
        /**
         * Login a Registered Users.
         *
         */
        public function login(){
            $uname = Input::get('username');
            $password = Input::get('password');
                if (Auth::attempt(array('user_name' => $uname, 'password' => $password))){
                return "success";
                }
                else {        
                    return "Wrong Credentials";
                }
            }
        }
    }   
    

    路线:-

    Route::post('/login', 'UserRegisterController@login');
    

    迁移:-

    <?php
    
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Database\Migrations\Migration;
    
    class Userregisters extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('userregisters', function($table)
            {
                $table->increments('id');
                $table->string('first_name', 128);
                $table->string('last_name', 128);
                $table->string('user_name', 128);
                $table->string('password', 128);
                $table->string('email', 128);
                $table->timestamps();
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::drop('userregisters');
        }
    }
    

    如果有任何错误,请告诉我。

    【讨论】:

    • 我正在尝试使用您的代码并首先添加 html,当我点击页面时,我只得到这个 html &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;h3&gt;Login Form&lt;/h3&gt;
    • 您没有收到任何登录表单吗?
    • 没有。我只收到Login Form 文字:(
    • 你在使用 laravel 5 吗?并将此代码粘贴到您的 login.blade.php 文件中。
    • 是的,我使用的是 Laravel 5 版本,并且我已在 login.blade.php 文件中添加了您的 HTML 代码。
    【解决方案4】:

    尝试使用身份验证尝试

        $email=$request->email;
        $password=$request->password;
    
         if(Auth::attempt(['email'=>$email,'password'=>$password]))
           {
                    return redirect()->intended('admin/dashboard');
             }
    

    这将检查身份验证

    这里可以阅读官方文档

    http://laravel.com/docs/5.1/authentication#authenticating-users

    更新

    首先您需要创建名为users的表

    id|username|password|email|remember_token|created_at|updated_at
    

    然后在你的用户模型中

    protected $table = 'users';
    
      protected $fillable = ['username', 'email', 'password'];
    

    你想插入数据的列应该写入可填充数组,created_at和updated_at类型是mysql中的datatime,所以它会自动插入数据和时间

    在你的用户控制器中

     public function loginPost(Request $request)
            {
                $email=$request->email;
                $password=$request->password;
               if(Auth::attempt(['email'=>$email,'password'=>$password]))
               {
                    return redirect()->intended('admin/dashboard');
               }
    
               return Redirect::to('login');
            }
    

    请注意 auth::attempt 会自动对密码进行哈希处理,因此您无需对密码进行哈希处理。

    在登录认证前插入一条记录和Hash密码。

    $data=[];
    $data['email']=$request->email;
    $data['password']=Hash::make($password);
    User::create($data);
    

    更新 2

      public function insert()
        {
             $data=[];
        $data['email']=$request->email;
        $data['password']=Hash::make($password);
        AdminLoginModel::create($data);
        }
    

    【讨论】:

    • 嗨。感谢您的快速回复,但我不明白(我是 laravel 的新手)所以您可以提供有关我的问题的示例。 :)
    • 我必须在哪里存储这个??在我的控制器中??
    • 关于这个auth::attempt will automatically hash password so you no need to hash password我已经使用迁移创建了表然后我使用phpmyadmin添加了虚拟用户记录所以我没有哈希密码所以怎么做??
    • 仅在不使用注册登录时尝试验证。首先您使用 laravel 注册表单插入记录
    • $data=[]; $密码='1234'; $data['email']=example@gmail.com; $data['password']=Hash::make($password);用户::create($data);
    猜你喜欢
    • 1970-01-01
    • 2014-05-20
    • 2018-03-30
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 2017-01-02
    • 2020-06-18
    • 1970-01-01
    相关资源
    最近更新 更多