threeel
3 months ago

Policy always returns 403

Posted 3 months ago by threeel

Hello all i have been having an issue while testing an api endpoint

i have tried introducing a policy into the project and still trying to figure it out the policy is

    /**
     * Determine whether the user can view the lecture.
     *
     * @param \App\Models\User $user
     * @param \App\Models\Lecture $lecture
     * @return mixed
     */
    public function view(User $user,Lecture $lecture) {
        return true;
    }

the controller

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function index() {
        $this->authorize('view',Lecture::class);

        return ['data','meta'];
    }

Test

    public function test_that_lectures_are_viewed_publicly() {

        $response = $this->getJson($this->getEndpoint('lectures'));

        $response->assertOk();
        $response->assertJsonStructure(['data', 'meta']);

    }

public function getEndpoint($endpoint, $append = null) {

        if ($append) {
            return $this->endpoint_prefix . $endpoint . '/' . $append;
        }

        return $this->endpoint_prefix . $endpoint;

    }

i have registered the Policy in the Auth Service provider

    protected $policies = [
        // 'App\Model' => 'App\Policies\ModelPolicy',
        Course::class           => CoursePolicy::class,
        Lecture::class          => LecturePolicy::class,
        SubscriptionPlan::class => SubscriptionPlanPolicy::class,
    ];

 /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot() {

        $this->registerPolicies();

        Passport::routes();

        Gate::before(function($user, $ability) {

            return $user->isAdmin();
        });
    }

problem is that i always get a 403 if anyone could help would appreciate it. Laravel 5.8 is used

Please sign in or create an account to participate in this conversation.