use of io.gravitee.am.model.ReferenceType in project gravitee-access-management by gravitee-io.
the class JdbcOrganizationUserRepository method search.
@Override
public Single<Page<User>> search(ReferenceType referenceType, String referenceId, FilterCriteria criteria, int page, int size) {
LOGGER.debug("search({}, {}, {}, {}, {})", referenceType, referenceId, criteria, page, size);
StringBuilder queryBuilder = new StringBuilder();
queryBuilder.append(" FROM organization_users WHERE reference_id = :refId AND reference_type = :refType AND ");
ScimUserSearch search = this.databaseDialectHelper.prepareScimSearchUserQuery(queryBuilder, criteria, page, size);
// execute query
org.springframework.r2dbc.core.DatabaseClient.GenericExecuteSpec executeSelect = template.getDatabaseClient().sql(search.getSelectQuery()).bind("refType", referenceType.name()).bind("refId", referenceId);
for (Map.Entry<String, Object> entry : search.getBinding().entrySet()) {
executeSelect = executeSelect.bind(entry.getKey(), entry.getValue());
}
Flux<JdbcOrganizationUser> userFlux = executeSelect.map(row -> rowMapper.read(JdbcOrganizationUser.class, row)).all();
// execute count to provide total in the Page
org.springframework.r2dbc.core.DatabaseClient.GenericExecuteSpec executeCount = template.getDatabaseClient().sql(search.getCountQuery());
executeCount = executeCount.bind("refType", referenceType.name()).bind("refId", referenceId);
for (Map.Entry<String, Object> entry : search.getBinding().entrySet()) {
executeCount = executeCount.bind(entry.getKey(), entry.getValue());
}
Mono<Long> userCount = executeCount.map(row -> row.get(0, Long.class)).first();
return fluxToFlowable(userFlux).map(this::toEntity).flatMap(user -> completeUser(user).toFlowable()).toList().flatMap(list -> monoToSingle(userCount).map(total -> new Page<User>(list, page, total)));
}
use of io.gravitee.am.model.ReferenceType in project gravitee-access-management by gravitee-io.
the class JdbcRoleRepository method search.
@Override
public Single<Page<Role>> search(ReferenceType referenceType, String referenceId, String query, int page, int size) {
LOGGER.debug("search({}, {}, {}, {}, {})", referenceType, referenceId, query, page, size);
boolean wildcardSearch = query.contains("*");
String wildcardValue = query.replaceAll("\\*+", "%");
String search = this.databaseDialectHelper.buildSearchRoleQuery(wildcardSearch, page, size);
String count = this.databaseDialectHelper.buildCountRoleQuery(wildcardSearch);
return fluxToFlowable(template.getDatabaseClient().sql(search).bind("value", wildcardSearch ? wildcardValue : query).bind("refId", referenceId).bind("refType", referenceType.name()).map(row -> rowMapper.read(JdbcRole.class, row)).all()).map(this::toEntity).flatMap(role -> completeWithScopes(Maybe.just(role), role.getId()).toFlowable()).toList().flatMap(data -> monoToSingle(template.getDatabaseClient().sql(count).bind("value", wildcardSearch ? wildcardValue : query).bind("refId", referenceId).bind("refType", referenceType.name()).map(row -> row.get(0, Long.class)).first()).map(total -> new Page<Role>(data, page, total)));
}
use of io.gravitee.am.model.ReferenceType in project gravitee-access-management by gravitee-io.
the class AuthenticationServiceImpl method onAuthenticationSuccess.
@Override
public User onAuthenticationSuccess(Authentication auth) {
final DefaultUser principal = (DefaultUser) auth.getPrincipal();
final EndUserAuthentication authentication = new EndUserAuthentication(principal.getUsername(), null, new SimpleAuthenticationContext());
Map<String, String> details = auth.getDetails() == null ? new HashMap<>() : new HashMap<>((Map<String, String>) auth.getDetails());
details.putIfAbsent(Claims.organization, Organization.DEFAULT);
String organizationId = details.get(Claims.organization);
final String source = details.get(SOURCE);
io.gravitee.am.model.User endUser = userService.findByExternalIdAndSource(ReferenceType.ORGANIZATION, organizationId, principal.getId(), source).switchIfEmpty(Maybe.defer(() -> userService.findByUsernameAndSource(ReferenceType.ORGANIZATION, organizationId, principal.getUsername(), source))).switchIfEmpty(Maybe.error(new UserNotFoundException(principal.getUsername()))).flatMapSingle(existingUser -> {
existingUser.setSource(details.get(SOURCE));
existingUser.setLoggedAt(new Date());
existingUser.setLoginsCount(existingUser.getLoginsCount() + 1);
if (existingUser.getAdditionalInformation() != null) {
existingUser.getAdditionalInformation().putAll(principal.getAdditionalInformation());
} else {
existingUser.setAdditionalInformation(new HashMap<>(principal.getAdditionalInformation()));
}
return userService.update(existingUser).flatMap(user -> updateRoles(principal, existingUser).andThen(Single.just(user)));
}).onErrorResumeNext(ex -> {
if (ex instanceof UserNotFoundException) {
final io.gravitee.am.model.User newUser = new io.gravitee.am.model.User();
newUser.setInternal(false);
newUser.setExternalId(principal.getId());
newUser.setUsername(principal.getUsername());
newUser.setSource(details.get(SOURCE));
newUser.setReferenceType(ReferenceType.ORGANIZATION);
newUser.setReferenceId(organizationId);
newUser.setLoggedAt(new Date());
newUser.setLoginsCount(1L);
newUser.setAdditionalInformation(principal.getAdditionalInformation());
return userService.create(newUser).flatMap(user -> userService.setRoles(principal, user).andThen(Single.just(user)));
}
return Single.error(ex);
}).flatMap(userService::enhance).doOnSuccess(user -> auditService.report(AuditBuilder.builder(AuthenticationAuditBuilder.class).principal(authentication).referenceType(ReferenceType.ORGANIZATION).referenceId(organizationId).user(user).ipAddress(details.get(IP_ADDRESS_KEY)).userAgent(details.get(USER_AGENT_KEY)))).blockingGet();
principal.setId(endUser.getId());
principal.setUsername(endUser.getUsername());
if (endUser.getAdditionalInformation() != null) {
principal.getAdditionalInformation().putAll(endUser.getAdditionalInformation());
}
principal.getAdditionalInformation().put(StandardClaims.SUB, endUser.getId());
principal.getAdditionalInformation().put(StandardClaims.PREFERRED_USERNAME, endUser.getUsername());
principal.getAdditionalInformation().put(Claims.organization, endUser.getReferenceId());
principal.getAdditionalInformation().put("login_count", endUser.getLoginsCount());
principal.getAdditionalInformation().computeIfAbsent(StandardClaims.EMAIL, val -> endUser.getEmail());
principal.getAdditionalInformation().computeIfAbsent(StandardClaims.NAME, val -> endUser.getDisplayName());
// set roles
Set<String> roles = endUser.getRoles() != null ? new HashSet<>(endUser.getRoles()) : new HashSet<>();
if (principal.getRoles() != null) {
roles.addAll(principal.getRoles());
}
principal.getAdditionalInformation().put(CustomClaims.ROLES, roles);
return principal;
}
use of io.gravitee.am.model.ReferenceType in project gravitee-access-management by gravitee-io.
the class CustomLogoutSuccessHandler method determineTargetUrl.
@Override
protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) {
String logoutRedirectUrl = request.getParameter(LOGOUT_URL_PARAMETER);
if (logoutRedirectUrl != null && !logoutRedirectUrl.isEmpty()) {
setTargetUrlParameter(LOGOUT_URL_PARAMETER);
}
final Cookie[] cookies = request.getCookies();
final Optional<Cookie> authCookie = Stream.of(cookies).filter(c -> authCookieName.equals(c.getName())).findFirst();
authCookie.ifPresent(cookie -> {
try {
final String jwtStr = cookie.getValue().substring("Bearer ".length());
final JWT jwt = jwtParser.parse(jwtStr);
WebAuthenticationDetails details = new WebAuthenticationDetails(request);
// read user profile to obtain same information as login step.
// if the read fails, trace only with information available into the cookie
userService.findById(ReferenceType.ORGANIZATION, (String) jwt.get("org"), (String) jwt.getSub()).doOnSuccess(user -> auditService.report(AuditBuilder.builder(LogoutAuditBuilder.class).user(user).referenceType(ReferenceType.ORGANIZATION).referenceId((String) jwt.get("org")).ipAddress(details.getRemoteAddress()).userAgent(details.getUserAgent()))).doOnError(err -> {
logger.warn("Unable to read user information, trace logout with minimal data", err);
auditService.report(AuditBuilder.builder(LogoutAuditBuilder.class).principal(new EndUserAuthentication(jwt.get("username"), null, new SimpleAuthenticationContext())).referenceType(ReferenceType.ORGANIZATION).referenceId((String) jwt.get("org")).ipAddress(details.getRemoteAddress()).userAgent(details.getUserAgent()));
}).subscribe();
} catch (Exception e) {
logger.warn("Unable to extract information from authentication cookie", e);
}
});
return super.determineTargetUrl(request, response);
}
use of io.gravitee.am.model.ReferenceType in project gravitee-access-management by gravitee-io.
the class IdentityProviderServiceImpl method create.
@Override
public Single<IdentityProvider> create(ReferenceType referenceType, String referenceId, NewIdentityProvider newIdentityProvider, User principal, boolean system) {
LOGGER.debug("Create a new identity provider {} for {} {}", newIdentityProvider, referenceType, referenceId);
var identityProvider = new IdentityProvider();
identityProvider.setId(newIdentityProvider.getId() == null ? RandomString.generate() : newIdentityProvider.getId());
identityProvider.setReferenceType(referenceType);
identityProvider.setReferenceId(referenceId);
identityProvider.setName(newIdentityProvider.getName());
identityProvider.setType(newIdentityProvider.getType());
identityProvider.setSystem(system);
identityProvider.setConfiguration(newIdentityProvider.getConfiguration());
identityProvider.setExternal(newIdentityProvider.isExternal());
identityProvider.setDomainWhitelist(ofNullable(newIdentityProvider.getDomainWhitelist()).orElse(List.of()));
identityProvider.setCreatedAt(new Date());
identityProvider.setUpdatedAt(identityProvider.getCreatedAt());
return identityProviderRepository.create(identityProvider).flatMap(identityProvider1 -> {
// create event for sync process
Event event = new Event(Type.IDENTITY_PROVIDER, new Payload(identityProvider1.getId(), identityProvider1.getReferenceType(), identityProvider1.getReferenceId(), Action.CREATE));
return eventService.create(event).flatMap(__ -> Single.just(identityProvider1));
}).onErrorResumeNext(ex -> {
LOGGER.error("An error occurs while trying to create an identity provider", ex);
return Single.error(new TechnicalManagementException("An error occurs while trying to create an identity provider", ex));
});
}
Aggregations