Search in sources :

Example 1 with NotAuthorizedException

use of org.summerb.approaches.security.api.exceptions.NotAuthorizedException in project summerb by skarpushin.

the class RestExceptionTranslator method determineFailureResult.

private DtoBase determineFailureResult(Exception ex, HttpServletRequest request, HttpServletResponse response) {
    // first see if it is FVE
    FieldValidationException fve = ExceptionUtils.findExceptionOfType(ex, FieldValidationException.class);
    if (fve != null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        return fve.getErrorDescriptionObject();
    }
    boolean translateAuthErrors = Boolean.TRUE.equals(Boolean.valueOf(request.getHeader(X_TRANSLATE_AUTHORIZATION_ERRORS)));
    GenericServerErrorResult ret = null;
    if (translateAuthErrors) {
        ret = new GenericServerErrorResult(exceptionTranslator.buildUserMessage(ex, LocaleContextHolder.getLocale()), new ExceptionInfo(ex));
    }
    NotAuthorizedException naex = ExceptionUtils.findExceptionOfType(ex, NotAuthorizedException.class);
    if (naex != null) {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return ret != null ? ret : naex.getResult();
    }
    AuthenticationException ae = ExceptionUtils.findExceptionOfType(ex, AuthenticationException.class);
    if (ae != null) {
        // NOTE: See how we did that in AuthenticationFailureHandlerImpl...
        // Looks like we need to augment our custom RestLoginFilter so it
        // will put username to request
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return ret != null ? ret : new NotAuthorizedResult("(username not resolved)", SecurityMessageCodes.AUTH_FATAL);
    }
    AccessDeniedException ade = ExceptionUtils.findExceptionOfType(ex, AccessDeniedException.class);
    if (ade != null) {
        if (authenticationTrustResolver.isAnonymous(SecurityContextHolder.getContext().getAuthentication())) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return ret != null ? ret : new NotAuthorizedResult(getCurrentUser(null), SecurityMessageCodes.LOGIN_REQUIRED);
        }
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return ret != null ? ret : new NotAuthorizedResult(getCurrentUser(null), SecurityMessageCodes.ACCESS_DENIED);
    }
    CurrentUserNotFoundException cunfe = ExceptionUtils.findExceptionOfType(ex, CurrentUserNotFoundException.class);
    if (cunfe != null) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return ret != null ? ret : new NotAuthorizedResult(getCurrentUser(null), SecurityMessageCodes.LOGIN_REQUIRED);
    }
    // TODO: Do we really need to send whole stack trace to client ??? I think we
    // should do it only during development
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    return new GenericServerErrorResult(exceptionTranslator.buildUserMessage(ex, LocaleContextHolder.getLocale()), new ExceptionInfo(ex));
}
Also used : FieldValidationException(org.summerb.approaches.validation.FieldValidationException) AccessDeniedException(org.springframework.security.access.AccessDeniedException) AuthenticationException(org.springframework.security.core.AuthenticationException) NotAuthorizedResult(org.summerb.approaches.security.api.dto.NotAuthorizedResult) CurrentUserNotFoundException(org.summerb.approaches.security.api.CurrentUserNotFoundException) NotAuthorizedException(org.summerb.approaches.security.api.exceptions.NotAuthorizedException) GenericServerErrorResult(org.summerb.utils.exceptions.dto.GenericServerErrorResult) ExceptionInfo(org.summerb.utils.exceptions.dto.ExceptionInfo)

Example 2 with NotAuthorizedException

use of org.summerb.approaches.security.api.exceptions.NotAuthorizedException in project summerb by skarpushin.

the class EasyCrudM2mServiceImpl method removeReferencee.

@Override
public void removeReferencee(T1Id referencerId, T2Id referenceeId) throws NotAuthorizedException {
    try {
        Query q = Query.n();
        addEqQuery(ManyToManyDto.FN_SRC, referencerId, q);
        addEqQuery(ManyToManyDto.FN_DST, referenceeId, q);
        ManyToManyDto<T1Id, T2Id> pair = findOneByQuery(q);
        try {
            deleteById(pair.getId());
        } catch (EntityNotFoundException e) {
        // that's ok, we wanted it to not exist, it's not there. This
        // state
        // is acceptable
        }
    } catch (Throwable t) {
        Throwables.throwIfInstanceOf(t, NotAuthorizedException.class);
        throw new RuntimeException("Failed to remove reference from " + serviceFrom.getEntityTypeMessageCode() + " identified by " + referencerId + " to " + serviceTo.getEntityTypeMessageCode() + " identified by " + referenceeId, t);
    }
}
Also used : Query(org.summerb.approaches.jdbccrud.api.query.Query) EntityNotFoundException(org.summerb.approaches.jdbccrud.api.exceptions.EntityNotFoundException) NotAuthorizedException(org.summerb.approaches.security.api.exceptions.NotAuthorizedException)

Example 3 with NotAuthorizedException

use of org.summerb.approaches.security.api.exceptions.NotAuthorizedException in project summerb by skarpushin.

the class EasyCrudRestControllerBase method resolveReferences.

private void resolveReferences(List<String> referencesToResolve, CrudQueryResult<TId, TDto> ret, List<TDto> items) throws EntityNotFoundException, NotAuthorizedException {
    Preconditions.checkState(dataSetLoader != null, "DataSetLoader is required to resolve references");
    Preconditions.checkState(referencesRegistry != null, "referencesRegistry is required to resolve references");
    DataSet ds = new DataSet();
    DataTable<TId, TDto> table = new DataTable<>(service.getEntityTypeMessageCode());
    table.putAll(items);
    ds.getTables().put(table.getName(), table);
    List<Ref> references = referencesToResolve.stream().map(name -> referencesRegistry.getRefByName(name)).collect(Collectors.toList());
    Ref[] refsArr = (Ref[]) references.toArray(new Ref[references.size()]);
    dataSetLoader.resolveReferencedObjects(ds, refsArr);
    // now remove initial table from dataset because we don't want to
    // duplicate this. It's already populated to rows
    ds.getTables().remove(table.getName());
    // x. ret
    ret.setRefsResolved(references.stream().collect(Collectors.toMap(Ref::getName, Function.identity())));
    ret.setRefs(ds);
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) PermissionsResolverStrategy(org.summerb.approaches.jdbccrud.rest.permissions.PermissionsResolverStrategy) Arrays(java.util.Arrays) RequestParam(org.springframework.web.bind.annotation.RequestParam) SingleItemResult(org.summerb.approaches.jdbccrud.rest.dto.SingleItemResult) RestExceptionTranslator(org.summerb.approaches.springmvc.security.implsrest.RestExceptionTranslator) HasId(org.summerb.approaches.jdbccrud.api.dto.HasId) Autowired(org.springframework.beans.factory.annotation.Autowired) DataTable(org.summerb.approaches.jdbccrud.api.dto.datapackage.DataTable) Function(java.util.function.Function) InitializingBean(org.springframework.beans.factory.InitializingBean) PagerParams(org.summerb.approaches.jdbccrud.api.dto.PagerParams) RequestBody(org.springframework.web.bind.annotation.RequestBody) ModelAttribute(org.springframework.web.bind.annotation.ModelAttribute) PutMapping(org.springframework.web.bind.annotation.PutMapping) GenericFilterBean(org.springframework.web.filter.GenericFilterBean) DataSetLoader(org.summerb.approaches.jdbccrud.api.relations.DataSetLoader) GetMapping(org.springframework.web.bind.annotation.GetMapping) OrderBy(org.summerb.approaches.jdbccrud.api.query.OrderBy) MultipleItemsResult(org.summerb.approaches.jdbccrud.rest.dto.MultipleItemsResult) Ref(org.summerb.approaches.jdbccrud.api.dto.relations.Ref) DeleteMapping(org.springframework.web.bind.annotation.DeleteMapping) ReferencesRegistry(org.summerb.approaches.jdbccrud.api.relations.ReferencesRegistry) PostMapping(org.springframework.web.bind.annotation.PostMapping) PathVariablesMap(org.summerb.approaches.jdbccrud.rest.commonpathvars.PathVariablesMap) MediaType(org.springframework.http.MediaType) FilteringParamsToQueryConverterImpl(org.summerb.approaches.jdbccrud.mvc.filter.FilteringParamsToQueryConverterImpl) BeansException(org.springframework.beans.BeansException) PaginatedList(org.summerb.approaches.jdbccrud.api.dto.PaginatedList) QueryNarrowerStrategy(org.summerb.approaches.jdbccrud.rest.querynarrower.QueryNarrowerStrategy) Collectors(java.util.stream.Collectors) ApplicationContext(org.springframework.context.ApplicationContext) Query(org.summerb.approaches.jdbccrud.api.query.Query) FilteringParamsToQueryConverter(org.summerb.approaches.jdbccrud.mvc.filter.FilteringParamsToQueryConverter) EasyCrudQueryParams(org.summerb.approaches.jdbccrud.mvc.model.EasyCrudQueryParams) CrudQueryResult(org.summerb.approaches.jdbccrud.rest.dto.CrudQueryResult) NotAuthorizedException(org.summerb.approaches.security.api.exceptions.NotAuthorizedException) ApiIgnore(springfox.documentation.annotations.ApiIgnore) List(java.util.List) DataSet(org.summerb.approaches.jdbccrud.api.dto.datapackage.DataSet) CollectionUtils(org.springframework.util.CollectionUtils) EntityNotFoundException(org.summerb.approaches.jdbccrud.api.exceptions.EntityNotFoundException) Preconditions(com.google.common.base.Preconditions) ApplicationContextAware(org.springframework.context.ApplicationContextAware) EasyCrudService(org.summerb.approaches.jdbccrud.api.EasyCrudService) DataTable(org.summerb.approaches.jdbccrud.api.dto.datapackage.DataTable) Ref(org.summerb.approaches.jdbccrud.api.dto.relations.Ref) DataSet(org.summerb.approaches.jdbccrud.api.dto.datapackage.DataSet)

Example 4 with NotAuthorizedException

use of org.summerb.approaches.security.api.exceptions.NotAuthorizedException in project summerb by skarpushin.

the class ControllerExceptionHandlerStrategyLegacyImpl method buildJsonError.

/**
 * This peace of crap needs to be removed. Because in case of JSON it's rest
 * API, there is no place for {@link ModelAndView}. Response should be pure JSON
 * content.
 *
 * So instead of implementing it here it's better to just re-throw exception and
 * let {@link RestExceptionTranslator} handle it and gracefully convert it into
 * json description of error happened
 */
protected ModelAndView buildJsonError(Throwable ex, HttpServletRequest req, HttpServletResponse res) {
    String msg = exceptionTranslator.buildUserMessage(ex, LocaleContextHolder.getLocale());
    NotAuthorizedException nae;
    FieldValidationException fve;
    AccessDeniedException ade;
    boolean translateAuthExc = Boolean.TRUE.equals(Boolean.valueOf(req.getHeader(RestExceptionTranslator.X_TRANSLATE_AUTHORIZATION_ERRORS)));
    if ((nae = ExceptionUtils.findExceptionOfType(ex, NotAuthorizedException.class)) != null) {
        NotAuthorizedResult naeResult = nae.getResult();
        res.setStatus(isAnonymous() ? HttpServletResponse.SC_UNAUTHORIZED : HttpServletResponse.SC_FORBIDDEN);
        if (translateAuthExc) {
            return new ModelAndView(jsonView, ControllerBase.ATTR_EXCEPTION, msg);
        } else {
            respondWithJson(naeResult, res);
            return null;
        }
    } else if ((ade = ExceptionUtils.findExceptionOfType(ex, AccessDeniedException.class)) != null) {
        res.setStatus(isAnonymous() ? HttpServletResponse.SC_UNAUTHORIZED : HttpServletResponse.SC_FORBIDDEN);
        if (translateAuthExc) {
            return new ModelAndView(jsonView, ControllerBase.ATTR_EXCEPTION, msg);
        } else {
            respondWithJson(new NotAuthorizedResult(getCurrentUser(), SecurityMessageCodes.ACCESS_DENIED), res);
            return null;
        }
    } else if ((fve = ExceptionUtils.findExceptionOfType(ex, FieldValidationException.class)) != null) {
        res.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        ValidationErrorsVm vepm = new ValidationErrorsVm(fve.getErrors());
        return new ModelAndView(jsonView, ControllerBase.ATTR_VALIDATION_ERRORS, vepm.getMsg());
    }
    log.warn("Failed to process request", ex);
    res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    return new ModelAndView(jsonView, ControllerBase.ATTR_EXCEPTION, msg);
}
Also used : FieldValidationException(org.summerb.approaches.validation.FieldValidationException) AccessDeniedException(org.springframework.security.access.AccessDeniedException) ValidationErrorsVm(org.summerb.approaches.springmvc.model.ValidationErrorsVm) ModelAndView(org.springframework.web.servlet.ModelAndView) NotAuthorizedResult(org.summerb.approaches.security.api.dto.NotAuthorizedResult) NotAuthorizedException(org.summerb.approaches.security.api.exceptions.NotAuthorizedException)

Aggregations

NotAuthorizedException (org.summerb.approaches.security.api.exceptions.NotAuthorizedException)4 AccessDeniedException (org.springframework.security.access.AccessDeniedException)2 EntityNotFoundException (org.summerb.approaches.jdbccrud.api.exceptions.EntityNotFoundException)2 Query (org.summerb.approaches.jdbccrud.api.query.Query)2 Preconditions (com.google.common.base.Preconditions)1 Arrays (java.util.Arrays)1 List (java.util.List)1 Function (java.util.function.Function)1 Collectors (java.util.stream.Collectors)1 BeansException (org.springframework.beans.BeansException)1 InitializingBean (org.springframework.beans.factory.InitializingBean)1 Autowired (org.springframework.beans.factory.annotation.Autowired)1 ApplicationContext (org.springframework.context.ApplicationContext)1 ApplicationContextAware (org.springframework.context.ApplicationContextAware)1 MediaType (org.springframework.http.MediaType)1 AuthenticationException (org.springframework.security.core.AuthenticationException)1 CollectionUtils (org.springframework.util.CollectionUtils)1 DeleteMapping (org.springframework.web.bind.annotation.DeleteMapping)1 GetMapping (org.springframework.web.bind.annotation.GetMapping)1 ModelAttribute (org.springframework.web.bind.annotation.ModelAttribute)1