Search in sources :

Example 1 with ACTION

use of io.gravitee.rest.api.service.common.JWTHelper.ACTION in project gravitee-management-rest-api by gravitee-io.

the class UserServiceImpl method finalizeRegistration.

/**
 * Allows to complete the creation of a user which is pre-created.
 * @param registerUserEntity a valid token and a password
 * @return the user
 */
@Override
public UserEntity finalizeRegistration(final RegisterUserEntity registerUserEntity) {
    try {
        DecodedJWT jwt = getDecodedJWT(registerUserEntity.getToken());
        final String action = jwt.getClaim(Claims.ACTION).asString();
        if (RESET_PASSWORD.name().equals(action)) {
            throw new UserStateConflictException("Reset password forbidden on this resource");
        }
        if (USER_REGISTRATION.name().equals(action)) {
            checkUserRegistrationEnabled(GraviteeContext.getCurrentContext());
        } else if (GROUP_INVITATION.name().equals(action)) {
            // check invitations
            final String email = jwt.getClaim(Claims.EMAIL).asString();
            final List<InvitationEntity> invitations = invitationService.findAll();
            final List<InvitationEntity> userInvitations = invitations.stream().filter(invitation -> invitation.getEmail().equals(email)).collect(toList());
            if (userInvitations.isEmpty()) {
                throw new IllegalStateException("Invitation has been canceled");
            }
        }
        // check password here to avoid user creation if password is invalid
        if (registerUserEntity.getPassword() != null) {
            if (!passwordValidator.validate(registerUserEntity.getPassword())) {
                throw new PasswordFormatInvalidException();
            }
        }
        final Object subject = jwt.getSubject();
        User user;
        if (subject == null) {
            final NewExternalUserEntity externalUser = new NewExternalUserEntity();
            final String email = jwt.getClaim(Claims.EMAIL).asString();
            externalUser.setSource(IDP_SOURCE_GRAVITEE);
            externalUser.setSourceId(email);
            externalUser.setFirstname(registerUserEntity.getFirstname());
            externalUser.setLastname(registerUserEntity.getLastname());
            externalUser.setEmail(email);
            user = convert(create(externalUser, true));
            user.setOrganizationId(GraviteeContext.getCurrentOrganization());
        } else {
            final String username = subject.toString();
            LOGGER.debug("Create an internal user {}", username);
            Optional<User> checkUser = userRepository.findById(username);
            user = checkUser.orElseThrow(() -> new UserNotFoundException(username));
            if (StringUtils.isNotBlank(user.getPassword())) {
                throw new UserAlreadyFinalizedException(GraviteeContext.getCurrentOrganization());
            }
        }
        if (GROUP_INVITATION.name().equals(action)) {
            // check invitations
            final String email = user.getEmail();
            final String userId = user.getId();
            final List<InvitationEntity> invitations = invitationService.findAll();
            invitations.stream().filter(invitation -> invitation.getEmail().equals(email)).forEach(invitation -> {
                invitationService.addMember(invitation.getReferenceType().name(), invitation.getReferenceId(), userId, invitation.getApiRole(), invitation.getApplicationRole());
                invitationService.delete(invitation.getId(), invitation.getReferenceId());
            });
        }
        // Set date fields
        user.setUpdatedAt(new Date());
        // Encrypt password if internal user
        encryptPassword(user, registerUserEntity.getPassword());
        user = userRepository.update(user);
        auditService.createOrganizationAuditLog(Collections.singletonMap(USER, user.getId()), User.AuditEvent.USER_CREATED, user.getUpdatedAt(), null, user);
        // Do not send back the password
        user.setPassword(null);
        final UserEntity userEntity = convert(user, true);
        searchEngineService.index(userEntity, false);
        return userEntity;
    } catch (AbstractManagementException ex) {
        throw ex;
    } catch (Exception ex) {
        LOGGER.error("An error occurs while trying to create an internal user with the token {}", registerUserEntity.getToken(), ex);
        throw new TechnicalManagementException(ex.getMessage(), ex);
    }
}
Also used : BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) Page(io.gravitee.common.data.domain.Page) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) LoggerFactory(org.slf4j.LoggerFactory) MembershipRepository(io.gravitee.repository.management.api.MembershipRepository) Autowired(org.springframework.beans.factory.annotation.Autowired) SocialIdentityProviderEntity(io.gravitee.rest.api.model.configuration.identity.SocialIdentityProviderEntity) RoleScope(io.gravitee.rest.api.model.permissions.RoleScope) StringUtils(org.apache.commons.lang3.StringUtils) UPDATE(io.gravitee.rest.api.model.permissions.RolePermissionAction.UPDATE) IdentityProviderService(io.gravitee.rest.api.service.configuration.identity.IdentityProviderService) TemplateEngine(io.gravitee.el.TemplateEngine) Algorithm(com.auth0.jwt.algorithms.Algorithm) AuditQuery(io.gravitee.rest.api.model.audit.AuditQuery) PageableBuilder(io.gravitee.repository.management.api.search.builder.PageableBuilder) RoleMappingEntity(io.gravitee.rest.api.model.configuration.identity.RoleMappingEntity) Duration(java.time.Duration) PortalHook(io.gravitee.rest.api.service.notification.PortalHook) GroupMappingEntity(io.gravitee.rest.api.model.configuration.identity.GroupMappingEntity) Collectors.toSet(java.util.stream.Collectors.toSet) ApplicationSettings(io.gravitee.rest.api.model.application.ApplicationSettings) RolePermissionAction(io.gravitee.rest.api.model.permissions.RolePermissionAction) JsonPathFunction(io.gravitee.el.spel.function.json.JsonPathFunction) Instant(java.time.Instant) SimpleApplicationSettings(io.gravitee.rest.api.model.application.SimpleApplicationSettings) Collectors(java.util.stream.Collectors) Key(io.gravitee.rest.api.model.parameters.Key) NotificationParamsBuilder(io.gravitee.rest.api.service.notification.NotificationParamsBuilder) EmailNotificationBuilder(io.gravitee.rest.api.service.builder.EmailNotificationBuilder) UrlSanitizerUtils(io.gravitee.rest.api.service.sanitizer.UrlSanitizerUtils) DatatypeConverter(javax.xml.bind.DatatypeConverter) AuditEntity(io.gravitee.rest.api.model.audit.AuditEntity) RolePermission(io.gravitee.rest.api.model.permissions.RolePermission) SearchEngineService(io.gravitee.rest.api.service.search.SearchEngineService) JWT(com.auth0.jwt.JWT) io.gravitee.rest.api.service(io.gravitee.rest.api.service) java.util(java.util) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Pageable(io.gravitee.rest.api.model.common.Pageable) GraviteeContext(io.gravitee.rest.api.service.common.GraviteeContext) DEFAULT_JWT_EMAIL_REGISTRATION_EXPIRE_AFTER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_EMAIL_REGISTRATION_EXPIRE_AFTER) InitializingBean(org.springframework.beans.factory.InitializingBean) Value(org.springframework.beans.factory.annotation.Value) JWTVerifier(com.auth0.jwt.JWTVerifier) ReadContext(com.jayway.jsonpath.ReadContext) ConfigurableEnvironment(org.springframework.core.env.ConfigurableEnvironment) UserRepository(io.gravitee.repository.management.api.UserRepository) Claims(io.gravitee.rest.api.service.common.JWTHelper.Claims) UserStatus(io.gravitee.repository.management.model.UserStatus) io.gravitee.rest.api.model(io.gravitee.rest.api.model) Membership(io.gravitee.repository.management.model.Membership) Query(io.gravitee.rest.api.service.search.query.Query) UuidString(io.gravitee.rest.api.service.common.UuidString) Logger(org.slf4j.Logger) ParameterReferenceType(io.gravitee.rest.api.model.parameters.ParameterReferenceType) JsonPath(com.jayway.jsonpath.JsonPath) Maps(io.gravitee.common.util.Maps) DEFAULT_JWT_ISSUER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER) MetadataPage(io.gravitee.common.data.domain.MetadataPage) Collectors.toList(java.util.stream.Collectors.toList) Component(org.springframework.stereotype.Component) USER(io.gravitee.repository.management.model.Audit.AuditProperties.USER) ChronoUnit(java.time.temporal.ChronoUnit) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) io.gravitee.rest.api.service.exceptions(io.gravitee.rest.api.service.exceptions) UserCriteria(io.gravitee.repository.management.api.search.UserCriteria) User(io.gravitee.repository.management.model.User) ACTION(io.gravitee.rest.api.service.common.JWTHelper.ACTION) QueryBuilder(io.gravitee.rest.api.service.search.query.QueryBuilder) SearchResult(io.gravitee.rest.api.service.impl.search.SearchResult) User(io.gravitee.repository.management.model.User) UuidString(io.gravitee.rest.api.service.common.UuidString) TechnicalException(io.gravitee.repository.exceptions.TechnicalException) Collectors.toList(java.util.stream.Collectors.toList) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Aggregations

JWT (com.auth0.jwt.JWT)1 JWTVerifier (com.auth0.jwt.JWTVerifier)1 Algorithm (com.auth0.jwt.algorithms.Algorithm)1 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)1 JsonPath (com.jayway.jsonpath.JsonPath)1 ReadContext (com.jayway.jsonpath.ReadContext)1 MetadataPage (io.gravitee.common.data.domain.MetadataPage)1 Page (io.gravitee.common.data.domain.Page)1 Maps (io.gravitee.common.util.Maps)1 TemplateEngine (io.gravitee.el.TemplateEngine)1 JsonPathFunction (io.gravitee.el.spel.function.json.JsonPathFunction)1 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)1 MembershipRepository (io.gravitee.repository.management.api.MembershipRepository)1 UserRepository (io.gravitee.repository.management.api.UserRepository)1 UserCriteria (io.gravitee.repository.management.api.search.UserCriteria)1 PageableBuilder (io.gravitee.repository.management.api.search.builder.PageableBuilder)1 USER (io.gravitee.repository.management.model.Audit.AuditProperties.USER)1 Membership (io.gravitee.repository.management.model.Membership)1 User (io.gravitee.repository.management.model.User)1 UserStatus (io.gravitee.repository.management.model.UserStatus)1