Search in sources :

Example 41 with AccessDeniedException

use of org.springframework.security.access.AccessDeniedException in project vaadin-jsf-integration by alejandro-du.

the class SignupForm method save.

public String save() throws Exception {
    user.setEnabled(true);
    // Set the default user role on this new user
    user.addRole(roleManager.getRole(Constants.USER_ROLE));
    try {
        user = userManager.saveUser(user);
    } catch (AccessDeniedException ade) {
        // thrown by UserSecurityAdvice configured in aop:advisor userManagerSecurity
        log.warn(ade.getMessage());
        getResponse().sendError(HttpServletResponse.SC_FORBIDDEN);
        return null;
    } catch (UserExistsException e) {
        addMessage("errors.existing.user", new Object[] { user.getUsername(), user.getEmail() });
        // redisplay the unencrypted passwords
        user.setPassword(user.getConfirmPassword());
        return null;
    }
    addMessage("user.registered");
    getSession().setAttribute(Constants.REGISTERED, Boolean.TRUE);
    // log user in automatically
    UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getConfirmPassword(), user.getAuthorities());
    auth.setDetails(user);
    SecurityContextHolder.getContext().setAuthentication(auth);
    // Send an account information e-mail
    message.setSubject(getText("signup.email.subject"));
    try {
        sendUserMessage(user, getText("signup.email.message"), RequestUtil.getAppURL(getRequest()));
    } catch (MailException me) {
        addError(me.getMostSpecificCause().getMessage());
        return null;
    }
    return "home";
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) UserExistsException(org.appfuse.service.UserExistsException) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) MailException(org.springframework.mail.MailException)

Example 42 with AccessDeniedException

use of org.springframework.security.access.AccessDeniedException in project ma-modules-public by infiniteautomation.

the class LoggingRestController method query.

@PreAuthorize("isAdmin()")
@ApiOperation(value = "Query ma.log logs", notes = "Returns a list of recent logs, ie. /by-filename/ma.log?limit(10)\n" + "<br>Query Examples: \n" + "by-filename/ma.log/?level=gt=DEBUG\n" + "by-filename/ma.log/?thread=qtp-1\n" + "by-filename/ma.log/?message=setPointValue\n" + "NOTE: Querying non ma.log files is not supported.")
@RequestMapping(method = RequestMethod.GET, produces = { "application/json" }, value = "/by-filename/{filename}")
public ResponseEntity<QueryArrayStream<?>> query(@PathVariable String filename, HttpServletRequest request) {
    RestProcessResult<QueryArrayStream<?>> result = new RestProcessResult<QueryArrayStream<?>>(HttpStatus.OK);
    try {
        ASTNode query = parseRQLtoAST(request.getQueryString());
        File file = new File(Common.getLogsDir(), filename);
        if (file.exists()) {
            // Pattern pattern = new
            if (filename.matches(LogQueryArrayStream.LOGFILE_REGEX)) {
                LogQueryArrayStream stream = new LogQueryArrayStream(filename, query);
                return result.createResponseEntity(stream);
            } else {
                throw new AccessDeniedException("Non ma.log files are not accessible on this endpoint.");
            }
        } else {
            result.addRestMessage(getDoesNotExistMessage());
        }
    } catch (InvalidRQLRestException e) {
        LOG.error(e.getMessage(), e);
        result.addRestMessage(getInternalServerErrorMessage(e.getMessage()));
        return result.createResponseEntity();
    }
    return result.createResponseEntity();
}
Also used : RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) AccessDeniedException(org.springframework.security.access.AccessDeniedException) InvalidRQLRestException(com.infiniteautomation.mango.rest.v2.exception.InvalidRQLRestException) ASTNode(net.jazdw.rql.parser.ASTNode) QueryArrayStream(com.serotonin.m2m2.web.mvc.rest.v1.model.QueryArrayStream) LogQueryArrayStream(com.serotonin.m2m2.web.mvc.rest.v1.model.logging.LogQueryArrayStream) File(java.io.File) LogQueryArrayStream(com.serotonin.m2m2.web.mvc.rest.v1.model.logging.LogQueryArrayStream) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 43 with AccessDeniedException

use of org.springframework.security.access.AccessDeniedException in project ma-modules-public by infiniteautomation.

the class FileStoreRestV2Controller method download.

@ApiOperation(value = "List a directory or download a file from a store")
@RequestMapping(method = RequestMethod.GET, produces = {}, value = "/{name}/**")
public ResponseEntity<?> download(@ApiParam(value = "Valid File Store name", required = true, allowMultiple = false) @PathVariable("name") String name, @ApiParam(value = "Set content disposition to attachment", required = false, defaultValue = "true", allowMultiple = false) @RequestParam(required = false, defaultValue = "true") boolean download, @AuthenticationPrincipal User user, HttpServletRequest request, HttpServletResponse response) throws IOException, HttpMediaTypeNotAcceptableException {
    FileStoreDefinition def = ModuleRegistry.getFileStoreDefinition(name);
    if (def == null)
        throw new ResourceNotFoundException("File store: " + name);
    // Check permissions
    def.ensureStoreReadPermission(user);
    File root = def.getRoot().getCanonicalFile();
    String path = parsePath(request);
    File file = new File(root, path).getCanonicalFile();
    if (!file.toPath().startsWith(root.toPath())) {
        throw new AccessDeniedException("Path is below file store root");
    }
    // TODO Allow downloading directory as a zip
    if (file.isFile()) {
        return getFile(file, download, request, response);
    } else {
        return listStoreContents(file, root, request);
    }
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) ResourceNotFoundException(com.infiniteautomation.mango.rest.v2.exception.ResourceNotFoundException) File(java.io.File) CommonsMultipartFile(org.springframework.web.multipart.commons.CommonsMultipartFile) MultipartFile(org.springframework.web.multipart.MultipartFile) FileStoreDefinition(com.serotonin.m2m2.module.FileStoreDefinition) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 44 with AccessDeniedException

use of org.springframework.security.access.AccessDeniedException in project ma-modules-public by infiniteautomation.

the class FileStoreRestV2Controller method list.

@ApiOperation(value = "List all file store names", notes = "Must have read access to see the store")
@RequestMapping(method = RequestMethod.GET, produces = { "application/json" })
public ResponseEntity<List<String>> list(@AuthenticationPrincipal User user, HttpServletRequest request) {
    Map<String, FileStoreDefinition> defs = ModuleRegistry.getFileStoreDefinitions();
    List<String> accessible = new ArrayList<String>(defs.size());
    if (user.isAdmin()) {
        // admin users don't need to filter the results
        for (FileStoreDefinition def : defs.values()) {
            def.ensureStoreReadPermission(user);
            accessible.add(def.getStoreName());
        }
    } else {
        for (FileStoreDefinition def : defs.values()) {
            try {
                def.ensureStoreReadPermission(user);
                accessible.add(def.getStoreName());
            } catch (AccessDeniedException e) {
            }
        }
    }
    return new ResponseEntity<>(accessible, HttpStatus.OK);
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) ResponseEntity(org.springframework.http.ResponseEntity) ArrayList(java.util.ArrayList) FileStoreDefinition(com.serotonin.m2m2.module.FileStoreDefinition) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 45 with AccessDeniedException

use of org.springframework.security.access.AccessDeniedException in project alien4cloud by alien4cloud.

the class LocationPolicyValidationService method validateLocationPolicies.

public List<LocationPolicyTask> validateLocationPolicies(DeploymentMatchingConfiguration matchingConfiguration) {
    List<LocationPolicyTask> tasks = Lists.newArrayList();
    Location location = null;
    Orchestrator orchestrator = null;
    // TODO change this later, as now we only support one location policy and only for _A4C_ALL group
    String locationId = safe(matchingConfiguration.getLocationIds()).get(AlienConstants.GROUP_ALL);
    if (StringUtils.isBlank(locationId)) {
        tasks.add(new LocationPolicyTask());
    } else {
        location = locationService.getOrFail(locationId);
        orchestrator = orchestratorService.getOrFail(location.getOrchestratorId());
        try {
            // if a location already exists, then check the rigths on it
            locationSecurityService.checkAuthorisation(location, matchingConfiguration.getEnvironmentId());
            if (!Objects.equals(orchestrator.getState(), OrchestratorState.CONNECTED)) {
                UnavailableLocationTask task = new UnavailableLocationTask(location.getName(), orchestrator.getName());
                task.setCode(TaskCode.LOCATION_DISABLED);
                tasks.add(task);
            }
        } catch (AccessDeniedException e) {
            UnavailableLocationTask task = new UnavailableLocationTask(location.getName(), orchestrator.getName());
            task.setCode(TaskCode.LOCATION_UNAUTHORIZED);
            tasks.add(task);
        }
    }
    return tasks;
}
Also used : AccessDeniedException(org.springframework.security.access.AccessDeniedException) LocationPolicyTask(alien4cloud.topology.task.LocationPolicyTask) UnavailableLocationTask(alien4cloud.topology.task.UnavailableLocationTask) Orchestrator(alien4cloud.model.orchestrators.Orchestrator) Location(alien4cloud.model.orchestrators.locations.Location)

Aggregations

AccessDeniedException (org.springframework.security.access.AccessDeniedException)186 Test (org.junit.Test)33 Test (org.junit.jupiter.api.Test)20 Authentication (org.springframework.security.core.Authentication)18 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)17 ArrayList (java.util.ArrayList)15 ApplicationUser (org.finra.herd.model.dto.ApplicationUser)14 SecurityUserWrapper (org.finra.herd.model.dto.SecurityUserWrapper)14 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)14 AbstractServiceTest (org.finra.herd.service.AbstractServiceTest)13 Method (java.lang.reflect.Method)12 JoinPoint (org.aspectj.lang.JoinPoint)11 MethodSignature (org.aspectj.lang.reflect.MethodSignature)11 SecurityContext (org.springframework.security.core.context.SecurityContext)11 NamespaceAuthorization (org.finra.herd.model.api.xml.NamespaceAuthorization)10 Credential (com.sequenceiq.cloudbreak.domain.Credential)8 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)8 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)8 WebMessageException (org.hisp.dhis.dxf2.webmessage.WebMessageException)7 Interpretation (org.hisp.dhis.interpretation.Interpretation)7