Search in sources :

Example 66 with Permissions

use of com.serotonin.m2m2.vo.permission.Permissions in project ma-modules-public by infiniteautomation.

the class JsonDataRestController method modifyJsonData.

/**
 * Helper to modify data
 * @param result
 * @param xid
 * @param path
 * @param readPermissions
 * @param editPermissions
 * @param name
 * @param data
 * @param builder
 * @param request
 * @return
 */
private ResponseEntity<JsonDataModel> modifyJsonData(MapOperation operation, RestProcessResult<JsonDataModel> result, String xid, String[] pathParts, Set<String> readPermissions, Set<String> editPermissions, String name, boolean publicData, JsonNode data, UriComponentsBuilder builder, HttpServletRequest request) {
    // check we are using this method only for replace and append
    if (operation != MapOperation.REPLACE && operation != MapOperation.APPEND)
        throw new IllegalArgumentException();
    User user = this.checkUser(request, result);
    if (!result.isOk()) {
        return result.createResponseEntity();
    }
    JsonNode dataToReturn = data;
    JsonDataVO vo = this.dao.getByXid(xid);
    if (vo != null) {
        // Check existing permissions
        if (!Permissions.hasPermission(user, vo.getEditPermission())) {
            result.addRestMessage(getUnauthorizedMessage());
            return result.createResponseEntity();
        }
        // Replace the data
        vo.setName(name);
        vo.setPublicData(publicData);
        vo.setReadPermission(Permissions.implodePermissionGroups(readPermissions));
        vo.setEditPermission(Permissions.implodePermissionGroups(editPermissions));
        JsonNode existingData = (JsonNode) vo.getJsonData();
        if (operation == MapOperation.REPLACE) {
            JsonNode newData = replaceNode(existingData, pathParts, data);
            vo.setJsonData(newData);
        } else if (operation == MapOperation.APPEND) {
            dataToReturn = mergeNode(existingData, pathParts, data);
        }
    } else {
        // can't append/merge to a non-existing object or replace data at a path of a non existing object
        if (operation == MapOperation.APPEND || pathParts.length > 0) {
            result.addRestMessage(getDoesNotExistMessage());
            return result.createResponseEntity();
        }
        // Going to create a new one
        vo = new JsonDataVO();
        vo.setXid(xid);
        vo.setName(name);
        vo.setPublicData(publicData);
        vo.setReadPermission(Permissions.implodePermissionGroups(readPermissions));
        vo.setEditPermission(Permissions.implodePermissionGroups(editPermissions));
        vo.setJsonData(data);
    }
    JsonDataModel model = new JsonDataModel(vo);
    if (!model.validate()) {
        result.addRestMessage(this.getValidationFailedError());
        // return only the data that was saved, i.e. the data that we supplied a path to
        vo.setJsonData(data);
        return result.createResponseEntity(model);
    }
    // Ensure we have the correct permissions
    // First we must check to ensure that the User actually has editPermission before they can save it otherwise
    // they won't be able to modify it.
    Set<String> userPermissions = Permissions.explodePermissionGroups(user.getPermissions());
    if (!user.isAdmin() && Collections.disjoint(userPermissions, editPermissions)) {
        // Return validation error
        result.addRestMessage(this.getValidationFailedError());
        model.addValidationMessage("jsonData.editPermissionRequired", RestMessageLevel.ERROR, "editPermission");
        vo.setJsonData(data);
        return result.createResponseEntity(model);
    }
    try {
        String initiatorId = request.getHeader("initiatorId");
        this.dao.save(vo, initiatorId);
        // return only the data that was saved, i.e. the data that we supplied a path to
        vo.setJsonData(dataToReturn);
        URI location = builder.path("/v1/json-data/{xid}").buildAndExpand(new Object[] { vo.getXid() }).toUri();
        result.addRestMessage(this.getResourceCreatedMessage(location));
        return result.createResponseEntity(model);
    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
        result.addRestMessage(getInternalServerErrorMessage(e.getMessage()));
    }
    return result.createResponseEntity();
}
Also used : User(com.serotonin.m2m2.vo.User) JsonDataVO(com.serotonin.m2m2.vo.json.JsonDataVO) JsonDataModel(com.serotonin.m2m2.web.mvc.rest.v1.model.jsondata.JsonDataModel) JsonNode(com.fasterxml.jackson.databind.JsonNode) URI(java.net.URI) BadRequestException(com.infiniteautomation.mango.rest.v2.exception.BadRequestException) RestValidationFailedException(com.serotonin.m2m2.web.mvc.rest.v1.exception.RestValidationFailedException) NotFoundRestException(com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 67 with Permissions

use of com.serotonin.m2m2.vo.permission.Permissions in project ma-modules-public by infiniteautomation.

the class PointHierarchyRestController method getPath.

/**
 * Get a path to a folder
 * @param xid
 * @param request
 * @return
 */
@ApiOperation(value = "Get path to a point using point's XID", notes = "Points returned based on user priviledges")
@RequestMapping(method = RequestMethod.GET, value = "/path/{xid}", produces = { "application/json" })
public ResponseEntity<List<String>> getPath(@PathVariable String xid, HttpServletRequest request) {
    RestProcessResult<List<String>> result = new RestProcessResult<List<String>>(HttpStatus.OK);
    PointHierarchy ph = DataPointDao.instance.getPointHierarchy(true);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        DataPointVO vo = DataPointDao.instance.getByXid(xid);
        if (vo == null) {
            result.addRestMessage(getDoesNotExistMessage());
            return result.createResponseEntity();
        }
        // Check permissions
        try {
            if (!Permissions.hasDataPointReadPermission(user, vo)) {
                result.addRestMessage(getUnauthorizedMessage());
                return result.createResponseEntity();
            } else {
                return result.createResponseEntity(ph.getPath(vo.getId()));
            }
        } catch (PermissionException e) {
            result.addRestMessage(getUnauthorizedMessage());
            return result.createResponseEntity();
        }
    } else {
        return result.createResponseEntity();
    }
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) User(com.serotonin.m2m2.vo.User) PointHierarchy(com.serotonin.m2m2.vo.hierarchy.PointHierarchy) List(java.util.List) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 68 with Permissions

use of com.serotonin.m2m2.vo.permission.Permissions in project ma-modules-public by infiniteautomation.

the class UserCommentRestController method updateUserComment.

@ApiOperation(value = "Updates a user comment")
@RequestMapping(method = RequestMethod.PUT, consumes = { "application/json" }, produces = { "application/json" }, value = "/{xid}")
public ResponseEntity<UserCommentModel> updateUserComment(@PathVariable String xid, @RequestBody(required = true) UserCommentModel model, UriComponentsBuilder builder, HttpServletRequest request) throws RestValidationFailedException {
    RestProcessResult<UserCommentModel> result = new RestProcessResult<UserCommentModel>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        UserCommentVO u = UserCommentDao.instance.getByXid(xid);
        if (u == null) {
            result.addRestMessage(getDoesNotExistMessage());
            return result.createResponseEntity();
        } else {
            // Change the owner
            if (model.getUserId() == 0) {
                model.setUserId(user.getId());
                model.setUsername(user.getUsername());
            }
            // Check permissions
            if (hasEditPermission(model.getData(), user)) {
                // Validate and Update
                if (!model.validate()) {
                    result.addRestMessage(this.getValidationFailedError());
                } else {
                    UserCommentDao.instance.save(model.getData());
                    URI location = builder.path("v1/comments/{xid}").buildAndExpand(model.getXid()).toUri();
                    result.addRestMessage(getResourceUpdatedMessage(location));
                }
                return result.createResponseEntity(model);
            } else {
                result.addRestMessage(this.getUnauthorizedMessage());
                return result.createResponseEntity();
            }
        }
    }
    return result.createResponseEntity();
}
Also used : RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) User(com.serotonin.m2m2.vo.User) UserCommentModel(com.serotonin.m2m2.web.mvc.rest.v1.model.comment.UserCommentModel) URI(java.net.URI) UserCommentVO(com.serotonin.m2m2.vo.comment.UserCommentVO) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 69 with Permissions

use of com.serotonin.m2m2.vo.permission.Permissions in project ma-modules-public by infiniteautomation.

the class UserRestController method getUserPermissions.

@ApiOperation(value = "Get User Permissions Information for all users", notes = "", response = PermissionDetails.class, responseContainer = "Array")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Ok", response = PermissionDetails.class), @ApiResponse(code = 403, message = "User does not have access", response = ResponseEntity.class) })
@RequestMapping(method = RequestMethod.GET, produces = { "application/json" }, value = "/permissions")
public ResponseEntity<List<PermissionDetails>> getUserPermissions(HttpServletRequest request) {
    RestProcessResult<List<PermissionDetails>> result = new RestProcessResult<List<PermissionDetails>>(HttpStatus.OK);
    User currentUser = this.checkUser(request, result);
    if (result.isOk()) {
        List<PermissionDetails> ds = new ArrayList<>();
        for (User user : UserDao.instance.getActiveUsers()) {
            PermissionDetails deets = Permissions.getPermissionDetails(currentUser, null, user);
            if (deets != null)
                ds.add(deets);
        }
        return result.createResponseEntity(ds);
    }
    return result.createResponseEntity();
}
Also used : RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) User(com.serotonin.m2m2.vo.User) PermissionDetails(com.serotonin.m2m2.vo.permission.PermissionDetails) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) ApiResponses(com.wordnik.swagger.annotations.ApiResponses) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 70 with Permissions

use of com.serotonin.m2m2.vo.permission.Permissions in project ma-modules-public by infiniteautomation.

the class UserRestController method getAllUserGroups.

@ApiOperation(value = "Get All User Groups that a user can 'see', Optionally excluding groups", notes = "", response = String.class, responseContainer = "Array")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Ok", response = String.class), @ApiResponse(code = 403, message = "User does not have access", response = ResponseEntity.class) })
@RequestMapping(method = RequestMethod.GET, produces = { "application/json" }, value = "/permissions-groups/{exclude}")
public ResponseEntity<Set<String>> getAllUserGroups(@ApiParam(value = "Exclude Groups comma separated", required = false, allowMultiple = false, defaultValue = "") @PathVariable String exclude, HttpServletRequest request) {
    RestProcessResult<Set<String>> result = new RestProcessResult<Set<String>>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        Set<String> groups = new TreeSet<>();
        if (user.isAdmin()) {
            for (User u : UserDao.instance.getActiveUsers()) groups.addAll(Permissions.explodePermissionGroups(u.getPermissions()));
        } else {
            groups.addAll(Permissions.explodePermissionGroups(user.getPermissions()));
        }
        if (!StringUtils.isEmpty(exclude)) {
            for (String part : exclude.split(",")) groups.remove(part);
        }
        return result.createResponseEntity(groups);
    }
    return result.createResponseEntity();
}
Also used : RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) TreeSet(java.util.TreeSet) Set(java.util.Set) User(com.serotonin.m2m2.vo.User) TreeSet(java.util.TreeSet) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) ApiResponses(com.wordnik.swagger.annotations.ApiResponses) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

User (com.serotonin.m2m2.vo.User)61 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)43 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)43 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)40 RestProcessResult (com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult)36 ArrayList (java.util.ArrayList)27 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)20 PermissionException (com.serotonin.m2m2.vo.permission.PermissionException)17 DwrPermission (com.serotonin.m2m2.web.dwr.util.DwrPermission)16 NotFoundRestException (com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException)15 HashMap (java.util.HashMap)15 List (java.util.List)14 ProcessResult (com.serotonin.m2m2.i18n.ProcessResult)10 ASTNode (net.jazdw.rql.parser.ASTNode)10 PointValueTime (com.serotonin.m2m2.rt.dataImage.PointValueTime)9 RestValidationFailedException (com.serotonin.m2m2.web.mvc.rest.v1.exception.RestValidationFailedException)8 DataPointModel (com.serotonin.m2m2.web.mvc.rest.v1.model.DataPointModel)8 URI (java.net.URI)8 Map (java.util.Map)8 ResponseEntity (org.springframework.http.ResponseEntity)7