private Response processUser(HttpServletRequest request, Provider provider, String id,
String displayName) throws JOSEException, ParseException {
Optional<User> user = dao.findByProvider(provider, id);
// Step 3a. If user is already signed in then link accounts.
User userToSave;
String authHeader = request.getHeader(AuthUtils.AUTH_HEADER_KEY);
if (StringUtils.isNotBlank(authHeader)) {
if (user.isPresent()) {
return Response
.status(Status.CONFLICT)
.entity(new ErrorMessage(String.format(CONFLICT_MSG, provider.capitalize())))
.build();
}
String subject = AuthUtils.getSubject(authHeader);
Optional<User> foundUser = dao.findById(Long.parseLong(subject));
if (!foundUser.isPresent()) {
return Response.status(Status.NOT_FOUND).entity(new ErrorMessage(NOT_FOUND_MSG))
.build();
}
userToSave = foundUser.get();
userToSave.setProviderId(provider, id);
if (userToSave.getDisplayName() == null) {
userToSave.setDisplayName(displayName);
}
userToSave = dao.save(userToSave);
} else {
// Step 3b. Create a new user account or return an existing one.
if (user.isPresent()) {
userToSave = user.get();
} else {
userToSave = new User();
userToSave.setProviderId(provider, id);
userToSave.setDisplayName(displayName);
userToSave = dao.save(userToSave);
}
}
Token token = AuthUtils.createToken(request.getRemoteHost(), userToSave.getId());
return Response.ok().entity(token).build();
}