对角色侃侃而谈司机laravel认证 [英] laravel authentication with eloquent driver on roles

查看:248
本文介绍了对角色侃侃而谈司机laravel认证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的Laravel应用程序验证用户身份。

I am trying to authenticate users in my Laravel application.

我遇到以下问题:


  • 使用驱动程序的数据库在auth.php:我可以登录使用AUTH ::尝试()和Auth ::检查工作,但如果登录的用户拥有一个我无法验证一定的作用。

  • 使用驱动程序的雄辩在auth.php:我可以登录使用AUTH ::尝试(),但AUTH ::检查不工作。不过,我可以检查已登录用户的角色。

  • using driver database in auth.php: I can login using auth::attempt(), and auth::check is working, but I can't validate if the logged in user has a certain role.
  • using driver eloquent in auth.php: I can login using auth::attempt(), but auth::check is not working. I can however check the role of the logged in user.

编辑(问题):我怎样才能解决这个问题,使只有其中一个司机,我可以做一个完整的验证和角色检查

edit (question): How can I fix this so that with only one of the drivers, i can do a complete authentication and role check?

迁移表:

Schema::create('users', function ($table) {
        $table->increments('id');
        $table->integer('group_id')->unsigned();
        $table->string('name', 64);
        $table->string('email', 64)->unique();
        $table->string('username', 64)->unique();
        $table->string('phone', 13);
        $table->string('address', 64);
        $table->boolean('isresponsible');
        $table->string('password', 64);
        $table->rememberToken()->nullable();
    });
Schema::create('roles', function ($table) {
        $table->increments('id');
        $table->string('name');
    });

Schema::create('users_roles', function ($table) {
            $table->integer('user_id')->unsigned();
            $table->integer('role_id')->unsigned();
        }
    );
Schema::table('users_roles', function($table){
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        $table->foreign('role_id')->references('id')->on('roles');
    });

模型类用户

<?php
use Illuminate\Auth\UserTrait;`
use Illuminate\Auth\UserInterface;`
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {


use UserTrait, RemindableTrait;

/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'users';
public $timestamps = false;

public static $rules = ['name' => 'required', 'group_id' => 'required', 'email' => 'required', 'phone' => 'required'];
protected $fillable = ['name', 'group_id', 'email', 'phone', 'address', 'isresponsible', 'password'];

/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */
protected $hidden = array('password', 'remember_token');

public function group()
{
    return $this->belongsTo('Group');
}

public function userroles(){
    return $this->hasMany('Userrole');
}

public function roles()
{
    return $this->belongsToMany('Role', 'users_roles');
}

public function hasRole($check)
{
    dd($this->roles->toArray());
    return in_array($check, array_fetch($this->roles->toArray(), 'name'));
}

public function setBasicPassword($id){
    $user = User::find($id);
    $user->password = Hash::make('changeme');
    $user->save();
}

public function isValid()
{
    $validation = Validator::make($this->attributes, static::$rules);
    if ($validation->passes()) return true;
    $this->messages = $validation->messages();
    return false;
}


/**
 * Get the e-mail address where password reminders are sent.
 *
 * @return string
 */
public function getReminderEmail()
{
    // TODO: Implement getReminderEmail() method.
}

/**
 * Get the unique identifier for the user.
 *
 * @return mixed
 */
public function getAuthIdentifier()
{
    return $this->email;
}

/**
 * Get the password for the user.
 *
 * @return string
 */
public function getAuthPassword()
{
    return $this->password;
}

/**
 * Get the token value for the "remember me" session.
 *
 * @return string
 */
public function getRememberToken()
{
    return $this->remember_token;
}

public function setRememberToken($value)
{
    $this->remember_token = $value;
}

public function getRememberTokenName()
{
    return 'remember_token';
}
}

模式级角色
    

model Class Role

class Role extends Eloquent
{

protected $table = 'roles';
public $timestamps = false;

public static $rules = ['role_id' => 'required', 'name' => 'required'];
protected $fillable = ['name'];

/**
 * Get users with a certain role
 */
public function userroles()
{
    return $this->belongsToMany('User', 'users_roles');
}
}

HomeController的认证功能。

HomeController authentication function

 public function authenticate(){
    $rules = array(
        'email'    => 'required|email',
        'password' => 'required|alphaNum|min:3'
    );
    $validator = Validator::make(Input::all(), $rules);
    if ($validator->fails()) {
        return Redirect::to('login')
            ->withErrors($validator)
            ->withInput(Input::except('password'));
    } else {
        $userdata = array(
            'email' => Input::get('email'),
            'password' => Input::get('password')
        );
        if (Auth::attempt($userdata, true)) {
            return Redirect::action('HomeController@index');

        } else {
            return Redirect::action('HomeController@login')->withInput();
        }
    }
}

使用数据库驱动程序结果
- AUTH:尝试()和AUTH ::检查正在

USING THE DATABASE DRIVER
- auth:attempt() and auth::check are working

$this->beforeFilter('admin', ['only' => ['index']]); //filter in controller
//filter in filters;php
Route::filter('admin', function()
{
if(!Auth::check()) return Redirect::action('HomeController@index');
if(!Auth::user()->hasRole('admin')) return View::make('errors.401');
});

此过程出现调用未定义的方法照亮\\验证\\ GenericUser :: hasRole()

This fails with 'Call to undefined method Illuminate\Auth\GenericUser::hasRole()'

修改数据库驱动程序返回一个对象GenericUser,我需要我自己的用户对象。不知道在哪里我可以改变这一点。

EDIT The database driver return a GenericUser Object, and I need my own User object. Don't know where I can change this.

解决方法:我宁愿不使用的,丑陋的code和过滤器(或意见)不应该需要做到这一点。

Workaround:I'd rather not use this, ugly code and filters (or views) should not need to do this

Route::filter('admin', function()
{
    if(!Auth::check()) return Redirect::action('HomeController@index');
    $user = User::find((Auth::user()->id));
    if(!$user->hasRole('admin')){ return View::make('errors.401');}
});

使用雄辩DRIVER

USING THE ELOQUENT DRIVER


  • AUTH ::尝试()成功

  • AUTH ::检查()失败

  • 在过滤器没有错误

推荐答案

问题是你的 getAuthIdentifier的实现()。这种方法实际上应该返回的用于记录你的表的主键,而不是用户名。

The problem is your implementation of getAuthIdentifier(). This method should actually return the primary key of your table and not the username that's used for logging in.

所以,你应该是这样的:

So yours should look like this:

public function getAuthIdentifier(){
    return $this->id;
}

或实际,我建议你清理你的模式多一点,因为所有的 getSomeAuthStuff 方法中的两种特质的贯彻落实。

Or actually, I recommend you clean up your model a bit more since all of the getSomeAuthStuff methods are implemented in the two traits.

使用默认模型在github 作为基地并添加所有的自定义code(角色的方法,规则等)

Use the default model on github as a base and add all your custom code (roles methods, rules etc)

getAuthIdentifier()返回的值将被保存在session。结果
当使用检查()之后, retrieveById 将在名为 UserProvider 。和 EloquentUserProvider 做到这一点:

The value returned from getAuthIdentifier() will be stored in the session.
When using check() afterwards, retrieveById will be called on the UserProvider. And the EloquentUserProvider does this:

public function retrieveById($identifier)
{
    return $this->createModel()->newQuery()->find($identifier);
}

它使用找到()该搜索将其模型的主键(通常为 ID

It uses find() which searches for the model by it's primary key (usually id)

这篇关于对角色侃侃而谈司机laravel认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆