artesaos / defender Goto Github PK
View Code? Open in Web Editor NEWRoles & Permissions for Laravel
License: MIT License
Roles & Permissions for Laravel
License: MIT License
I'm attempting to find the roles that a user has.
I seem to have a little trouble doing this how would you go about this?
Is there a way to add multiple roles in the Blade @is()
extension?
Bom dia,
Estou tendo um problema que nao estou encontrando o motivo do mesmo.
quando eu executo o login ele me retorna o seguinte erro:
Whoops, looks like something went wrong.
BadMethodCallException in Builder.php line 2161:
Call to undefined method Illuminate\Database\Query\Builder::hasPermission()
Tem alguma ideia ?
ErrorException in Container.php line 1065:
Illegal offset type in isset or empty
in Container.php line 1065
at HandleExceptions->handleError('2', 'Illegal offset type in isset or empty', '/var/www/ommininew/vendor/laravel/framework/src/Illuminate/Container/Container.php', '1065', array('abstract' => object(Closure))) in Container.php line 1065
at Container->getAlias(object(Closure)) in Application.php line 668
at Application->make(object(Closure)) in AbstractDefenderMiddleware.php line 55
at AbstractDefenderMiddleware->forbiddenResponse() in NeedsPermissionMiddleware.php line 47
at NeedsPermissionMiddleware->handle(object(Request), object(Closure), 'scliente.alertas')
at call_user_func_array(array(object(NeedsPermissionMiddleware), 'handle'), array(object(Request), object(Closure), 'scliente.alertas')) in /var/www/ommininew/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php line 124
at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in Authenticate.php line 47
at Authenticate->handle(object(Request), object(Closure))
at call_user_func_array(array(object(Authenticate), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in GetUserFromToken.php line 37
at GetUserFromToken->handle(object(Request), object(Closure))
at call_user_func_array(array(object(GetUserFromToken), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Router.php line 710
at Router->runRouteWithinStack(object(Route), object(Request)) in Router.php line 675
at Router->dispatchToRoute(object(Request)) in Router.php line 635
at Router->dispatch(object(Request)) in Kernel.php line 236
at Kernel->Illuminate\Foundation\Http{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 139
at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in VerifyCsrfToken.php line 50
at VerifyCsrfToken->handle(object(Request), object(Closure))
at call_user_func_array(array(object(VerifyCsrfToken), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in ShareErrorsFromSession.php line 49
at ShareErrorsFromSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(ShareErrorsFromSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in StartSession.php line 62
at StartSession->handle(object(Request), object(Closure))
at call_user_func_array(array(object(StartSession), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 37
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure))
at call_user_func_array(array(object(AddQueuedCookiesToResponse), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in EncryptCookies.php line 59
at EncryptCookies->handle(object(Request), object(Closure))
at call_user_func_array(array(object(EncryptCookies), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline{closure}(object(Request)) in CheckForMaintenanceMode.php line 44
at CheckForMaintenanceMode->handle(object(Request), object(Closure))
at call_user_func_array(array(object(CheckForMaintenanceMode), 'handle'), array(object(Request), object(Closure))) in Pipeline.php line 124
at Pipeline->Illuminate\Pipeline{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 103
at Pipeline->then(object(Closure)) in Kernel.php line 122
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 87
at Kernel->handle(object(Request)) in index.php line 55
The registerRepositoryInterfaces()
function in DefenderServiceProvider
class is creating the Role
and Permission
singletons based on default package classes. This does not allows the repository pattern to provide expected behavior.
I'm using MongoDB and need to extend my models from a different class than default Eloquent\Model
. Below are the key parts of this logic:
protected function registerRepositoryInterfaces()
{
$this->app->singleton('defender.role', function ($app) {
return new EloquentRoleRepository($app, new Role());
});
...
$this->app->singleton('defender.permission', function ($app) {
return new EloquentPermissionRepository($app, new Permission());
});
...
$this->app->singleton('defender.user', function ($app) {
$userModel = $app['config']->get('defender.user_model');
return new EloquentUserRepository($app, $app->make($userModel));
});
...
}
The $userModel
creation follows the correct behavior, so should be the Role
and Permission
, but changing the logic throws the error:
Type error: Argument 2 passed to Artesaos\Defender\Repositories\Eloquent\EloquentRoleRepository::__construct() must be an instance of Artesaos\Defender\Role
So, I believe one strategy would be to refactor the Role
and Permission
classes into traits to be used by necessary classes of the app or by default flat classes of the package. This, of course, needs to be better studied. Or a simpler aproach by changing the signature of the __construct
functions of EloquentRoleRepository
and EloquentPermissionRepository
classes.
Using 'attachPermission' defender inserts a new register at table permission_role with field 'value' 0.
When 'detachPermission' is used, defender deletes the row for permission passed.
attachPermission should insert(if not exist) the register and set field 'value' = 1.
and for detachPermission should not delete the register, only set field 'value' to 0.
This way the field value will be used to determinate if have or not the permission.
Example situation:
A user can register customers, but it can only edit and update their own customers.
I deal with this situation very often.
With the introduction of Laravel offical ACL layer we need a way to remove the conflict with the official can @can and endcan.
Since this is a breaking change, we'll need a major release.
With the release of Laravel 5.2 and its new Auth configuration, we must find a way to support both Laravel 5.1 LTS and Laravel 5.2 configuration files.
Migrations estão sendo geradas com datas de 2015.
Em qualquer aplicação criada após a data das migrations do pacote, ocorrerá conflito (por exemplo, as migrations criam chaves estrangeiras utilizando a tabela user - mesmo em pacotes cuja primeira migração ainda não foi efetuada).
Seria possível utilizar um stub para criação dos arquivos de migração de acordo com a data?
[RuntimeException]
Error Output: PHP Fatal error: Class 'Artesaos\Defender\Providers\Defender
ServiceProvider' not found in E:\EasyPHP-DevServer-14.1VC11\data\localweb\g
amenivora\vendor\laravel\framework\src\Illuminate\Foundation\ProviderReposi
tory.php on line 146
i'm stuck in here :
// file START ommited
'providers' => [
// other providers ommited
\Artesaos\Defender\Providers\DefenderServiceProvider::class,
],
// file END ommited
Throw an exception when the user doesn't have permission.
An exception allows project specific customization using the laravel exception handler.
Add support to refresh / extend previous temporary permissions given to a role or a user.
Having problem while upgrading to 0.4.1 version.
The Documentation says to implement the interface Artesaos\Defender\Contracts\User on Users's class but there's no User.php file located in Contracts dir.
I have this error on console.
Interface 'Artesaos\Defender\Contracts\User' not found
$user->permissions = [
'permission.name' => true,
'permission2.name' => false
];
$user->save();
Eu criei as seguintes regras: superadmin, admin, user.
Coloquei 1 usuário com a regra de superadmin no usuário e mesmo assim, ao usar a rota desta forma:
Route::get('foo', ['middleware' => ['auth', 'needsRole'], 'can' => ['admin', 'patient'], function()
{
return 'Yes I am!';
}]);
Recebo o retorn
Desta forma:
Route::get('foo', ['middleware' => ['auth', 'needsRole:superadmin'], function() {
return 'Yes I am!';
}]);
Só funciona se eu passar apenas uma regra se eu adicionar um |admin, nem o primeiro nem as outras funcionam.
Add to support to give a user a temporary permission that expires after a certain time.
Just to be more simple, this proposal will prevent boring with large readme.md and possible confusions.
#53
Given that already exists a project for Laravel with the same name and similar goal, we new ideas to rename the project.
Please, comment with your suggestion.
[English]
I've tested the commands, that is very cool!
I would like to propose some improvements:
1 - One option to attach permission to a user, even if that permission already exists.
2 - A command to list permissions of the user like defender:permissions user
3 - A command to list roles of the user like defender:roles user
4 - Command to detach permissions for users
5 - Command to remove permissions
5 - Command to remove roles
6 - Command to add/remove temporary permissions
[Português]
Testei os comandos, muito show!
Gostaria de sugerir melhorias:
1 - Ter opção de poder adicionar um usuário a uma permissão existente, sem precisar criar;
2 - Ter como lista permissões do usuário algo como artisan defender:permissions user
3 - Ter como lista roles do usuário algo como artisan defender:roles user
4 - Poder remover permissões do usuário
5 - Poder apagar permissoes
6 - adicionar/remover permissões temporaria
7 - tudo que falei de permissões também para roles
Há alguma especificação diferente para a versão 5.1 do Laravel?
Boa tarde pessoal,
Percebi que na linha 98 do arquivo src\Defender\Providers\DefenderServiceProvider.php é definido o model de usuário levando em consideração o Model default do laravel, que fica em "App\User"... Minha pergunta é a seguinte, se por ventura o nome da minha aplicação for modificado ou até mesmo o namespace do Model de usuário for alterado, como devo proceder neste caso?
Hi.
Have you planned to add a method to filter users by role ?
e.g. : User::role('admin')->get() or User::role('guest')->get()
Migrations should be pushed right to migrations folder, even if user has its own path for it.
To fix this, change ServiceProvider to:
/**
* Publish migration file.
*/
private function publishMigrations()
{
$this->publishes([__DIR__.'/../../resources/migrations/' => database_path('database/migrations')], 'migrations');
}
(I'm busy to pull a request sorry :) )
Como usar o middleware "needsPermission" no controller para proteger métodos ao invés de usar nas routes? preciso especificar quais permissões necessárias determinados métodos precisam no controller, para os casos de rotas RESTful
on laravel 5.2, tried the examples, just printing text on on the page and not hiding anything.. oh and the template_helpers option in the config is set to true, am i missing anything?.. oh and not using multi-auth
Is it possible to use this to check if the current user is the owner of a resource? I am wanting to basically give the owner of a post the ability to edit it, while the moderators and admins implicitly have that ability through the plugin middleware.
I.e. an admin, a moderator, and the owner of a post have the ability to edit it.
index.blade.php
<ul>
@can('perm1')
<li>Menu 1</li>
@endcan
@can('perm2')
<li>Menu 2</li>
@endcan
@can('perm3')
<li>Menu 3</li>
@endcan
@can('perm4')
<li>Menu 4</li>
@endcan
</li>
Hello,
i have a problem with the @shield commands in my blade files... found that this line:
$this->app->afterResolving('blade.compiler', function (BladeCompiler $bladeCompiler) {
DefenderServiceProvider.php line: 118
is not firing... and the @shield lines get printed.
i have installed the latest 5.1.* update
Protect route or group, better for route::resource, based on its name and matching with user permissions.
Documentar pacote
How get $user->getAllPermisiion();
Bom dia galera. Eu tava implementando uns códigos aqui, tomando como base a arquitetura do defender, e me deparei com um detalhe…
no arquivo HasRole.php, nas funções hasRole e attachRole…
Enquanto o hasRole faz uma comparação da “string” role no banco, a função attachRole recebe um objeto Role como parâmetro.
O detalhe é que o attachRole utiliza a função hasRole. Porém, ao passar o parâmetro no hasRole, é passado o objeto, ao invés da string. Como resultado, vai sempre entrar no if, gerando duplicidade das roles.
Isso foi arquitetado propositalmente, ou seria um possível bug? Fiz um composer update, e na minha versão local. essa questão se encontra em:
arquivo HasRole.php
linha 51
exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'Gate' not found'
Tentei fazer o seguinte, mas não dá erro, apenas uma tela em branco. Não aparece nada nos logs para eu poder ajudar. O que eu estou fazendo errado?
`Route::group([ 'prefix' => 'admin', 'middleware' => ['auth', 'needsRole'], 'is' => 'admin' ], function() {
Route::get('/', ['as' => 'admin.painel', 'uses' => 'PainelController@index']);
});`
I noticed that it is not possible to use php artisan config:cache
when using Defender. The reason for this is the following lines in the config file, where a closure is used:
/*
* Forbidden callback
*/
'forbidden_callback' => function () {
throw new \Artesaos\Defender\Exceptions\ForbiddenException();
},
It seems to be bad practice to use closures in a config file. Is there a way to avoid using a closure here? I found a similar issue here: https://github.com/lucadegasperi/oauth2-server-laravel/issues/323.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.