Should I place logic about authentication on the model? - laravel

I'm developing an application which involves authentication and files acl.
Now I want to write a method on the file model called "userCanAccess" which check if the given user/ the user role is in the file acl.
The code will be something along those lines:
public function userCanAccess($user = null) {
$user = is_null($user) ? auth()->user() : $user;
if($this->acl->users->contains($user)
|| $this->acl->roles->contains($user->role)) {
return true;
}
return false
}
Is it right to place this kind of logic on the model?

Laravel has a neat built-in bit of functionality called Policies.
You'd create a FilePolicy that applies to the File model:
php artisan make:policy FilePolicy --model=File
and in the resulting app/Policies/FilePolicy.php, you'll see some ready-to-edit existing policies, one of which is called view. Put your authorization logic here.
Once you've built that, you can apply the policy in a variety of ways, like controller functions, middleware on your routes, or directly within views using the #can Blade directive.
https://laravel.com/docs/5.8/authorization#authorizing-actions-using-policies

This should work just fine for me, but rather than bombing the model class, I would extract it to the trait.

You can make roles and permissions tables
User model:
public function roles()
{
return $this->belongsToMany(Role::class);
}
Role model:
public function users()
{
return $this->belongsToMany(User::class);
}
public function permissions()
{
return $this->belongsToMany(Permission::class);
}
Permission model:
public function roles()
{
return $this->belongsToMany(Role::class);
}
then in app/Providers/AuthServiceProvider you can make Gate like this:
public function boot()
{
$this->registerPolicies();
foreach ($this->getPermissions() as $permission) {
Gate::define($permission->name,function($user) use($permission){
return $user->hasRole($permission->roles);
});
}
}
private function getPermissions(){
return Permission::with('roles')->get();
}
at the end you can use ACL everywhere you want by just write Gate name like:show-comments or access-files or ....

Related

Laravel authorization policy not working on Show page

I have a laravel app using Policies to assign roles and permissions, i cant seem to access the show page and im not sure what im doing wrong?
If i set return true it still shows a 403 error as well, so im unsure where im going wrong here. The index page is accessable but the show page is not?
UserPolicy
public function viewAny(User $user)
{
if ($user->isSuperAdmin() || $user->hasPermissionTo(44, 'web')) {
return true;
}
return false;
}
public function view(User $user, User $model)
{
if ($user->isSuperAdmin() || $user->hasPermissionTo(44, 'web')) {
return true;
}
return false;
}
UserController
public function __construct()
{
$this->authorizeResource(User::class, 'user');
}
public function index()
{
$page_title = 'Users';
$page_description = 'User Profiles';
$users = User::all();
return view('pages.users.users.index', compact('page_title', 'page_description', 'users'));
}
public function create()
{
//
}
public function store(Request $request)
{
//
}
public function show($id)
{
$user = User::findOrFail($id);
$user_roles = $user->getRoleNames()->toArray();
return view('pages.users.users.show', compact('user', 'user_roles'));
}
Base on Authorize Resource and Resource Controller documentation.
You should run php artisan make:policy UserPolicy --model=User. This allows the policy to navigate within the model.
When you use the authorizeResource() function you should implement your condition in the middleware like:
// For Index
Route::get('/users', [UserController::class, 'index'])->middleware('can:viewAny,user');
// For View
Route::get('/users/{user}', [UserController::class, 'view'])->middleware('can:view,user');
or you can also use one policy for both view and index on your controller.
I had an issue with authorizeResource function.
I stuck on failed auth policy error:
This action is unauthorized.
The problem was that I named controller resource/request param with different name than its model class name.
F. ex. my model class name is Acknowledge , but I named param as timelineAcknowledge
Laravel writes in its documentation that
The authorizeResource method accepts the model's class name as its first argument, and the name of the route / request parameter that will contain the model's ID as its second argument
So the second argument had to be request parameter name.
// Here request param name is timelineAcknowledge
public function show(Acknowledge $timelineAcknowledge)
{
return $timelineAcknowledge->toArray();
}
// So I used this naming here also
public function __construct()
{
$this->authorizeResource(Acknowledge::class, 'timelineAcknowledge');
}
Solution was to name request param to the same name as its model class name.
Fixed code example
// I changed param name to the same as its model name
public function show(Acknowledge $acknowledge)
{
return $acknowledge->toArray();
}
// Changed here also
public function __construct()
{
$this->authorizeResource(Acknowledge::class, 'acknowledge');
}
I looked over Laravel policy auth code and I saw that the code actually expects the name to be as the model class name, but I couldn't find it anywhere mentioned in Laravel docs.
Of course in most of the cases request param name is the same as model class name, but I had a different case.
Hope it might help for someone.

Adding custom where clause to AuthenticatesUser Trait Laravel

We have decided to use Laravel for a project as a test run for future frameworks and are really enjoying it. There is one issue we are having though.
We use the trait Illuminate\Foundation\Auth\AuthenticatesUsers which handles user authentication. It works well. However, we have a column in the database called userstatus which could be a 0 or a 1.
How do we inject this where clause into the Illuminate\Foundation\Auth\AuthenticatesUsers trait?
I was thinking maybe something here (in my LoginController):
public function authenticated($request , $user){
//if $user->userstatus != 1 logout and redirect to start page
}
But I dont know how to logout (im looking into that now) .
your logic is right, you should redefine login and authenticated methods within LoginController.
your methods should be like below:
this method should be within your LoginController.php:
class LoginController extends Controller
{
use AuthenticatesUsers {
login as public loginParent;
}
protected function login(Request $request){
$default = '/';
$user = User::where('email', $request->get('email'))->NotActive->first();
if($user){
return redirect()->intended($default);
}
return $this->loginParent($request);
}
protected function authenticated(Request $request, $user)
{
if($user->not_active) {
$this->logout($request);
}
}
}
then we should create ScopeNotActive method within User.php Model as Local Scope:
//User.php
public function ScopeNotActive($query){
return $query->where('userStatus', '!=', 1);
}
and a Mutator to check if the user is not active:
// User.php
public function getNotActiveAttribute(){
return $this->userStatus != 1;
}

Laravel : gates and policies vs normal function

I did that to test if an user can access to a resource:
I created a function in a "global" service:
class IsAuthorizedToRessource{
public function isAuthorizedToUser($connectedUserId, $userId){
// return true or false
}
}
In my controller I call this service:
protected $isAuthorizedToRessource;
public function __construct()
{
$this->isAuthorizedToRessource = new IsAuthorizedToRessource();
}
public function show(Request $request,$id)
{
if (! $this->isAuthorizedToRessource->isAuthorizedToUser(Auth::user()->id, $id)){
return response()->json("not authorized to this ressource", 403);
}
//....
}
All is running fine. But I saw in the Laravel documentation that there is the "gates" and "policies". Despite of the documentation, I don't understand these concepts. And I have tried a lot of things without success.
My question: is my current technique sustainable? or should I make the effort to use these techniques "gates" and "policies"?
How can I use these techniques? (I specify: I do not use a model - I saw there is a "with" and a "without" model technique).

Implicit route model binding 401 unauthorized

I have a super simple learning app. My Laravel version is 5.5.13. A User can create a Pet. I am implicitly throwing 404 but I need to also implicitly throw 401 is this possible?
Details on setup:
Pet model:
class Pet extends Model
{
protected $fillable = ['name', 'user_id'];
public function user()
{
return $this->belongsTo('App\User');
}
}
And User model giving the relationship hasMany:
class User extends Authenticatable
{
use Notifiable;
// ... some stuff hidden for brevity
public function pets()
{
return $this->hasMany('App\Pet');
}
}
I used implicit route model binding to throw 404 status when the id is not found like this:
Route::group(['middleware' => 'auth:api'], function() {
Route::get('pets', 'PetController#index');
Route::get('pets/{pet}', 'PetController#show');
Route::post('pets', 'PetController#store');
Route::put('pets/{pet}', 'PetController#update');
Route::delete('pets/{pet}', 'PetController#delete');
});
Notice the {pet} instead of {id}.
However I also want to throw 401 unauthorized status if the $pet->user_id does not equal Auth::guard('api')->user()->id. Is this implicitly possible?
If not possible, may you please show me how to explicitly do this in the controller? I was doing this, but I don't think it's the recommended way is it?
public function show(Pet $pet)
{
if ($pet->user_id != Auth::guard('api')->user()->id) {
return response()->json(['message'=>'Not authenticated to view this pet'], 401);
}
return $pet;
}
The more Laravel centric way todo this is using policies.
Then for each action you want to authorize you register them inside your policy. Your show method would then become:
public function show(Pet $pet)
{
$this->authorize('show', $pet);
return $pet;
}
So your steps would be:
Create a new Policy for Pets
Add the actions you want to authorize
Register the policy in the AuthServiceProvider
Use the authorize
call inside your Controller action

Many to Many to One relationship

I've got four tables Users[user_id] - role_user[user_id,role_id] - Roles[role_id] - Permissions[role_id]. A User could have many Roles, while the Role has many Permissions. So, a Permission has one Role, while a Role belongs to many Users.
// User.php ...
class User extends Model
{
public function roles()
{
return $this->belongsToMany('Role');
}
}
// Roles.php
class Role extends Model
{
public function users()
{
return $this->belongsToMany('App\User');
}
public function permissions()
{
return $this->hasMany('Permission');
}
}
// Permission.php
class Permission extends Model
{
public function role()
{
return $this->belongsTo('Role');
}
}
I guess the real question is; can you chain relationship methods, like: App\User::find(1)->roles->permissions; I don't think you can because the ->roles returns a Collection and not an eloquent model, so the permissions method doesn't exists off roles.
Is there another way I can get the collection of permissions for all roles for a given use, preferably with a single line?
I haven't tested it, but I think this will work or work with very small twick. Add this function in your User Model.
public function getPermission($id){
$roles = Roles::where('user_id','=', id)->get();
$permissions = array();
foreach($roles as $role){
array_push($permissions, $role->permissions);
}
return $permissions;
}
and access as $user->getPermission($user->id);. This might not be the best solution, but it should solve the problem.
UPDATED CODE
You can use accessor like the example bellow and this will return a permission collection. Use this function in your User Model
public function getPermissions($value){
$role_ids = Roles::where('user_id','=', $value)
->select(array('permission_id'))
->toArray();
return Permission::find($role_ids);
}
and access it like $permissions = App\User::find(1)->permissions;. I believe this will work as you expected.

Resources