I need some kind of @preFilter
(or, if it isnot possible than @postFilter
) to filter the results of my REST API. I can not use the preFilter
anotation, because I need to consider the user role. I have three different roles:
user
the normal user, who shold only access data which he ownsteamleader
this role should access all data of his teamadmin
who can access all data.
Because our database structure is really complex, it will be necessary, to access some other data, before I can decide if the user can access the requested data or parts of the requested data.
The snippet works only for the roles user
and admin
. For teamleader it will be more complex, then there will be a bunch of masterDataId
which have to be connect with or
.
Here is some pseudocode, hopefully its not to confusing:
public class RoleFilter {
DimensionAttributeValueRepository dimensionAttributeValueRepository;
public void doFilter(Collection<AllDatas> data) {
if (user.getRole() != "admin") {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
DimensionAttributeValue tmpValue = dimensionAttributeValueRepository.findByChrValue(auth.getUsername());
MasterData masterData = tmpValue.getMasterData();
data.filter(data.masterDataId == masterData.getMasterDataID());
}
}
}
Update: Example
Lets say I have two users, user A is a normal user with the role "user". User B is an admin with the role "admin".
There is a Database table, in which the userData
are stored. The table looks like the following.
| ID | username | name | email |
Both of them are sending a simple authenticated GET
request to /userData
.
Now my backend detects based on the authentication
header the users and add the roles.
Nwo depending on the role, the user A should only get an answere which contains his personal data, user B should get all data which are accessible though /userData
.
Response for user A:
{
"res":[
{
"id":1,
"username":"userA",
"name":"A",
"email":"userA@mail.com"
}
]
}
Response for user B:
{
"res":[
{
"id":1,
"username":"userA",
"name":"A",
"email":"userA@mail.com"
},
{
"id":2,
"username":"userB",
"name":"B",
"email":"userB@mail.com"
},
{
"id":3,
"username":"userC",
"name":"C",
"email":"userC@mail.com"
}
]
}