kodeine/laravel-acl

Request for full document with controller and Models.

kushal555 opened this issue · 1 comments

@kodeine I really want to thanks to your bottom of my heart for making such a great library. Really I have all things which I expect.
If you can explain its document little bit more then it really useful for all newbie Laravel Developers like me.
What I face problem know that how can I integrate into my controller and here any need to create a model for role and permission.
so Please also mention a little example that contains models and controllers.

Again thank you very much.

@kushal555
Have you checked out wiki?
Here is my own step-by-step basic setup for you using laravel-acl package together with Laravel 5.3.

I have added use HasRole trait to the User model class.
Model: app/User.php

class User extends Authenticatable
{
    use HasRole;
    // ... Other fields and methods for your User model
}

Let's add three simple functions to check user permissions and role.
Helper: app/Helpers/general.php

/**
 * Return true if user have permission.
 * @param        $permission
 * @return bool
 */
function has_permission($permission)
{
    if (auth()->guest()) {
        return false;
    }
    $user = auth()->user();
    if ( ! $user->can($permission)) {
        return false;
    }

    return true;
}

/**
 * Show 403 error page if permission check fails.
 * @param $permission
 */
function require_permission($permission)
{
    $error_message = 'You don\'t have access to this resource';
    abort_if(auth()->guest(), 403, $error_message);
    $user = auth()->user();

    $permission_description = trans("permissions.{$permission}");
    $error_message          = empty($permission_description) ? $error_message : "You don't have this permission: $permission_description";

    abort_unless($user->can($permission), 403, $error_message);
}

/**
 * Check if current user is a Global admin.
 * @return bool
 */
function is_admin()
{
    if (auth()->guest()) {
        return false;
    }
    $user = auth()->user();
    return $user->hasRole(ROLE_ADMIN);
}

To make it DRY and organized we will use middleware to filter out any requests from non-admin users for admin-only routes:
routes/web.php

Route::group([ 'middleware' => [ 'auth', 'auth.admin' ] ], function () {
    Route::get('admin/dashboard', 'Admin@dashboard')->name('admin.dashboard.get');
});

Middleware class for checking user role.
app/Http/Middleware/AuthorizeAdmin.php

<?php
namespace App\Http\Middleware;

use Closure;
class AuthorizeAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (is_admin()) {
            return $next($request);
        }
        abort(403, 'Forbidden action.');
    }
}

Middleware class needs to be included in routeMiddleware array so we can use it in routes/web.php.
app/Http/Kernel.php

/**
 * The application's route middleware.
 *
 * These middleware may be assigned to groups or used individually.
 *
 * @var array
 */
protected $routeMiddleware = [
    // ...
    'auth.admin' => \App\Http\Middleware\AuthorizeAdmin::class,
    // ...
];

We can use Blade extension in templates like that:
resources/views/layouts/parts/menu.blade.php

...
@role(ROLE_ADMIN)
  <li class="text-white">|</li>
  <li><a href="{{ route('admin.dashboard.get') }}" class="text-white">Admin Dashboard</a></li>
@endrole
...
@permission('view.users')
  @include('users.list')
@endpermission
...

If you have permissions configured for your role, you can use it like this in controllers:

example code that sends invite to user if current user have permissions to do that

/**
 * @param $id
 * @return \Illuminate\Http\JsonResponse
 */
public function inviteSend($id)
{
    $organization = Organization::find($id);
    abort_if(empty($organization), 404, 'Organization Not Found');
    require_permission('send.invites.organization');

    $request_data                    = request()->all();
    $request_data['organization_id'] = $organization->id;
    $validate                        = OrganizationInvite::send($request_data);
    if ($validate !== true && $validate instanceof Validator) {
        $errors = $validate->getMessageBag()->toArray();

        return util_response_json([
            'status' => RESPONSE_STATUS_ERROR,
            'error'  => 'Couldn\'t Send Invite',
            'data'   => $errors,
        ]);
    }

    return util_response_json([
        'status'  => RESPONSE_STATUS_OK,
        'message' => 'Invite Sent Successfully.',
    ]);

}

Feel free to ask any questions.
To @kodeine:
If you'll find this example useful please let me know, I'll add it to the wiki to new "Examples" section.