Search in sources :

Example 86 with ResultCodeException

use of eu.bcvsolutions.idm.core.api.exception.ResultCodeException in project CzechIdMng by bcvsolutions.

the class SysSystemController method saveConnectorFormValues.

/**
 * Saves connector configuration form values
 *
 * @param backendId
 * @param formValues
 * @return
 */
@ResponseBody
@PreAuthorize("hasAuthority('" + AccGroupPermission.SYSTEM_UPDATE + "')")
@RequestMapping(value = "/{backendId}/connector-form-values", method = RequestMethod.POST)
@ApiOperation(value = "Connector configuration - save values", nickname = "postConnectorFormValues", tags = { SysSystemController.TAG }, authorizations = { @Authorization(value = SwaggerConfig.AUTHENTICATION_BASIC, scopes = { @AuthorizationScope(scope = AccGroupPermission.SYSTEM_UPDATE, description = "") }), @Authorization(value = SwaggerConfig.AUTHENTICATION_CIDMST, scopes = { @AuthorizationScope(scope = AccGroupPermission.SYSTEM_UPDATE, description = "") }) })
public Resource<?> saveConnectorFormValues(@ApiParam(value = "System's uuid identifier or code.", required = true) @PathVariable @NotNull String backendId, @RequestBody @Valid List<IdmFormValueDto> formValues) {
    SysSystemDto entity = getDto(backendId);
    if (entity == null) {
        throw new ResultCodeException(CoreResultCode.NOT_FOUND, ImmutableMap.of("entity", backendId));
    }
    IdmFormDefinitionDto formDefinition = getConnectorFormDefinition(entity);
    return formDefinitionController.saveFormValues(entity, formDefinition, formValues);
}
Also used : ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) IdmFormDefinitionDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDefinitionDto) SysSystemDto(eu.bcvsolutions.idm.acc.dto.SysSystemDto) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 87 with ResultCodeException

use of eu.bcvsolutions.idm.core.api.exception.ResultCodeException in project CzechIdMng by bcvsolutions.

the class SysSystemEntityController method getConnectorObject.

@ResponseBody
@PreAuthorize("hasAuthority('" + AccGroupPermission.SYSTEM_READ + "')")
@RequestMapping(value = "/{backendId}/connector-object", method = RequestMethod.GET)
@ApiOperation(value = "Connector object for the system entity", nickname = "getConnectorObject", response = IcConnectorObject.class, tags = { SysSystemEntityController.TAG }, authorizations = { @Authorization(value = SwaggerConfig.AUTHENTICATION_BASIC, scopes = { @AuthorizationScope(scope = AccGroupPermission.SYSTEM_READ, description = "") }), @Authorization(value = SwaggerConfig.AUTHENTICATION_CIDMST, scopes = { @AuthorizationScope(scope = AccGroupPermission.SYSTEM_READ, description = "") }) })
public ResponseEntity<IcConnectorObject> getConnectorObject(@ApiParam(value = "System entity's uuid identifier.", required = true) @PathVariable @NotNull String backendId) {
    SysSystemEntityDto systemEntity = this.getDto(backendId);
    if (systemEntity == null) {
        throw new ResultCodeException(CoreResultCode.NOT_FOUND, ImmutableMap.of("entity", backendId));
    }
    IcConnectorObject connectorObject = ((SysSystemEntityService) getService()).getConnectorObject(systemEntity, IdmBasePermission.READ);
    if (connectorObject == null) {
        return new ResponseEntity<IcConnectorObject>(HttpStatus.NO_CONTENT);
    }
    return new ResponseEntity<IcConnectorObject>(connectorObject, HttpStatus.OK);
}
Also used : SysSystemEntityService(eu.bcvsolutions.idm.acc.service.api.SysSystemEntityService) ResponseEntity(org.springframework.http.ResponseEntity) IcConnectorObject(eu.bcvsolutions.idm.ic.api.IcConnectorObject) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) SysSystemEntityDto(eu.bcvsolutions.idm.acc.dto.SysSystemEntityDto) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 88 with ResultCodeException

use of eu.bcvsolutions.idm.core.api.exception.ResultCodeException in project CzechIdMng by bcvsolutions.

the class DefaultAccAuthenticator method authenticate.

@Override
public LoginDto authenticate(LoginDto loginDto) {
    // temporary solution for get system id, this is not nice.
    String systemCodeable = configurationService.getValue(PROPERTY_AUTH_SYSTEM_ID);
    if (StringUtils.isEmpty(systemCodeable)) {
        // without system can't check
        return null;
    }
    // 
    SysSystemDto system = (SysSystemDto) lookupService.lookupDto(SysSystemDto.class, systemCodeable);
    // 
    if (system == null) {
        LOG.warn("System by codeable identifier [{}] not found. Check configuration property [{}]", systemCodeable, PROPERTY_AUTH_SYSTEM_ID);
        // system doesn't exist
        return null;
    }
    IdmIdentityDto identity = (IdmIdentityDto) lookupService.lookupDto(IdmIdentityDto.class, loginDto.getUsername());
    if (identity == null) {
        throw new IdmAuthenticationException(MessageFormat.format("Check identity can login: The identity [{0}] either doesn't exist or is deleted.", loginDto.getUsername()));
    }
    // 
    // search authentication attribute for system with provisioning mapping, only for identity
    SysSystemAttributeMappingDto attribute = systemAttributeMappingService.getAuthenticationAttribute(system.getId(), SystemEntityType.IDENTITY);
    // 
    if (attribute == null) {
        // attribute MUST exist
        throw new ResultCodeException(AccResultCode.AUTHENTICATION_AUTHENTICATION_ATTRIBUTE_DONT_SET, ImmutableMap.of("name", system.getName()));
    }
    // 
    // find if identity has account on system
    List<AccAccountDto> accounts = accountService.getAccounts(system.getId(), identity.getId());
    if (accounts.isEmpty()) {
        // user hasn't account on system, continue
        return null;
    }
    // 
    ResultCodeException authFailedException = null;
    IcUidAttribute auth = null;
    for (AccAccountDto account : accounts) {
        SysSchemaAttributeDto schemaAttribute = schemaAttributeService.get(attribute.getSchemaAttribute());
        SysSchemaObjectClassDto schemaObjectClassDto = DtoUtils.getEmbedded(schemaAttribute, SysSchemaAttribute_.objectClass, SysSchemaObjectClassDto.class);
        SysSystemEntityDto systemEntityDto = systemEntityService.get(account.getSystemEntity());
        IcObjectClass objectClass = new IcObjectClassImpl(schemaObjectClassDto.getObjectClassName());
        IcConnectorObject connectorObject = systemService.readConnectorObject(system.getId(), systemEntityDto.getUid(), objectClass);
        // 
        if (connectorObject == null) {
            continue;
        }
        // 
        String transformUsername = null;
        // iterate over all attributes to find authentication attribute
        for (IcAttribute icAttribute : connectorObject.getAttributes()) {
            if (icAttribute.getName().equals(schemaAttributeService.get(attribute.getSchemaAttribute()).getName())) {
                transformUsername = String.valueOf(icAttribute.getValue());
                break;
            }
        }
        if (transformUsername == null) {
            throw new ResultCodeException(AccResultCode.AUTHENTICATION_USERNAME_DONT_EXISTS, ImmutableMap.of("username", loginDto.getUsername(), "name", system.getName()));
        }
        // authentication over system, when password or username not exist or bad credentials - throw error
        try {
            // authentication against system
            auth = provisioningService.authenticate(transformUsername, loginDto.getPassword(), system, SystemEntityType.IDENTITY);
            authFailedException = null;
            // check auth
            if (auth == null || auth.getValue() == null) {
                authFailedException = new ResultCodeException(AccResultCode.AUTHENTICATION_AGAINST_SYSTEM_FAILED, ImmutableMap.of("name", system.getName(), "username", loginDto.getUsername()));
                // failed, continue to another
                break;
            }
            // everything success break
            break;
        } catch (ResultCodeException e) {
            // failed, continue to another
            authFailedException = new ResultCodeException(CoreResultCode.AUTH_FAILED, "Invalid login or password.", e);
        }
    }
    if (auth == null || auth.getValue() == null) {
        authFailedException = new ResultCodeException(AccResultCode.AUTHENTICATION_AGAINST_SYSTEM_FAILED, ImmutableMap.of("name", system.getName(), "username", loginDto.getUsername()));
    }
    // 
    if (authFailedException != null) {
        throw authFailedException;
    }
    String module = this.getModule();
    loginDto = jwtAuthenticationService.createJwtAuthenticationAndAuthenticate(loginDto, identity, module);
    LOG.info("Identity with username [{}] is authenticated by system [{}]", loginDto.getUsername(), system.getName());
    return loginDto;
}
Also used : IcObjectClassImpl(eu.bcvsolutions.idm.ic.impl.IcObjectClassImpl) SysSystemAttributeMappingDto(eu.bcvsolutions.idm.acc.dto.SysSystemAttributeMappingDto) SysSchemaAttributeDto(eu.bcvsolutions.idm.acc.dto.SysSchemaAttributeDto) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) AccAccountDto(eu.bcvsolutions.idm.acc.dto.AccAccountDto) SysSystemDto(eu.bcvsolutions.idm.acc.dto.SysSystemDto) IcObjectClass(eu.bcvsolutions.idm.ic.api.IcObjectClass) IcAttribute(eu.bcvsolutions.idm.ic.api.IcAttribute) IcConnectorObject(eu.bcvsolutions.idm.ic.api.IcConnectorObject) IdmAuthenticationException(eu.bcvsolutions.idm.core.security.exception.IdmAuthenticationException) IcUidAttribute(eu.bcvsolutions.idm.ic.api.IcUidAttribute) SysSchemaObjectClassDto(eu.bcvsolutions.idm.acc.dto.SysSchemaObjectClassDto) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto) SysSystemEntityDto(eu.bcvsolutions.idm.acc.dto.SysSystemEntityDto)

Example 89 with ResultCodeException

use of eu.bcvsolutions.idm.core.api.exception.ResultCodeException in project CzechIdMng by bcvsolutions.

the class AbstractScriptEvaluator method evaluate.

/**
 * Evaluated given script with parameters. Check if this we have permission for evaluated this script.
 * @param scriptCode
 * @param parameters
 * @return
 * @throws ClassNotFoundException
 */
protected Object evaluate(String scriptCode, Map<String, Object> parameters) {
    IdmScript script = scriptRepository.findOneByCode(scriptCode);
    // 
    if (script == null) {
        throw new ResultCodeException(CoreResultCode.NOT_FOUND, ImmutableMap.of("script", scriptCode));
    }
    // 
    if (!canExecuteScript(script)) {
        throw new ResultCodeException(CoreResultCode.GROOVY_SCRIPT_INVALID_CATEGORY, ImmutableMap.of("scriptCategory", script.getCategory()));
    }
    // 
    List<IdmScriptAuthorityDto> scriptAuthorities = getScriptAuthorityForScript(script.getId());
    // 
    List<Class<?>> extraAllowedClasses = new ArrayList<>();
    // 
    // Add builder
    extraAllowedClasses.add(Builder.class);
    // 
    for (IdmScriptAuthorityDto scriptAuthority : scriptAuthorities) {
        if (scriptAuthority.getType() == ScriptAuthorityType.CLASS_NAME) {
            try {
                extraAllowedClasses.add(Class.forName(scriptAuthority.getClassName()));
            } catch (ClassNotFoundException e) {
                LOG.error(e.getLocalizedMessage());
                throw new ResultCodeException(CoreResultCode.BAD_VALUE, ImmutableMap.of("class", scriptAuthority.getClassName()), e);
            }
        } else {
            parameters.put(scriptAuthority.getService(), applicationContext.getBean(scriptAuthority.getService()));
        }
    }
    // 
    try {
        return groovyScriptService.evaluate(script.getScript(), parameters, extraAllowedClasses);
    } catch (SecurityException | IdmSecurityException ex) {
        LOG.error("SecurityException [{}]. Script code: [{}], name: [{}], category: [{}]", ex.getLocalizedMessage(), script.getCode(), script.getName(), script.getCategory().name());
        throw ex;
    } catch (Exception e) {
        LOG.error("Exception [{}]. Script code: [{}], name: [{}], category: [{}]", e.getLocalizedMessage(), script.getCode(), script.getName(), script.getCategory().name());
        throw e;
    }
}
Also used : IdmScript(eu.bcvsolutions.idm.core.model.entity.IdmScript) IdmScriptAuthorityDto(eu.bcvsolutions.idm.core.api.dto.IdmScriptAuthorityDto) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) ArrayList(java.util.ArrayList) IdmSecurityException(eu.bcvsolutions.idm.core.security.exception.IdmSecurityException) IdmSecurityException(eu.bcvsolutions.idm.core.security.exception.IdmSecurityException) IdmSecurityException(eu.bcvsolutions.idm.core.security.exception.IdmSecurityException) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException)

Example 90 with ResultCodeException

use of eu.bcvsolutions.idm.core.api.exception.ResultCodeException in project CzechIdMng by bcvsolutions.

the class JwtIdmAuthenticationFilter method authorize.

@Override
public boolean authorize(String token, HttpServletRequest request, HttpServletResponse response) {
    IdmJwtAuthenticationDto claims = null;
    try {
        Optional<Jwt> jwt = HttpFilterUtils.parseToken(token);
        if (!jwt.isPresent()) {
            return false;
        }
        HttpFilterUtils.verifyToken(jwt.get(), jwtTokenMapper.getVerifier());
        claims = jwtTokenMapper.getClaims(jwt.get());
        ctx.setToken(claims);
        Authentication auth = authenticationManager.authenticate(jwtTokenMapper.fromDto(claims));
        LOG.debug("User [{}] successfully logged in.", auth.getName());
        return auth.isAuthenticated();
    } catch (ResultCodeException ex) {
        LOG.warn("Invalid token, reason: [{}]", ex.getMessage());
        ctx.setCodeEx(ex);
        // only expired or authorities changed
        ctx.setToken(claims);
    } catch (AuthenticationException ex) {
        LOG.warn("Invalid authentication, reason: [{}]", ex.getMessage());
        ctx.setAuthEx(ex);
    } catch (InvalidSignatureException | IOException | IllegalArgumentException ex) {
        // client sent some rubbish, just log and ignore
        LOG.warn("Invalid IdM auth token received.", ex);
    }
    return false;
}
Also used : InvalidSignatureException(org.springframework.security.jwt.crypto.sign.InvalidSignatureException) AuthenticationException(org.springframework.security.core.AuthenticationException) Jwt(org.springframework.security.jwt.Jwt) Authentication(org.springframework.security.core.Authentication) ResultCodeException(eu.bcvsolutions.idm.core.api.exception.ResultCodeException) IdmJwtAuthenticationDto(eu.bcvsolutions.idm.core.security.api.dto.IdmJwtAuthenticationDto) IOException(java.io.IOException)

Aggregations

ResultCodeException (eu.bcvsolutions.idm.core.api.exception.ResultCodeException)162 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)48 ApiOperation (io.swagger.annotations.ApiOperation)47 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)47 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)44 IdmIdentityDto (eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto)33 Test (org.junit.Test)31 ResponseEntity (org.springframework.http.ResponseEntity)22 SysSystemDto (eu.bcvsolutions.idm.acc.dto.SysSystemDto)20 IdmRoleDto (eu.bcvsolutions.idm.core.api.dto.IdmRoleDto)17 AbstractIntegrationTest (eu.bcvsolutions.idm.test.api.AbstractIntegrationTest)17 Transactional (org.springframework.transaction.annotation.Transactional)17 IdmFormDefinitionDto (eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDefinitionDto)15 UUID (java.util.UUID)15 ArrayList (java.util.ArrayList)14 IdmPasswordPolicyDto (eu.bcvsolutions.idm.core.api.dto.IdmPasswordPolicyDto)13 PasswordChangeDto (eu.bcvsolutions.idm.core.api.dto.PasswordChangeDto)12 DefaultEventResult (eu.bcvsolutions.idm.core.api.event.DefaultEventResult)12 IOException (java.io.IOException)12 AccAccountDto (eu.bcvsolutions.idm.acc.dto.AccAccountDto)10