I am using REST api with JPA, and getting the user information in the header section .
For audit purpose need to save the user detail with each request.
How to directly get the user info at JPA level (@Prepersist and @PreUpdate hooks) from rest header.
I don't want to pass the details though service layer
Is there any generic way to do it ?
Note-I am not using spring.
Thanks in advance.
I had the similar problem with spring framework. Following idea may help you.
Create AppContext using ThreadLocal
public class AppContext {
private static final ThreadLocal<User> currentUser = new ThreadLocal<>();
public static void setCurrentUser(String tenant) {
currentUser.set(tenant);
}
public static String getCurrentUser() {
return currentUser.get();
}
public static void clear() {
currentUser.remove();
}
}
Use filter or similar to get user from http header and set to the AppContext
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
// Your code to extract user info from header
// Build user object and set to the AppContext
AppContext.setCurrentUser(user);
//doFilter
chain.doFilter(httpRequest, response);
}
Use AppContext on the repository. It should available on request scope.
@PrePersist
public void onPrePersist() {
if(AppContext.getCurrentUser() != null){
this.user = AppContext.getCurrentUser();
}
}
}