Laravel 5 - 如何检查用户名和密码是否与表格匹配?

8
我已经在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');
    }
}

数据库结构

enter image description here

enter image description here

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 (model)

    <?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');

我能看一下你的路由吗? - aldrin27
4个回答

6
尝试使用“auth attempt”。
    $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'];

无论你想要在哪一列插入数据,都应该写在可填充的数组中。在MySQL中,created_at和updated_at类型为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将自动哈希密码,因此您不需要哈希密码。
在登录验证之前,插入一条记录并哈希密码。
$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);
    }

我必须把这个存储在哪里??在我的控制器中吗?? - Mr.Happy
关于 auth::attempt将自动哈希密码,因此您无需哈希密码,我使用迁移创建了表,然后使用phpmyadmin添加了一个虚拟用户记录,因此我没有哈希密码,那该怎么办呢? - Mr.Happy
只有在不使用注册时才进行身份验证尝试。首先,您需要使用Laravel注册表单插入记录。 - Vision Coderz
嗨。我已经更新了我的问题,并加入了你的答案,所以你能否请检查一下,因为它没有重定向。 - Mr.Happy
你能够发布插入记录并删除输出"Done"的代码吗? die; - Vision Coderz
显示剩余6条评论

3

这是非模型内容

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);
   }

}

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

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


你没有收到任何登录表单吗? - RaMeSh
不,我只得到“登录表单”文本 :( - Mr.Happy
你正在使用Laravel 5吗?将这段代码粘贴到你的login.blade.php文件中。 - RaMeSh
转到您的 app\config 文件夹,只需更改 Illuminate\View\ViewServiceProvider::class 中的 app.php 文件, Illuminate\Html\HtmlServiceProvider::class, - RaMeSh
自动加载的服务提供者将这些代码行添加上去 Illuminate\View\ViewServiceProvider::class, Illuminate\Html\HtmlServiceProvider::class - RaMeSh
显示剩余23条评论

2
最初的回答
需要先进行导入操作。
use Hash;

then encode your password with Hash

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

finally check your password and email like this

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

尝试获取非对象的属性。为什么? - Sead Lab

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接