Search in sources :

Example 21 with RestValidationFailedException

use of com.serotonin.m2m2.web.mvc.rest.v1.exception.RestValidationFailedException in project ma-modules-public by infiniteautomation.

the class UserRestController method updateUser.

@ApiOperation(value = "Updates a user")
@RequestMapping(method = RequestMethod.PUT, consumes = { "application/json", "text/csv" }, produces = { "application/json", "text/csv" }, value = "/{username}")
public ResponseEntity<UserModel> updateUser(@PathVariable String username, @RequestBody(required = true) UserModel model, UriComponentsBuilder builder, 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();
            }
            // Cannot make yourself disabled or not admin
            if (user.getId() == u.getId()) {
                if (!(authentication instanceof UsernamePasswordAuthenticationToken)) {
                    throw new AccessDeniedException(new TranslatableMessage("rest.error.usernamePasswordOnly"));
                }
                boolean failed = false;
                if (!model.isAdmin()) {
                    model.addValidationMessage(new ProcessMessage("permissions", new TranslatableMessage("users.validate.adminInvalid")));
                    failed = true;
                }
                if (model.getDisabled()) {
                    model.addValidationMessage(new ProcessMessage("disabled", new TranslatableMessage("users.validate.adminDisable")));
                    failed = true;
                }
                if (failed) {
                    result.addRestMessage(getValidationFailedError());
                    return result.createResponseEntity(model);
                }
            }
            // Cannot Rename a User to an existing Username
            if (!model.getUsername().equals(username)) {
                User existingUser = UserDao.instance.getUser(model.getUsername());
                if (existingUser != null) {
                    model.addValidationMessage(new ProcessMessage("username", new TranslatableMessage("users.validate.usernameInUse")));
                    result.addRestMessage(getValidationFailedError());
                    return result.createResponseEntity(model);
                }
            }
            // Set the ID for the user for validation
            model.getData().setId(u.getId());
            if (!model.validate()) {
                result.addRestMessage(this.getValidationFailedError());
            } else {
                User newUser = model.getData();
                newUser.setId(u.getId());
                if (!StringUtils.isBlank(model.getData().getPassword()))
                    newUser.setPassword(Common.encrypt(model.getData().getPassword()));
                else
                    newUser.setPassword(u.getPassword());
                UserDao.instance.saveUser(newUser);
                sessionRegistry.userUpdated(request, newUser);
            }
            return result.createResponseEntity(model);
        } else {
            if (u.getId() != user.getId()) {
                LOG.warn("Non admin user: " + user.getUsername() + " attempted to update user : " + u.getUsername());
                result.addRestMessage(this.getUnauthorizedMessage());
                return result.createResponseEntity();
            } else {
                if (!(authentication instanceof UsernamePasswordAuthenticationToken)) {
                    throw new AccessDeniedException(new TranslatableMessage("rest.error.usernamePasswordOnly"));
                }
                // Allow users to update themselves
                User newUser = model.getData();
                newUser.setId(u.getId());
                if (!StringUtils.isBlank(model.getData().getPassword()))
                    newUser.setPassword(Common.encrypt(model.getData().getPassword()));
                else
                    newUser.setPassword(u.getPassword());
                // If we are not Admin we cannot modify our own privs
                if (!u.isAdmin()) {
                    if (!StringUtils.equals(u.getPermissions(), newUser.getPermissions())) {
                        model.addValidationMessage(new ProcessMessage("permissions", new TranslatableMessage("users.validate.cannotChangePermissions")));
                        result.addRestMessage(this.getValidationFailedError());
                        return result.createResponseEntity(model);
                    }
                }
                if (!model.validate()) {
                    result.addRestMessage(this.getValidationFailedError());
                } else {
                    // Cannot make yourself disabled admin or not admin
                    boolean failed = false;
                    if (user.getId() == u.getId()) {
                        if (model.getDisabled()) {
                            model.addValidationMessage(new ProcessMessage("disabled", new TranslatableMessage("users.validate.adminDisable")));
                            failed = true;
                        }
                        if (u.isAdmin()) {
                            // We were superadmin, so we must still have it
                            if (!model.getData().isAdmin()) {
                                model.addValidationMessage(new ProcessMessage("permissions", new TranslatableMessage("users.validate.adminInvalid")));
                                failed = true;
                            }
                        } else {
                            // We were not superadmin so we must not have it
                            if (model.getData().isAdmin()) {
                                model.addValidationMessage(new ProcessMessage("permissions", new TranslatableMessage("users.validate.adminGrantInvalid")));
                                failed = true;
                            }
                        }
                        if (failed) {
                            result.addRestMessage(getValidationFailedError());
                            return result.createResponseEntity(model);
                        }
                    }
                    UserDao.instance.saveUser(newUser);
                    sessionRegistry.userUpdated(request, newUser);
                    URI location = builder.path("v1/users/{username}").buildAndExpand(model.getUsername()).toUri();
                    result.addRestMessage(getResourceCreatedMessage(location));
                }
                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) ProcessMessage(com.serotonin.m2m2.i18n.ProcessMessage) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) URI(java.net.URI) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 22 with RestValidationFailedException

use of com.serotonin.m2m2.web.mvc.rest.v1.exception.RestValidationFailedException in project ma-modules-public by infiniteautomation.

the class WatchListRestController method get.

@ApiOperation(value = "Get a Watchlist", notes = "", response = WatchListModel.class)
@RequestMapping(method = RequestMethod.GET, produces = { "application/json", "text/csv" }, value = "/{xid}")
public ResponseEntity<WatchListModel> get(@PathVariable String xid, HttpServletRequest request) throws RestValidationFailedException {
    RestProcessResult<WatchListModel> result = new RestProcessResult<WatchListModel>(HttpStatus.OK);
    try {
        User user = this.checkUser(request, result);
        if (result.isOk()) {
            WatchListVO wl = this.dao.getByXid(xid);
            if (wl == null) {
                result.addRestMessage(getDoesNotExistMessage());
                return result.createResponseEntity();
            }
            if (hasReadPermission(user, wl)) {
                List<WatchListDataPointModel> points = this.dao.getPointSummaries(wl.getId());
                // Filter them on read permission
                ListIterator<WatchListDataPointModel> it = points.listIterator();
                while (it.hasNext()) {
                    if (!Permissions.hasPermission(user, it.next().getReadPermission()))
                        it.remove();
                }
                return result.createResponseEntity(new WatchListModel(wl, points));
            } else {
                result.addRestMessage(getUnauthorizedMessage());
            }
        }
    } catch (Exception e) {
        LOG.warn(e.getMessage(), e);
        result.addRestMessage(getInternalServerErrorMessage(e.getMessage()));
    }
    return result.createResponseEntity();
}
Also used : RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) WatchListDataPointModel(com.serotonin.m2m2.web.mvc.rest.v1.model.WatchListDataPointModel) User(com.serotonin.m2m2.vo.User) WatchListModel(com.serotonin.m2m2.web.mvc.rest.v1.model.WatchListModel) RestValidationFailedException(com.serotonin.m2m2.web.mvc.rest.v1.exception.RestValidationFailedException) InvalidRQLRestException(com.infiniteautomation.mango.rest.v2.exception.InvalidRQLRestException) IOException(java.io.IOException) WatchListVO(com.serotonin.m2m2.watchlist.WatchListVO) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 23 with RestValidationFailedException

use of com.serotonin.m2m2.web.mvc.rest.v1.exception.RestValidationFailedException in project ma-modules-public by infiniteautomation.

the class WatchListRestController method delete.

@ApiOperation(value = "Delete a WatchList ", notes = "Only the owner or an admin can delete", response = WatchListModel.class)
@RequestMapping(method = RequestMethod.DELETE, consumes = { "application/*" }, produces = { "*/*" }, value = "/{xid}")
public ResponseEntity<Void> delete(@PathVariable String xid, HttpServletRequest request) throws RestValidationFailedException {
    RestProcessResult<Void> result = new RestProcessResult<Void>(HttpStatus.OK);
    try {
        User user = this.checkUser(request, result);
        if (result.isOk()) {
            WatchListVO wl = this.dao.getByXid(xid);
            if (wl == null) {
                result.addRestMessage(getDoesNotExistMessage());
                return result.createResponseEntity();
            }
            if (isOwner(user, wl)) {
                String initiatorId = request.getHeader("initiatorId");
                this.dao.delete(wl.getId(), initiatorId);
                result.addRestMessage(HttpStatus.NO_CONTENT, new TranslatableMessage("common.deleted"));
                return result.createResponseEntity();
            } else {
                result.addRestMessage(this.getUnauthorizedMessage());
                return result.createResponseEntity();
            }
        }
    } catch (Exception e) {
        LOG.warn(e.getMessage(), e);
        result.addRestMessage(getInternalServerErrorMessage(e.getMessage()));
    }
    return result.createResponseEntity();
}
Also used : RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) User(com.serotonin.m2m2.vo.User) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) RestValidationFailedException(com.serotonin.m2m2.web.mvc.rest.v1.exception.RestValidationFailedException) InvalidRQLRestException(com.infiniteautomation.mango.rest.v2.exception.InvalidRQLRestException) IOException(java.io.IOException) WatchListVO(com.serotonin.m2m2.watchlist.WatchListVO) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

RestProcessResult (com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult)22 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)21 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)21 User (com.serotonin.m2m2.vo.User)20 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)12 RestValidationFailedException (com.serotonin.m2m2.web.mvc.rest.v1.exception.RestValidationFailedException)10 InvalidRQLRestException (com.infiniteautomation.mango.rest.v2.exception.InvalidRQLRestException)7 URI (java.net.URI)6 UserModel (com.serotonin.m2m2.web.mvc.rest.v1.model.user.UserModel)5 IOException (java.io.IOException)5 AccessDeniedException (com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException)4 WatchListVO (com.serotonin.m2m2.watchlist.WatchListVO)4 ProcessMessage (com.serotonin.m2m2.i18n.ProcessMessage)3 ProcessResult (com.serotonin.m2m2.i18n.ProcessResult)3 RestValidationMessage (com.serotonin.m2m2.web.mvc.rest.v1.message.RestValidationMessage)3 WatchListDataPointModel (com.serotonin.m2m2.web.mvc.rest.v1.model.WatchListDataPointModel)3 WatchListModel (com.serotonin.m2m2.web.mvc.rest.v1.model.WatchListModel)3 ThreadPoolSettingsModel (com.serotonin.m2m2.web.mvc.rest.v1.model.backgroundProcessing.ThreadPoolSettingsModel)3 UserCommentModel (com.serotonin.m2m2.web.mvc.rest.v1.model.comment.UserCommentModel)3 ApiResponses (com.wordnik.swagger.annotations.ApiResponses)3