autenticação laravel com driver eloquente em funções
Estou tentando autenticar usuários no meu aplicativo Laravel.
Estou com o seguinte problema:
usando driverbase de dados em auth.php: consigo efetuar login usando auth :: try () e auth :: check está funcionando, mas não consigo validar se o usuário logado tem uma determinada função.usando drivereloquente em auth.php: consigo efetuar login usando auth :: try (), mas auth :: check não está funcionando. No entanto, posso verificar o papel do usuário conectado.edit (question): Como posso corrigir isso para que, com apenas um dos drivers, eu possa fazer uma verificação completa da autenticação e da função?
Tabelas de migração:
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');
});
classe de modelo Usuário
<?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';
}
}
modelo Classe Função
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');
}
}
Função de autenticação HomeController
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();
}
}
}
USANDO O DRIVER DA BASE DE DADOS
- auth: try () e auth :: check estão funcionando
$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');
});
Isso falha com 'Chamada para o método indefinido Illuminate \ Auth \ GenericUser :: hasRole ()'
EDITAR obase de dados driver retorna um objeto GenericUser, e eu preciso do meu próprio objeto de usuário. Não sei onde eu posso mudar isso.
Solução alternativa: prefiro não usar isso, códigos e filtros feios (ou visualizações) não precisam fazer isso
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');}
});
USANDO O CONTROLADOR ELOQUENT
auth :: try () é bem-sucedidoauth :: check () falhanenhum erro no filtro