Search code examples
phplaravellaravel-5laravel-authorization

Laravel 5.6 Policy is not working properly on remote server


I create a policy called LetterPolicy , this is the code

    namespace App\Policies;

    use App\Letter;
    use App\User;
    use Illuminate\Auth\Access\HandlesAuthorization;

    class LetterPolicy
    {
        use HandlesAuthorization;

        /**
         * Create a new policy instance.
         *
         * @return void
         */

        public function __construct()
        {
            //
        }

        public function update(User $user, Letter $letter)
        {
            return($user->id === $letter->user_id || $user->role_id===1 ) ;
        }
    }

and this is authserviceprovider

namespace App\Providers;

use App\Letter;
use App\Policies\LetterPolicy;
use App\Policies\UserPolicy;
use App\User;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
        User::class => UserPolicy::class,
        Letter::class => LetterPolicy::class,
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();
        //
    }
}

And in the following code I check for the user

class LetterController extends Controller
{
protected $user;
public function __construct()
{
    $this->middleware(function ($request, $next){
       $this->user = Auth::user();
        return $next($request);
    });

}
public function edit(Letter $letter)
{
    if($this->user->can('update', $letter)){           
       //edit
    }
    else
        abort('403', 'Access Denied');
}

The code is working well in localhost but on the remote server it reports the access denied error. I created this policy after deploying the site on the server so I create a route /clear-cache with code

    Route::get('/clear-cache', function() {
        $exitCode = \Illuminate\Support\Facades\Artisan::call('cache:clear');
    });

To clear the cache after creating the policy. But it still reports the 403 error. What is the problem?


Solution

  • I tried dd($this->user->id === $letter->user_id || $this->user->role_id===1 ); in the COntroller and it returned false. I tried dd($this->user->id == $letter->user_id || $this->user->role_id==1 ); and it was true. Now it works but I don't know why!!!