Search in sources :

Example 11 with RestValidationFailedException

use of com.serotonin.m2m2.web.mvc.rest.v1.exception.RestValidationFailedException 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 12 with RestValidationFailedException

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

the class UserRestController method createNewUser.

/**
 * Create a new User
 * @param model
 * @param request
 * @return
 * @throws RestValidationFailedException
 */
@ApiOperation(value = "Create New User", notes = "Cannot save existing user")
@ApiResponses({ @ApiResponse(code = 201, message = "User Created", response = UserModel.class), @ApiResponse(code = 401, message = "Unauthorized Access", response = ResponseEntity.class), @ApiResponse(code = 409, message = "User Already Exists") })
@RequestMapping(method = RequestMethod.POST, consumes = { "application/json", "text/csv" }, produces = { "application/json", "text/csv" })
public ResponseEntity<UserModel> createNewUser(@ApiParam(value = "User to save", required = true) @RequestBody(required = true) UserModel model, UriComponentsBuilder builder, HttpServletRequest request) throws RestValidationFailedException {
    RestProcessResult<UserModel> result = new RestProcessResult<UserModel>(HttpStatus.CREATED);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        User u = UserDao.instance.getUser(model.getUsername());
        if (Permissions.hasAdmin(user)) {
            if (u == null) {
                // Create new user
                model.getData().setId(Common.NEW_ID);
                if (model.validate()) {
                    try {
                        User newUser = model.getData();
                        newUser.setPassword(Common.encrypt(model.getData().getPassword()));
                        UserDao.instance.saveUser(newUser);
                        URI location = builder.path("v1/users/{username}").buildAndExpand(model.getUsername()).toUri();
                        result.addRestMessage(getResourceCreatedMessage(location));
                        return result.createResponseEntity(model);
                    } catch (Exception e) {
                        result.addRestMessage(getInternalServerErrorMessage(e.getMessage()));
                        return result.createResponseEntity();
                    }
                } else {
                    result.addRestMessage(this.getValidationFailedError());
                    return result.createResponseEntity(model);
                }
            } else {
                model.addValidationMessage(new ProcessMessage("username", new TranslatableMessage("users.validate.usernameInUse")));
                result.addRestMessage(getValidationFailedError());
                return result.createResponseEntity(model);
            }
        } else {
            LOG.warn("Non admin user: " + user.getUsername() + " attempted to create user : " + model.getUsername());
            result.addRestMessage(this.getUnauthorizedMessage());
            return result.createResponseEntity();
        }
    }
    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) User(com.serotonin.m2m2.vo.User) ProcessMessage(com.serotonin.m2m2.i18n.ProcessMessage) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) URI(java.net.URI) RestValidationFailedException(com.serotonin.m2m2.web.mvc.rest.v1.exception.RestValidationFailedException) InvalidRQLRestException(com.infiniteautomation.mango.rest.v2.exception.InvalidRQLRestException) AccessDeniedException(com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException) NotFoundRestException(com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) ApiResponses(com.wordnik.swagger.annotations.ApiResponses) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 13 with RestValidationFailedException

use of com.serotonin.m2m2.web.mvc.rest.v1.exception.RestValidationFailedException 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 14 with RestValidationFailedException

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

the class UserRestController method deleteUser.

@ApiOperation(value = "Delete A User")
@RequestMapping(method = RequestMethod.DELETE, produces = { "application/json", "text/csv" }, value = "/{username}")
public ResponseEntity<UserModel> deleteUser(@ApiParam(value = "Username", required = true, allowMultiple = false) @PathVariable String username, HttpServletRequest request) 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 (u == null) {
            result.addRestMessage(getDoesNotExistMessage());
            return result.createResponseEntity();
        }
        UserModel model = new UserModel(u);
        if (Permissions.hasAdmin(user)) {
            if (u.getId() == user.getId()) {
                model.addValidationMessage(new ProcessMessage("username", new TranslatableMessage("users.validate.badDelete")));
                result.addRestMessage(getValidationFailedError());
                return result.createResponseEntity(model);
            }
            UserDao.instance.deleteUser(u.getId());
            return result.createResponseEntity(model);
        } else {
            LOG.warn("Non admin user: " + user.getUsername() + " attempted to delete user : " + u.getUsername());
            result.addRestMessage(this.getUnauthorizedMessage());
        }
    }
    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) User(com.serotonin.m2m2.vo.User) ProcessMessage(com.serotonin.m2m2.i18n.ProcessMessage) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 15 with RestValidationFailedException

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

the class JsonEmportV2Controller method uploadConfigurationFile.

@PreAuthorize("isAdmin()")
@ApiOperation(value = "Upload 1 configuration json file", notes = "Files should only contain the json object to be imported")
@RequestMapping(method = RequestMethod.POST, value = "/upload-file", consumes = { "multipart/form-data", "multipart/form-data;boundary=-----SWAG_BOUND" })
public ResponseEntity<ImportStatusProvider> uploadConfigurationFile(MultipartHttpServletRequest multipartRequest, UriComponentsBuilder builder, HttpServletRequest request, @ApiParam(value = "timeout for Status Resource to Expire, defaults to 5 minutes", required = false, allowMultiple = false) @RequestParam(value = "timeout", required = false) Long timeout, @AuthenticationPrincipal User user) throws RestValidationFailedException, IOException, JsonException {
    Map<String, MultipartFile> map = multipartRequest.getFileMap();
    if (map.size() != 1)
        throw new BadRequestException(new TranslatableMessage("rest.error.oneFileOnly"));
    Iterator<String> itr = multipartRequest.getFileNames();
    MultipartFile file = multipartRequest.getFile(itr.next());
    if (!file.isEmpty()) {
        JsonReader jr = new JsonReader(Common.JSON_CONTEXT, new String(file.getBytes()));
        JsonObject jo = jr.read(JsonObject.class);
        String resourceId = importStatusResources.generateResourceId();
        ImportStatusProvider statusProvider = new ImportStatusProvider(importStatusResources, resourceId, websocket, timeout, jo, user);
        // Setup the Temporary Resource
        this.importStatusResources.put(resourceId, statusProvider);
        URI location = builder.path("/v2/json-emport/import/{id}").buildAndExpand(resourceId).toUri();
        return getResourceCreated(statusProvider, location);
    } else {
        throw new BadRequestException(new TranslatableMessage("rest.error.noFileProvided"));
    }
}
Also used : MultipartFile(org.springframework.web.multipart.MultipartFile) BadRequestException(com.infiniteautomation.mango.rest.v2.exception.BadRequestException) JsonReader(com.serotonin.json.JsonReader) JsonObject(com.serotonin.json.type.JsonObject) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) URI(java.net.URI) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) 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