How to allow only specific User to update record in database?

Viewed 40

For example i have a Car class

@Table(name = "car")
@Entity
public class Car extends BaseEntity {
    @Enumerated(EnumType.STRING)
    private EColor color;

    private Driver driver;
}

And Driver class

@Entity
@Table(name = "driver")
public class Driver extends Person{
    private Long drivingExperience;
    private Set<Car> cars;
}

The driver can have multiple cars. What I want to check is whether the user is the owner of this car. And if not - restrict updating of car properties. Now I came up with this solution:

  public Car updateCar(Long carId, PartialUpdateCar partialUpdateCar, Long ownerId) {
        Car car = carRepository.getCar(carId);
        if(!ownerId.equals(car.getDriverId())){
            throw new AccessDeniedException("UNAUTHORIZED");
        }
        carMapper.update(car, partialUpdateCar);
        return carRepository.save(car);
    }

There is @PreAuthorize annotation that has nice queries to check whether user has a certain role or compare fields but I can't use it because I fetch objects to compare inside my service layer. How to avoid passing the current user id as a parameter to the service layer to check whether the user is the owner of a car?

0 Answers
Related