Pedro
Pedro

Reputation: 1477

Permissions User and Roles

I need some advice, basically I have an application where users can register as normal customers, and inside the dashboard there is a option to register as an author for a list of categories. A customer can be many authors.

So basically after registering/subscribing as an author in the custom dashboard appears a box of his author(s) that he created and after clicking it goes to a specific dashboard with different menu, etc.

My only issue is when I start to create the permissions, for example I created a Middle-ware with the name of "author", so when someone try to access these pages it must be an author.

Middleware code:

public function handle($request, Closure $next)
    {

        if(isset($request->id) && auth()->check() && count(auth()->user()->authorsProfile) > 0){
            return $next($request);
        }
        return redirect('/dashboard')->with("error","Only Authors Allowed");
    }

example:

Route::group(['middleware' => ['auth','author']], function() {
//Dashboard
Route::get('authorsarea/{id}','AuthorController@dashboard')->name('author-dashboard');
});

So the second validation i need to make is inside the controllers, I need to check based on the ID if this an author id belongs to the customer/user.

example:

 public function dashboard($id)
    {

        $user = Auth::user();

        $user_author = Author::find($id);

        if($user_author->user_id != Auth::user()->id){
            return back()->with("error","This Author is not you");
        }

        //Go to dashboard
        return view('frontend.author.dashboard');
    }

I feel that pasting alwasy this code and checking if this author belongs to the user doesnt feel quite clean, is there a better way than pasting always this code in each page controller where I try to access a private area for authors?

Or even if you guys feel that there is a completely different way of doing all of this I'm open to it.

Upvotes: 0

Views: 99

Answers (1)

thefallen
thefallen

Reputation: 9749

You can make another middleware and have the check there, similar to the author middleware you have created. Something like this:

public function handle($request, Closure $next)
{
    $authorID = $request->route()->parameter('id');
    $user_author = Author::find($authorID);

    if($user_author->user_id != auth()->user()->id){
        return back()->with('error', 'This Author is not you');
    }

    return $next($request);
}

Upvotes: 2

Related Questions