Search in sources :

Example 41 with Permissions

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

the class UserCommentRestController method deleteUserComment.

@ApiOperation(value = "Delete A User Comment by XID")
@RequestMapping(method = RequestMethod.DELETE, produces = { "application/json" }, value = "/{xid}")
public ResponseEntity<UserCommentModel> deleteUserComment(@ApiParam(value = "xid", required = true, allowMultiple = false) @PathVariable String xid, 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();
        }
        // Check permissions
        if (hasEditPermission(u, user)) {
            // Delete it
            String initiatorId = request.getHeader("initiatorId");
            UserCommentDao.instance.delete(u.getId(), initiatorId);
        } else {
            LOG.warn("Non admin user: " + user.getUsername() + " attempted to delete user comment : " + u.getUsername());
            result.addRestMessage(this.getUnauthorizedMessage());
        }
    }
    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) UserCommentVO(com.serotonin.m2m2.vo.comment.UserCommentVO) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 42 with Permissions

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

the class AuditRestController method queryRQL.

@ApiOperation(value = "Query Audit Events", notes = "Admin access only", response = AuditEventInstanceModel.class, responseContainer = "Array")
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<PageQueryStream<AuditEventInstanceVO, AuditEventInstanceModel, AuditEventDao>> queryRQL(HttpServletRequest request) {
    RestProcessResult<PageQueryStream<AuditEventInstanceVO, AuditEventInstanceModel, AuditEventDao>> result = new RestProcessResult<PageQueryStream<AuditEventInstanceVO, AuditEventInstanceModel, AuditEventDao>>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        try {
            if (!user.isAdmin()) {
                result.addRestMessage(getUnauthorizedMessage());
                return result.createResponseEntity();
            } else {
                // Limit our results based on the fact that our permissions should be in the permissions strings
                ASTNode root = parseRQLtoAST(request.getQueryString());
                return result.createResponseEntity(getPageStream(root));
            }
        } catch (InvalidRQLRestException e) {
            result.addRestMessage(getInternalServerErrorMessage(e.getMessage()));
            return result.createResponseEntity();
        }
    }
    return result.createResponseEntity();
}
Also used : AuditEventInstanceModel(com.serotonin.m2m2.web.mvc.rest.v1.model.audit.AuditEventInstanceModel) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) User(com.serotonin.m2m2.vo.User) InvalidRQLRestException(com.infiniteautomation.mango.rest.v2.exception.InvalidRQLRestException) ASTNode(net.jazdw.rql.parser.ASTNode) AuditEventDao(com.serotonin.m2m2.db.dao.AuditEventDao) PageQueryStream(com.serotonin.m2m2.web.mvc.rest.v1.model.PageQueryStream) AuditEventInstanceVO(com.serotonin.m2m2.vo.event.audit.AuditEventInstanceVO) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 43 with Permissions

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

the class ScriptUtilRestController method testScript.

@PreAuthorize("isAdmin()")
@ApiOperation(value = "Test a script")
@ApiResponses({ @ApiResponse(code = 401, message = "Unauthorized user access", response = ResponseEntity.class), @ApiResponse(code = 500, message = "Error processing request", response = ResponseEntity.class) })
@RequestMapping(method = RequestMethod.POST, value = { "/test" }, consumes = { "application/json" }, produces = { "application/json" })
public ResponseEntity<ScriptRestResult> testScript(@AuthenticationPrincipal User user, @RequestBody ScriptRestModel scriptModel) {
    if (LOG.isDebugEnabled())
        LOG.debug("Testing script for: " + user.getName());
    Map<String, IDataPointValueSource> context = convertContextModel(scriptModel.getContext(), true);
    try {
        CompiledScript script = CompiledScriptExecutor.compile(scriptModel.getScript());
        final StringWriter scriptOut = new StringWriter();
        final PrintWriter scriptWriter = new PrintWriter(scriptOut);
        int logLevel = ScriptLog.LogLevel.FATAL;
        if (StringUtils.isEmpty(scriptModel.getLogLevel())) {
            int levelId = ScriptLog.LOG_LEVEL_CODES.getId(scriptModel.getLogLevel());
            if (levelId == -1)
                throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, new TranslatableMessage("rest.script.error.unknownLogLevel", scriptModel.getLogLevel()));
            else
                logLevel = levelId;
        }
        ScriptLog scriptLog = new ScriptLog(scriptWriter, logLevel);
        final ScriptPermissions permissions = scriptModel.getPermissions().toPermissions();
        final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYY HH:mm:ss");
        ScriptPointValueSetter loggingSetter = new ScriptPointValueSetter(permissions) {

            @Override
            public void set(IDataPointValueSource point, Object value, long timestamp, String annotation) {
                DataPointRT dprt = (DataPointRT) point;
                if (!dprt.getVO().getPointLocator().isSettable()) {
                    scriptOut.append("Point " + dprt.getVO().getExtendedName() + " not settable.");
                    return;
                }
                if (!Permissions.hasPermission(dprt.getVO().getSetPermission(), permissions.getDataPointSetPermissions())) {
                    scriptOut.write(new TranslatableMessage("pointLinks.setTest.permissionDenied", dprt.getVO().getXid()).translate(Common.getTranslations()));
                    return;
                }
                scriptOut.append("Setting point " + dprt.getVO().getName() + " to " + value + " @" + sdf.format(new Date(timestamp)) + "\r\n");
            }

            @Override
            protected void setImpl(IDataPointValueSource point, Object value, long timestamp, String annotation) {
            // not really setting
            }
        };
        try {
            PointValueTime pvt = CompiledScriptExecutor.execute(script, context, new HashMap<String, Object>(), Common.timer.currentTimeMillis(), DataTypes.ALPHANUMERIC, Common.timer.currentTimeMillis(), permissions, scriptWriter, scriptLog, loggingSetter, null, true);
            if (LOG.isDebugEnabled())
                LOG.debug("Script output: " + scriptOut.toString());
            return new ResponseEntity<>(new ScriptRestResult(scriptOut.toString(), new PointValueTimeModel(pvt)), HttpStatus.OK);
        } catch (ResultTypeException e) {
            throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, e);
        }
    } catch (ScriptException e) {
        throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, e);
    }
}
Also used : CompiledScript(javax.script.CompiledScript) ScriptPointValueSetter(com.serotonin.m2m2.rt.script.ScriptPointValueSetter) PointValueTimeModel(com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.PointValueTimeModel) ScriptLog(com.serotonin.m2m2.rt.script.ScriptLog) ScriptPermissions(com.serotonin.m2m2.rt.script.ScriptPermissions) Date(java.util.Date) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) ScriptException(javax.script.ScriptException) ResponseEntity(org.springframework.http.ResponseEntity) StringWriter(java.io.StringWriter) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) SimpleDateFormat(java.text.SimpleDateFormat) GenericRestException(com.infiniteautomation.mango.rest.v2.exception.GenericRestException) PrintWriter(java.io.PrintWriter) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) ApiResponses(com.wordnik.swagger.annotations.ApiResponses) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 44 with Permissions

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

the class ScriptUtilRestController method runScript.

@PreAuthorize("isAdmin()")
@ApiOperation(value = "Run a script")
@ApiResponses({ @ApiResponse(code = 401, message = "Unauthorized user access", response = ResponseEntity.class), @ApiResponse(code = 500, message = "Error processing request", response = ResponseEntity.class) })
@RequestMapping(method = RequestMethod.POST, value = { "/run" }, consumes = { "application/json" }, produces = { "application/json" })
public ResponseEntity<ScriptRestResult> runScript(@AuthenticationPrincipal User user, @RequestBody ScriptRestModel scriptModel) {
    if (LOG.isDebugEnabled())
        LOG.debug("Running script for: " + user.getName());
    Map<String, IDataPointValueSource> context = convertContextModel(scriptModel.getContext(), false);
    try {
        CompiledScript script = CompiledScriptExecutor.compile(scriptModel.getScript());
        final StringWriter scriptOut = new StringWriter();
        final PrintWriter scriptWriter = new PrintWriter(scriptOut);
        int logLevel = ScriptLog.LogLevel.FATAL;
        if (StringUtils.isEmpty(scriptModel.getLogLevel())) {
            int levelId = ScriptLog.LOG_LEVEL_CODES.getId(scriptModel.getLogLevel());
            if (levelId == -1)
                throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, new TranslatableMessage("rest.script.error.unknownLogLevel", scriptModel.getLogLevel()));
            else
                logLevel = levelId;
        }
        ScriptLog scriptLog = new ScriptLog(scriptWriter, logLevel);
        ScriptPermissions permissions = scriptModel.getPermissions().toPermissions();
        try {
            PointValueTime pvt = CompiledScriptExecutor.execute(script, context, new HashMap<String, Object>(), Common.timer.currentTimeMillis(), DataTypes.ALPHANUMERIC, Common.timer.currentTimeMillis(), permissions, scriptWriter, scriptLog, new SetCallback(permissions, user), null, false);
            if (LOG.isDebugEnabled())
                LOG.debug("Script output: " + scriptOut.toString());
            return new ResponseEntity<>(new ScriptRestResult(scriptOut.toString(), new PointValueTimeModel(pvt)), HttpStatus.OK);
        } catch (ResultTypeException | ScriptPermissionsException e) {
            throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, e);
        }
    } catch (ScriptException e) {
        throw new GenericRestException(HttpStatus.INTERNAL_SERVER_ERROR, e);
    }
}
Also used : CompiledScript(javax.script.CompiledScript) PointValueTimeModel(com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.PointValueTimeModel) ScriptLog(com.serotonin.m2m2.rt.script.ScriptLog) ScriptPermissions(com.serotonin.m2m2.rt.script.ScriptPermissions) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) ScriptException(javax.script.ScriptException) ResponseEntity(org.springframework.http.ResponseEntity) StringWriter(java.io.StringWriter) ScriptPermissionsException(com.serotonin.m2m2.rt.script.ScriptPermissionsException) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) GenericRestException(com.infiniteautomation.mango.rest.v2.exception.GenericRestException) PrintWriter(java.io.PrintWriter) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) ApiResponses(com.wordnik.swagger.annotations.ApiResponses) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 45 with Permissions

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

the class DataPointRestController method doQuery.

private static StreamedArrayWithTotal doQuery(ASTNode rql, User user) {
    if (user.isAdmin()) {
        return new StreamedVOQueryWithTotal<>(DataPointDao.instance, rql, item -> {
            DataPointDao.instance.loadPartialRelationalData(item);
            return new DataPointModel(item);
        });
    } else {
        // Add some conditions to restrict based on user permissions
        ConditionSortLimitWithTagKeys conditions = DataPointDao.instance.rqlToCondition(rql);
        conditions.addCondition(DataPointDao.instance.userHasPermission(user));
        DataPointFilter dataPointFilter = new DataPointFilter(user);
        return new StreamedVOQueryWithTotal<>(DataPointDao.instance, conditions, item -> {
            boolean oldFilterMatches = dataPointFilter.hasDataPointReadPermission(item);
            // this is just a double check, permissions should be accounted for via SQL restrictions added by DataPointDao.userHasPermission()
            if (!oldFilterMatches) {
                throw new RuntimeException("Data point does not match old permission filter");
            }
            return true;
        }, item -> {
            DataPointDao.instance.loadPartialRelationalData(item);
            return new DataPointModel(item);
        });
    }
}
Also used : StreamedVOQueryWithTotal(com.infiniteautomation.mango.rest.v2.model.StreamedVOQueryWithTotal) DataPointModel(com.infiniteautomation.mango.rest.v2.model.dataPoint.DataPointModel) ConditionSortLimitWithTagKeys(com.infiniteautomation.mango.db.query.ConditionSortLimitWithTagKeys) DataPointFilter(com.serotonin.m2m2.web.mvc.rest.v1.model.dataPoint.DataPointFilter)

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