0
votes

I use Spring Data Rest with Spring Data Mongo.

I have a rather simple REST API which looks similar to this:

public class User {
        String id;
        String email;
        String password;
        List<String> roles;
}

public class UserData {
        String data;
        User user;
}

@PreAuthorize("hasRole('ROLE_USER')")
public interface QueryTemplateRepository extends
        MongoRepository<UserData, String> {
}

What I want now is that users can only access their data and if they create/edit data it will be linked to their account.

Do I have to get rid of the MongoRepository and write everything myself? Is there some kind of interceptor or filter where I can do this?

I will want to create more REST APIs that are restricted to the user's data, so it would be great if there was some generic solution to this problem.

2

2 Answers

1
votes

You can use features of AbstractMongoEventListener, it has convinient methods for your needs:

void onAfterConvert(DBObject dbo, E source)
void onAfterSave(E source, DBObject dbo)
void onBeforeSave(E source, DBObject dbo)
void onBeforeConvert(E source)
void onAfterLoad(DBObject dbo)
void onApplicationEvent(MongoMappingEvent event)

0
votes

I think this is a concern you could deal with in your service layer through aspects as a generic approach. AbstractMongoEventListener is a good example of an applied aspect technique.

Because you are dealing with spring-data-rest, no service layer is available unless you wrap it and expose the repository via a Controller.

There is nothing in REST standard regarding allowing modification/deletion of entities only by the creator of it.