Search in sources :

Example 1 with AccessDeniedException

use of com.infiniteautomation.mango.rest.v2.exception.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 2 with AccessDeniedException

use of com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException in project ma-modules-public by infiniteautomation.

the class UserRestController method updateMuted.

@ApiOperation(value = "Update a user's audio mute setting", notes = "If you do not provide the mute parameter the current setting will be toggled")
@RequestMapping(method = RequestMethod.PUT, produces = { "application/json", "text/csv" }, value = "/{username}/mute")
public ResponseEntity<UserModel> updateMuted(@ApiParam(value = "Username", required = true, allowMultiple = false) @PathVariable String username, @ApiParam(value = "Mute", required = false, defaultValue = "Toggle the current setting", allowMultiple = false) @RequestParam(required = false) Boolean mute, HttpServletRequest request, Authentication authentication) throws RestValidationFailedException {
    RestProcessResult<UserModel> result = new RestProcessResult<UserModel>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        User u = UserDao.instance.getUser(username);
        if (Permissions.hasAdmin(user)) {
            if (u == null) {
                result.addRestMessage(getDoesNotExistMessage());
                return result.createResponseEntity();
            }
            if (u.getId() == user.getId() && !(authentication instanceof UsernamePasswordAuthenticationToken)) {
                throw new AccessDeniedException(new TranslatableMessage("rest.error.usernamePasswordOnly"));
            }
            if (mute == null) {
                u.setMuted(!u.isMuted());
            } else {
                u.setMuted(mute);
            }
            UserModel model = new UserModel(u);
            if (!model.validate()) {
                result.addRestMessage(this.getValidationFailedError());
            } else {
                UserDao.instance.saveUser(u);
                sessionRegistry.userUpdated(request, u);
            }
            return result.createResponseEntity(model);
        } else {
            if (u.getId() != user.getId()) {
                LOG.warn("Non admin user: " + user.getUsername() + " attempted to access user : " + u.getUsername());
                result.addRestMessage(this.getUnauthorizedMessage());
                return result.createResponseEntity();
            } else {
                if (mute == null) {
                    // Toggle
                    u.setMuted(!u.isMuted());
                } else {
                    u.setMuted(mute);
                }
                UserModel model = new UserModel(u);
                // Allow users to update themselves
                model.getData().setId(u.getId());
                if (!model.validate()) {
                    result.addRestMessage(this.getValidationFailedError());
                } else {
                    UserDao.instance.saveUser(u);
                    sessionRegistry.userUpdated(request, u);
                }
                return result.createResponseEntity(model);
            }
        }
    }
    return result.createResponseEntity();
}
Also used : UserModel(com.serotonin.m2m2.web.mvc.rest.v1.model.user.UserModel) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) AccessDeniedException(com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException) User(com.serotonin.m2m2.vo.User) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 3 with AccessDeniedException

use of com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException in project ma-modules-public by infiniteautomation.

the class UserRestController method updateHomeUrl.

@ApiOperation(value = "Update a user's home url")
@RequestMapping(method = RequestMethod.PUT, produces = { "application/json", "text/csv" }, value = "/{username}/homepage")
public ResponseEntity<UserModel> updateHomeUrl(@ApiParam(value = "Username", required = true, allowMultiple = false) @PathVariable String username, @ApiParam(value = "Home Url", required = true, allowMultiple = false) @RequestParam(required = true) String url, HttpServletRequest request, Authentication authentication) throws RestValidationFailedException {
    RestProcessResult<UserModel> result = new RestProcessResult<UserModel>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        User u = UserDao.instance.getUser(username);
        if (Permissions.hasAdmin(user)) {
            if (u == null) {
                result.addRestMessage(getDoesNotExistMessage());
                return result.createResponseEntity();
            }
            if (u.getId() == user.getId() && !(authentication instanceof UsernamePasswordAuthenticationToken)) {
                throw new AccessDeniedException(new TranslatableMessage("rest.error.usernamePasswordOnly"));
            }
            u.setHomeUrl(url);
            UserModel model = new UserModel(u);
            if (!model.validate()) {
                result.addRestMessage(this.getValidationFailedError());
            } else {
                UserDao.instance.saveHomeUrl(u.getId(), url);
                sessionRegistry.userUpdated(request, u);
            }
            return result.createResponseEntity(model);
        } else {
            if (u.getId() != user.getId()) {
                LOG.warn("Non admin user: " + user.getUsername() + " attempted to access user : " + u.getUsername());
                result.addRestMessage(this.getUnauthorizedMessage());
                return result.createResponseEntity();
            } else {
                u.setHomeUrl(url);
                UserModel model = new UserModel(u);
                // Allow users to update themselves
                model.getData().setId(u.getId());
                if (!model.validate()) {
                    result.addRestMessage(this.getValidationFailedError());
                } else {
                    // We have confirmed that we are the user
                    UserDao.instance.saveHomeUrl(u.getId(), url);
                    sessionRegistry.userUpdated(request, u);
                }
                return result.createResponseEntity(model);
            }
        }
    }
    return result.createResponseEntity();
}
Also used : UserModel(com.serotonin.m2m2.web.mvc.rest.v1.model.user.UserModel) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) AccessDeniedException(com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException) User(com.serotonin.m2m2.vo.User) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 4 with AccessDeniedException

use of com.infiniteautomation.mango.rest.v2.exception.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 5 with AccessDeniedException

use of com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException in project ma-modules-public by infiniteautomation.

the class PasswordResetController method createTokenForUser.

@ApiOperation(value = "Creates a password reset token and link for the given user")
@RequestMapping(method = RequestMethod.POST, value = "/create")
@PreAuthorize("isAdmin() and isPasswordAuthenticated()")
public CreateTokenResponse createTokenForUser(@RequestBody CreateTokenRequest requestBody, @AuthenticationPrincipal User currentUser) throws AddressException, TemplateException, IOException {
    String username = requestBody.getUsername();
    boolean lockPassword = requestBody.isLockPassword();
    boolean sendEmail = requestBody.isSendEmail();
    Date expiry = requestBody.getExpiry();
    User user = UserDao.instance.getUser(username);
    if (user == null) {
        throw new BadRequestException(new TranslatableMessage("rest.error.unknownUser", username));
    }
    if (user.getId() == currentUser.getId()) {
        throw new AccessDeniedException(new TranslatableMessage("rest.error.cantResetOwnUser"));
    }
    if (lockPassword) {
        UserDao.instance.lockPassword(user);
    }
    CreateTokenResponse response = new CreateTokenResponse();
    String token = passwordResetService.generateToken(user, expiry);
    response.setToken(token);
    response.setFullUrl(passwordResetService.generateResetUrl(token));
    response.setRelativeUrl(passwordResetService.generateRelativeResetUrl(token));
    if (sendEmail) {
        passwordResetService.sendEmail(user, token);
    }
    return response;
}
Also used : AccessDeniedException(com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException) User(com.serotonin.m2m2.vo.User) BadRequestException(com.infiniteautomation.mango.rest.v2.exception.BadRequestException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) Date(java.util.Date) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

AccessDeniedException (com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException)10 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)10 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)10 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)7 User (com.serotonin.m2m2.vo.User)7 NotFoundRestException (com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException)4 RestProcessResult (com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult)4 BadRequestException (com.infiniteautomation.mango.rest.v2.exception.BadRequestException)3 UserModel (com.serotonin.m2m2.web.mvc.rest.v1.model.user.UserModel)3 ResponseEntity (org.springframework.http.ResponseEntity)3 AccessDeniedException (org.springframework.security.access.AccessDeniedException)3 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)3 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)3 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)2 PermissionException (com.serotonin.m2m2.vo.permission.PermissionException)2 File (java.io.File)2 Date (java.util.Date)2 AbstractRestV2Exception (com.infiniteautomation.mango.rest.v2.exception.AbstractRestV2Exception)1 InvalidRQLRestException (com.infiniteautomation.mango.rest.v2.exception.InvalidRQLRestException)1 ResourceNotFoundException (com.infiniteautomation.mango.rest.v2.exception.ResourceNotFoundException)1