Search in sources :

Example 1 with ReferenceType

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)));
}
Also used : ScimUserSearch(io.gravitee.am.repository.jdbc.common.dialect.ScimUserSearch) Address(io.gravitee.am.model.scim.Address) FilterCriteria(io.gravitee.am.repository.management.api.search.FilterCriteria) Completable(io.reactivex.Completable) Maybe(io.reactivex.Maybe) Query(org.springframework.data.relational.core.query.Query) LocalDateTime(java.time.LocalDateTime) Autowired(org.springframework.beans.factory.annotation.Autowired) Criteria.where(org.springframework.data.relational.core.query.Criteria.where) Single(io.reactivex.Single) InitializingBean(org.springframework.beans.factory.InitializingBean) DatabaseClient(org.springframework.r2dbc.core.DatabaseClient) OrganizationUserRepository(io.gravitee.am.repository.management.api.OrganizationUserRepository) AbstractJdbcRepository(io.gravitee.am.repository.jdbc.management.AbstractJdbcRepository) io.gravitee.am.repository.jdbc.management.api.spring.user(io.gravitee.am.repository.jdbc.management.api.spring.user) Attribute(io.gravitee.am.model.scim.Attribute) Flowable(io.reactivex.Flowable) Map(java.util.Map) ReferenceType(io.gravitee.am.model.ReferenceType) Sort(org.springframework.data.domain.Sort) Stream.concat(java.util.stream.Stream.concat) User(io.gravitee.am.model.User) Repository(org.springframework.stereotype.Repository) StreamUtils(org.springframework.data.util.StreamUtils) Page(io.gravitee.am.model.common.Page) TransactionalOperator(org.springframework.transaction.reactive.TransactionalOperator) PageRequest(org.springframework.data.domain.PageRequest) Mono(reactor.core.publisher.Mono) RandomString(io.gravitee.am.common.utils.RandomString) Flux(reactor.core.publisher.Flux) List(java.util.List) Stream(java.util.stream.Stream) RxJava2Adapter(reactor.adapter.rxjava.RxJava2Adapter) JdbcOrganizationUser(io.gravitee.am.repository.jdbc.management.api.model.JdbcOrganizationUser) Optional(java.util.Optional) ScimUserSearch(io.gravitee.am.repository.jdbc.common.dialect.ScimUserSearch) Page(io.gravitee.am.model.common.Page) RandomString(io.gravitee.am.common.utils.RandomString) DatabaseClient(org.springframework.r2dbc.core.DatabaseClient) JdbcOrganizationUser(io.gravitee.am.repository.jdbc.management.api.model.JdbcOrganizationUser) Map(java.util.Map)

Example 2 with ReferenceType

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)));
}
Also used : SpringRoleRepository(io.gravitee.am.repository.jdbc.management.api.spring.role.SpringRoleRepository) Completable(io.reactivex.Completable) Role(io.gravitee.am.model.Role) Maybe(io.reactivex.Maybe) Query(org.springframework.data.relational.core.query.Query) LocalDateTime(java.time.LocalDateTime) Autowired(org.springframework.beans.factory.annotation.Autowired) Criteria.where(org.springframework.data.relational.core.query.Criteria.where) Single(io.reactivex.Single) Function(java.util.function.Function) InitializingBean(org.springframework.beans.factory.InitializingBean) DatabaseClient(org.springframework.r2dbc.core.DatabaseClient) AbstractJdbcRepository(io.gravitee.am.repository.jdbc.management.AbstractJdbcRepository) Flowable(io.reactivex.Flowable) SpringRoleOauthScopeRepository(io.gravitee.am.repository.jdbc.management.api.spring.role.SpringRoleOauthScopeRepository) ReferenceType(io.gravitee.am.model.ReferenceType) Sort(org.springframework.data.domain.Sort) Repository(org.springframework.stereotype.Repository) Page(io.gravitee.am.model.common.Page) JdbcRole(io.gravitee.am.repository.jdbc.management.api.model.JdbcRole) Publisher(org.reactivestreams.Publisher) TransactionalOperator(org.springframework.transaction.reactive.TransactionalOperator) PageRequest(org.springframework.data.domain.PageRequest) Mono(reactor.core.publisher.Mono) RandomString(io.gravitee.am.common.utils.RandomString) RoleRepository(io.gravitee.am.repository.management.api.RoleRepository) Flux(reactor.core.publisher.Flux) List(java.util.List) RxJava2Adapter(reactor.adapter.rxjava.RxJava2Adapter) JdbcRole(io.gravitee.am.repository.jdbc.management.api.model.JdbcRole) Page(io.gravitee.am.model.common.Page) RandomString(io.gravitee.am.common.utils.RandomString)

Example 3 with ReferenceType

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;
}
Also used : UserNotFoundException(io.gravitee.am.service.exception.UserNotFoundException) java.util(java.util) Completable(io.reactivex.Completable) Maybe(io.reactivex.Maybe) AuthenticationAuditBuilder(io.gravitee.am.service.reporter.builder.AuthenticationAuditBuilder) Autowired(org.springframework.beans.factory.annotation.Autowired) AuditService(io.gravitee.am.service.AuditService) Single(io.reactivex.Single) DefaultUser(io.gravitee.am.identityprovider.api.DefaultUser) User(io.gravitee.am.identityprovider.api.User) AuditBuilder(io.gravitee.am.service.reporter.builder.AuditBuilder) ReferenceType(io.gravitee.am.model.ReferenceType) SimpleAuthenticationContext(io.gravitee.am.identityprovider.api.SimpleAuthenticationContext) MembershipService(io.gravitee.am.service.MembershipService) RoleService(io.gravitee.am.service.RoleService) AuthenticationService(io.gravitee.am.management.handlers.management.api.authentication.service.AuthenticationService) StandardClaims(io.gravitee.am.common.oidc.StandardClaims) EndUserAuthentication(io.gravitee.am.management.handlers.management.api.authentication.provider.security.EndUserAuthentication) MemberType(io.gravitee.am.model.membership.MemberType) Membership(io.gravitee.am.model.Membership) UserNotFoundException(io.gravitee.am.service.exception.UserNotFoundException) Organization(io.gravitee.am.model.Organization) Claims(io.gravitee.am.common.jwt.Claims) OrganizationUserService(io.gravitee.am.service.OrganizationUserService) CustomClaims(io.gravitee.am.common.oidc.CustomClaims) Authentication(org.springframework.security.core.Authentication) DefaultUser(io.gravitee.am.identityprovider.api.DefaultUser) User(io.gravitee.am.identityprovider.api.User) SimpleAuthenticationContext(io.gravitee.am.identityprovider.api.SimpleAuthenticationContext) DefaultUser(io.gravitee.am.identityprovider.api.DefaultUser) AuthenticationAuditBuilder(io.gravitee.am.service.reporter.builder.AuthenticationAuditBuilder) EndUserAuthentication(io.gravitee.am.management.handlers.management.api.authentication.provider.security.EndUserAuthentication)

Example 4 with ReferenceType

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);
}
Also used : Cookie(javax.servlet.http.Cookie) JWTParser(io.gravitee.am.jwt.JWTParser) UserService(io.gravitee.am.management.service.UserService) JWT(io.gravitee.am.common.jwt.JWT) EndUserAuthentication(io.gravitee.am.management.handlers.management.api.authentication.provider.security.EndUserAuthentication) WebAuthenticationDetails(io.gravitee.am.management.handlers.management.api.authentication.web.WebAuthenticationDetails) HttpServletResponse(javax.servlet.http.HttpServletResponse) SimpleUrlLogoutSuccessHandler(org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler) AuditService(io.gravitee.am.service.AuditService) HttpServletRequest(javax.servlet.http.HttpServletRequest) Stream(java.util.stream.Stream) AuditBuilder(io.gravitee.am.service.reporter.builder.AuditBuilder) LogoutAuditBuilder(io.gravitee.am.service.reporter.builder.LogoutAuditBuilder) Environment(org.springframework.core.env.Environment) Optional(java.util.Optional) ReferenceType(io.gravitee.am.model.ReferenceType) OrganizationUserService(io.gravitee.am.management.service.OrganizationUserService) Cookie(javax.servlet.http.Cookie) SimpleAuthenticationContext(io.gravitee.am.identityprovider.api.SimpleAuthenticationContext) JWT(io.gravitee.am.common.jwt.JWT) WebAuthenticationDetails(io.gravitee.am.management.handlers.management.api.authentication.web.WebAuthenticationDetails) LogoutAuditBuilder(io.gravitee.am.service.reporter.builder.LogoutAuditBuilder) SimpleAuthenticationContext(io.gravitee.am.identityprovider.api.SimpleAuthenticationContext) EndUserAuthentication(io.gravitee.am.management.handlers.management.api.authentication.provider.security.EndUserAuthentication)

Example 5 with ReferenceType

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));
    });
}
Also used : ApplicationService(io.gravitee.am.service.ApplicationService) Primary(org.springframework.context.annotation.Primary) Date(java.util.Date) Completable(io.reactivex.Completable) Maybe(io.reactivex.Maybe) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) IdentityProvider(io.gravitee.am.model.IdentityProvider) AuditService(io.gravitee.am.service.AuditService) Single(io.reactivex.Single) Event(io.gravitee.am.model.common.event.Event) Type(io.gravitee.am.common.event.Type) TechnicalManagementException(io.gravitee.am.service.exception.TechnicalManagementException) Flowable(io.reactivex.Flowable) User(io.gravitee.am.identityprovider.api.User) IdentityProviderAuditBuilder(io.gravitee.am.service.reporter.builder.management.IdentityProviderAuditBuilder) AuditBuilder(io.gravitee.am.service.reporter.builder.AuditBuilder) NewIdentityProvider(io.gravitee.am.service.model.NewIdentityProvider) ReferenceType(io.gravitee.am.model.ReferenceType) EventService(io.gravitee.am.service.EventService) IdentityProviderRepository(io.gravitee.am.repository.management.api.IdentityProviderRepository) IdentityProviderNotFoundException(io.gravitee.am.service.exception.IdentityProviderNotFoundException) Action(io.gravitee.am.common.event.Action) IdentityProviderWithApplicationsException(io.gravitee.am.service.exception.IdentityProviderWithApplicationsException) Logger(org.slf4j.Logger) Optional.ofNullable(java.util.Optional.ofNullable) EventType(io.gravitee.am.common.audit.EventType) AbstractManagementException(io.gravitee.am.service.exception.AbstractManagementException) RandomString(io.gravitee.am.common.utils.RandomString) UpdateIdentityProvider(io.gravitee.am.service.model.UpdateIdentityProvider) Component(org.springframework.stereotype.Component) List(java.util.List) Payload(io.gravitee.am.model.common.event.Payload) Lazy(org.springframework.context.annotation.Lazy) IdentityProviderService(io.gravitee.am.service.IdentityProviderService) Event(io.gravitee.am.model.common.event.Event) IdentityProvider(io.gravitee.am.model.IdentityProvider) NewIdentityProvider(io.gravitee.am.service.model.NewIdentityProvider) UpdateIdentityProvider(io.gravitee.am.service.model.UpdateIdentityProvider) Payload(io.gravitee.am.model.common.event.Payload) Date(java.util.Date) TechnicalManagementException(io.gravitee.am.service.exception.TechnicalManagementException)

Aggregations

ReferenceType (io.gravitee.am.model.ReferenceType)19 RandomString (io.gravitee.am.common.utils.RandomString)15 Autowired (org.springframework.beans.factory.annotation.Autowired)15 Single (io.reactivex.Single)13 Maybe (io.reactivex.Maybe)12 AuditBuilder (io.gravitee.am.service.reporter.builder.AuditBuilder)11 Completable (io.reactivex.Completable)11 Flowable (io.reactivex.Flowable)11 Logger (org.slf4j.Logger)11 LoggerFactory (org.slf4j.LoggerFactory)11 Component (org.springframework.stereotype.Component)11 AuditService (io.gravitee.am.service.AuditService)10 EventType (io.gravitee.am.common.audit.EventType)9 Action (io.gravitee.am.common.event.Action)9 User (io.gravitee.am.identityprovider.api.User)9 Event (io.gravitee.am.model.common.event.Event)9 Payload (io.gravitee.am.model.common.event.Payload)9 Lazy (org.springframework.context.annotation.Lazy)9 Page (io.gravitee.am.model.common.Page)8 EventService (io.gravitee.am.service.EventService)8