Matt McManis
Matt McManis

Reputation: 4675

Check if Backend User belongs to Group with OctoberCMS Laravel?

I'm using OctoberCMS based on Laravel.

I have a backend user, Matt in Groups owners, administrators.

How do I check if user belongs to a specific group to allow authentication?

I was told I need to pass a Group Object, but I don't know what that is.

use Auth;
use BackendAuth;
use Backend\Models\User;

if (BackendAuth::check()) {

    // get current backend user
    $backend_user = BackendAuth::getUser();

    // get current backend user's groups
    $backend_user_groups = Backend::getUser()->groups;

    // authenticate
    if ($backend_user->inGroup('administrators') {

    }
}

Error

public function inGroup($group)
Call to a member function getKey() on string

Another way I've tried

if (User::inGroup('administrators') {

} 

Error

Non-static method October\Rain\Auth\Models\User::inGroup() should not be called statically

Docs

https://octobercms.com/docs/backend/users

https://github.com/octobercms/library/blob/master/src/Auth/Models/User.php

Upvotes: 2

Views: 1664

Answers (3)

Raja Khoury
Raja Khoury

Reputation: 3195

I think first you should try to understand the errors before doing the permissions part

public function inGroup($group)

Call to a member function getKey() on string

Did you look what does the inGroup() function do ? This method does not expect a string as a parameter

Here's the complete function :

 /**
 * See if the user is in the given group.
 * @param Group $group
 * @return bool
 */
public function inGroup($group)
{
    foreach ($this->getGroups() as $_group) {
        if ($_group->getKey() == $group->getKey()) <<== Call to a member function getKey() on string
        { 
            return true;
        }
    }

    return false;
}

As regards the second error

Non-static method October\Rain\Auth\Models\User::inGroup() should not be called statically

You should initialize non-static methods like this :

(new User)->someMethod() 

Upvotes: 1

Meysam
Meysam

Reputation: 18137

You can also extend the backend user model and add a helper method to it to check roles. Do the following in the boot() method of your plugin:

use Backend\Models\User as BackendUser;

public function boot()
{
    BackendUser::extend(function($model) {

        $model->addDynamicMethod('hasRole', function($role) use ($model) {
            return $model->groups()->whereName($role)->exists();
        });

        $model->addDynamicMethod('isAdmin', function() use ($model) {
            return $model->hasRole('administrators');
        });

    }
}

Upvotes: 1

dragontree
dragontree

Reputation: 1799

There could be some helper functions for this but you can also use this:

$backend_user->groups()->whereName('administrators')->exists();

Upvotes: 5

Related Questions