Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Api-Platform, how to automatically add the authorized user as a resource owner when creating it?

How to automatically add the currently authorized user to a resource upon creation (POST).

I am using JWT authentication, and /api/ routes are protected from unauthorized users. I want to set it up so that when an authenticated user creates a new resource (i.e. by sending a POST request to /api/articles) the newly created Article resource is related to the authenticated user.

I'm currently using a custom EventSubscriber per resource type to add the user from token storage.

Here's the gist for the subscriber base class: https://gist.github.com/dsuurlant/5988f90e757b41454ce52050fd502273

And the entity subscriber that extends it: https://gist.github.com/dsuurlant/a8af7e6922679f45b818ec4ddad36286

However this does not work if for example, the entity constructor requires the user as a parameter.

E.g.

class Book {

    public User $owner;
    public string $name;

    public class __construct(User $user, string $name) {
        $this->owner = $user;
        $this->name  = $name;
    }
}

How to automatically inject the authorized user upon entity creation?

like image 384
Danielle Suurlant Avatar asked Jan 01 '18 18:01

Danielle Suurlant


1 Answers

For the time being, I'm using DTOs and data transformers.

The main disadvantage is having to create a new DTO for each resource where this behaviour is required.

As a simple example, I'm doing something like this:

class BootDtoTransformer implements DataTransformerInterface
{

    private Security $security;

    public function __construct(Security $security)
    {
        $this->security = $security;
    }

    public function transform($data, string $to, array $context = [])
    {

        $owner = $this->security->getUser();

        return $new Book($owner, $data->name);;
    }

    public function supportsTransformation($data, string $to, array $context = []): bool
    {

        if ($data instanceof Book) {
            return false;
        }

        return Book::class === $to && null !== ($context['input']['class'] ?? null);
    }

}

This logically works only for a single resource. To have a generic transformer for multiple resources I end up using some interfaces to set apart the "owneable" resources, and a bit of reflection to instantiate each class.

I would have thought this were doable during the denormalization phase, but I couldn't get it work.

like image 93
yivi Avatar answered Oct 27 '22 15:10

yivi