use of io.gravitee.rest.api.model.audit.AuditEntity in project gravitee-management-rest-api by gravitee-io.
the class AuditServiceImpl method getMetadata.
private Map<String, String> getMetadata(List<AuditEntity> content) {
Map<String, String> metadata = new HashMap<>();
for (AuditEntity auditEntity : content) {
// add user's display name
String metadataKey = "USER:" + auditEntity.getUser() + ":name";
try {
UserEntity user = userService.findById(auditEntity.getUser());
metadata.put(metadataKey, user.getDisplayName());
} catch (TechnicalManagementException e) {
LOGGER.error("Error finding metadata {}", auditEntity.getUser());
} catch (UserNotFoundException unfe) {
metadata.put(metadataKey, auditEntity.getUser());
}
if (Audit.AuditReferenceType.API.name().equals(auditEntity.getReferenceType())) {
metadataKey = "API:" + auditEntity.getReferenceId() + ":name";
if (!metadata.containsKey(metadataKey)) {
try {
Optional<Api> optApi = apiRepository.findById(auditEntity.getReferenceId());
if (optApi.isPresent()) {
metadata.put(metadataKey, optApi.get().getName());
}
} catch (TechnicalException e) {
LOGGER.error("Error finding metadata {}", metadataKey);
metadata.put(metadataKey, auditEntity.getReferenceId());
}
}
} else if (Audit.AuditReferenceType.APPLICATION.name().equals(auditEntity.getReferenceType())) {
metadataKey = "APPLICATION:" + auditEntity.getReferenceId() + ":name";
if (!metadata.containsKey(metadataKey)) {
try {
Optional<Application> optApp = applicationRepository.findById(auditEntity.getReferenceId());
if (optApp.isPresent()) {
metadata.put(metadataKey, optApp.get().getName());
}
} catch (TechnicalException e) {
LOGGER.error("Error finding metadata {}", metadataKey);
metadata.put(metadataKey, auditEntity.getReferenceId());
}
}
}
// add property metadata
String name;
if (auditEntity.getProperties() != null) {
for (Map.Entry<String, String> property : auditEntity.getProperties().entrySet()) {
metadataKey = new StringJoiner(":").add(property.getKey()).add(property.getValue()).add("name").toString();
if (!metadata.containsKey(metadataKey)) {
name = property.getValue();
try {
switch(Audit.AuditProperties.valueOf(property.getKey())) {
case API:
Optional<Api> optApi = apiRepository.findById(property.getValue());
if (optApi.isPresent()) {
name = optApi.get().getName();
}
break;
case APPLICATION:
Optional<Application> optApp = applicationRepository.findById(property.getValue());
if (optApp.isPresent()) {
name = optApp.get().getName();
}
break;
case PAGE:
Optional<io.gravitee.repository.management.model.Page> optPage = pageRepository.findById(property.getValue());
if (optPage.isPresent()) {
name = optPage.get().getName();
}
break;
case PLAN:
Optional<Plan> optPlan = planRepository.findById(property.getValue());
if (optPlan.isPresent()) {
name = optPlan.get().getName();
}
break;
case METADATA:
MetadataReferenceType refType = (Audit.AuditReferenceType.API.name().equals(auditEntity.getReferenceType())) ? MetadataReferenceType.API : (Audit.AuditReferenceType.APPLICATION.name().equals(auditEntity.getReferenceType())) ? MetadataReferenceType.APPLICATION : MetadataReferenceType.DEFAULT;
String refId = refType.equals(MetadataReferenceType.DEFAULT) ? getDefaultReferenceId() : auditEntity.getReferenceId();
Optional<Metadata> optMetadata = metadataRepository.findById(property.getValue(), refId, refType);
if (optMetadata.isPresent()) {
name = optMetadata.get().getName();
}
break;
case GROUP:
Optional<Group> optGroup = groupRepository.findById(property.getValue());
if (optGroup.isPresent()) {
name = optGroup.get().getName();
}
break;
case USER:
try {
UserEntity user = userService.findById(property.getValue());
name = user.getDisplayName();
} catch (UserNotFoundException unfe) {
name = property.getValue();
}
default:
break;
}
} catch (TechnicalException e) {
LOGGER.error("Error finding metadata {}", metadataKey);
name = property.getValue();
}
metadata.put(metadataKey, name);
}
}
}
}
return metadata;
}
use of io.gravitee.rest.api.model.audit.AuditEntity in project gravitee-management-rest-api by gravitee-io.
the class UserServiceImpl method resetPassword.
private void resetPassword(final String id, final String resetPageUrl) {
try {
LOGGER.debug("Resetting password of user id {}", id);
Optional<User> optionalUser = userRepository.findById(id);
if (!optionalUser.isPresent()) {
throw new UserNotFoundException(id);
}
final User user = optionalUser.get();
if (!isInternalUser(user)) {
throw new UserNotInternallyManagedException(id);
}
// do not perform this check if the request comes from an authenticated user (ie. admin or someone with right permission)
if (!isAuthenticated() || !canResetPassword()) {
AuditQuery query = new AuditQuery();
query.setEvents(Arrays.asList(User.AuditEvent.PASSWORD_RESET.name()));
query.setFrom(Instant.now().minus(1, ChronoUnit.HOURS).toEpochMilli());
query.setPage(1);
query.setSize(100);
MetadataPage<AuditEntity> events = auditService.search(query);
if (events != null) {
if (events.getContent().size() == 100) {
LOGGER.warn("More than 100 reset password received in less than 1 hour", user.getId());
}
Optional<AuditEntity> optReset = events.getContent().stream().filter(evt -> user.getId().equals(evt.getProperties().get(USER.name()))).findFirst();
if (optReset.isPresent()) {
LOGGER.warn("Multiple reset password received for user '{}' in less than 1 hour", user.getId());
throw new PasswordAlreadyResetException();
}
}
}
final Map<String, Object> params = getTokenRegistrationParams(convert(user, false), RESET_PASSWORD_PATH, RESET_PASSWORD, resetPageUrl);
notifierService.trigger(PortalHook.PASSWORD_RESET, params);
auditService.createOrganizationAuditLog(Collections.singletonMap(USER, user.getId()), User.AuditEvent.PASSWORD_RESET, new Date(), null, null);
emailService.sendAsyncEmailNotification(new EmailNotificationBuilder().to(user.getEmail()).template(EmailNotificationBuilder.EmailTemplate.TEMPLATES_FOR_ACTION_USER_PASSWORD_RESET).params(params).build(), GraviteeContext.getCurrentContext());
} catch (TechnicalException ex) {
final String message = "An error occurs while trying to reset password for user " + id;
LOGGER.error(message, ex);
throw new TechnicalManagementException(message, ex);
}
}
use of io.gravitee.rest.api.model.audit.AuditEntity in project gravitee-management-rest-api by gravitee-io.
the class AuditServiceImpl method search.
@Override
public MetadataPage<AuditEntity> search(AuditQuery query) {
Builder criteria = new Builder().from(query.getFrom()).to(query.getTo());
if (query.isCurrentEnvironmentLogsOnly()) {
criteria.references(Audit.AuditReferenceType.ENVIRONMENT, Collections.singletonList(GraviteeContext.getCurrentEnvironment()));
} else if (query.isCurrentOrganizationLogsOnly()) {
criteria.references(Audit.AuditReferenceType.ORGANIZATION, Collections.singletonList(GraviteeContext.getCurrentOrganization()));
} else if (query.getApiIds() != null && !query.getApiIds().isEmpty()) {
criteria.references(Audit.AuditReferenceType.API, query.getApiIds());
} else if (query.getApplicationIds() != null && !query.getApplicationIds().isEmpty()) {
criteria.references(Audit.AuditReferenceType.APPLICATION, query.getApplicationIds());
}
if (query.getEvents() != null && !query.getEvents().isEmpty()) {
criteria.events(query.getEvents());
}
Page<Audit> auditPage = auditRepository.search(criteria.build(), new PageableBuilder().pageNumber(query.getPage() - 1).pageSize(query.getSize()).build());
List<AuditEntity> content = auditPage.getContent().stream().map(this::convert).collect(Collectors.toList());
return new MetadataPage<>(content, query.getPage(), query.getSize(), auditPage.getTotalElements(), getMetadata(content));
}
use of io.gravitee.rest.api.model.audit.AuditEntity in project gravitee-management-rest-api by gravitee-io.
the class AuditServiceImpl method convert.
private AuditEntity convert(Audit audit) {
AuditEntity auditEntity = new AuditEntity();
auditEntity.setReferenceType(audit.getReferenceType().name());
auditEntity.setReferenceId(audit.getReferenceId());
auditEntity.setEvent(audit.getEvent());
auditEntity.setProperties(audit.getProperties());
auditEntity.setUser(audit.getUser());
auditEntity.setId(audit.getId());
auditEntity.setPatch(audit.getPatch());
auditEntity.setCreatedAt(audit.getCreatedAt());
return auditEntity;
}
use of io.gravitee.rest.api.model.audit.AuditEntity in project gravitee-management-rest-api by gravitee-io.
the class UserServiceTest method shouldResetPassword_auditEventNotMatch.
@Test
public void shouldResetPassword_auditEventNotMatch() throws TechnicalException {
when(environment.getProperty("jwt.secret")).thenReturn(JWT_SECRET);
when(environment.getProperty("user.creation.token.expire-after", Integer.class, DEFAULT_JWT_EMAIL_REGISTRATION_EXPIRE_AFTER)).thenReturn(1000);
when(user.getId()).thenReturn(USER_NAME);
when(user.getSource()).thenReturn("gravitee");
when(userRepository.findById(USER_NAME)).thenReturn(of(user));
MetadataPage mdPage = mock(MetadataPage.class);
AuditEntity entity1 = new AuditEntity();
entity1.setProperties(Collections.singletonMap("USER", "unknown"));
when(mdPage.getContent()).thenReturn(Arrays.asList(entity1));
when(auditService.search(argThat(arg -> arg.getEvents().contains(User.AuditEvent.PASSWORD_RESET.name())))).thenReturn(mdPage);
userService.resetPassword(USER_NAME);
verify(user, never()).setPassword(null);
verify(userRepository, never()).update(user);
verify(emailService).sendAsyncEmailNotification(any(), any());
}
Aggregations