Search in sources :

Example 1 with PermissionException

use of com.serotonin.m2m2.vo.permission.PermissionException in project ma-core-public by infiniteautomation.

the class UrlSecurityFilter method doFilter.

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    // Assume an http request.
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    boolean foundMapping = false;
    User user = Common.getHttpUser();
    String msg;
    String uri = request.getRequestURI();
    for (UriMappingDefinition uriDef : ModuleRegistry.getDefinitions(UriMappingDefinition.class)) {
        if (matcher.match(uriDef.getPath(), uri)) {
            boolean allowed = true;
            foundMapping = true;
            switch(uriDef.getPermission()) {
                case ADMINISTRATOR:
                    if ((user == null) || (!Permissions.hasAdmin(user)))
                        allowed = false;
                    break;
                case DATA_SOURCE:
                    if ((user == null) || (!user.isDataSourcePermission()))
                        allowed = false;
                    break;
                case USER:
                    if (user == null) {
                        allowed = false;
                    }
                    break;
                case CUSTOM:
                    try {
                        allowed = uriDef.hasCustomPermission(user);
                    } catch (PermissionException e) {
                        allowed = false;
                    }
                    break;
                case ANONYMOUS:
                    break;
            }
            if (!allowed) {
                if (user == null) {
                    msg = "Denying access to page where user isn't logged in, uri=" + uri + ", remote host ip= " + request.getRemoteHost();
                } else {
                    msg = "Denying access to page where user hasn't sufficient permission, user=" + user.getUsername() + ", uri=" + uri + ", remote host ip= " + request.getRemoteHost();
                }
                LOG.warn(msg);
                throw new AccessDeniedException(msg);
            }
            break;
        }
    }
    // if not set then check our other definitions
    if (!foundMapping) {
        for (ControllerMappingDefinition uriDef : ModuleRegistry.getDefinitions(ControllerMappingDefinition.class)) {
            if (matcher.match(uriDef.getPath(), uri)) {
                boolean allowed = true;
                foundMapping = true;
                switch(uriDef.getPermission()) {
                    case ADMINISTRATOR:
                        if ((user == null) || (!Permissions.hasAdmin(user)))
                            allowed = false;
                        break;
                    case DATA_SOURCE:
                        if ((user == null) || (!user.isDataSourcePermission()))
                            allowed = false;
                        break;
                    case USER:
                        if (user == null) {
                            allowed = false;
                        }
                        break;
                    case CUSTOM:
                        try {
                            allowed = uriDef.hasCustomPermission(user);
                        } catch (PermissionException e) {
                            allowed = false;
                        }
                        break;
                    case ANONYMOUS:
                        break;
                }
                if (!allowed) {
                    if (user == null) {
                        msg = "Denying access to page where user isn't logged in, uri=" + uri + ", remote host ip= " + request.getRemoteHost();
                    } else {
                        msg = "Denying access to page where user hasn't sufficient permission, user=" + user.getUsername() + ", uri=" + uri + ", remote host ip= " + request.getRemoteHost();
                    }
                    LOG.info(msg);
                    throw new AccessDeniedException(msg);
                }
                break;
            }
        }
    }
    // if not set then check our other definitions
    if (!foundMapping) {
        for (UrlMappingDefinition uriDef : ModuleRegistry.getDefinitions(UrlMappingDefinition.class)) {
            if (matcher.match(uriDef.getUrlPath(), uri)) {
                boolean allowed = true;
                foundMapping = true;
                switch(uriDef.getPermission()) {
                    case ADMINISTRATOR:
                        if ((user == null) || (!Permissions.hasAdmin(user)))
                            allowed = false;
                        break;
                    case DATA_SOURCE:
                        if ((user == null) || (!user.isDataSourcePermission()))
                            allowed = false;
                        break;
                    case USER:
                        if (user == null) {
                            allowed = false;
                        }
                        break;
                    case ANONYMOUS:
                        break;
                }
                if (!allowed) {
                    if (user == null) {
                        msg = "Denying access to page where user isn't logged in, uri=" + uri + ", remote host ip= " + request.getRemoteHost();
                    } else {
                        msg = "Denying access to page where user hasn't sufficient permission, user=" + user.getUsername() + ", uri=" + uri + ", remote host ip= " + request.getRemoteHost();
                    }
                    LOG.info(msg);
                    throw new AccessDeniedException(msg);
                }
                break;
            }
        }
    }
    filterChain.doFilter(servletRequest, servletResponse);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) AccessDeniedException(org.springframework.security.access.AccessDeniedException) User(com.serotonin.m2m2.vo.User) UriMappingDefinition(com.serotonin.m2m2.module.UriMappingDefinition) HttpServletResponse(javax.servlet.http.HttpServletResponse) ControllerMappingDefinition(com.serotonin.m2m2.module.ControllerMappingDefinition) UrlMappingDefinition(com.serotonin.m2m2.module.UrlMappingDefinition)

Example 2 with PermissionException

use of com.serotonin.m2m2.vo.permission.PermissionException in project ma-core-public by infiniteautomation.

the class DataPointDetailsController method handleRequest.

@Override
public View handleRequest(HttpServletRequest request, HttpServletResponse response, Map<String, Object> model) throws Exception {
    User user = Common.getHttpUser();
    int id = -1;
    if (user.getEditPoint() != null)
        id = user.getEditPoint().getId();
    DataPointDao dataPointDao = DataPointDao.instance;
    String idStr = request.getParameter("dpid");
    DataPointVO point = null;
    if (StringUtils.equals(idStr, "exception"))
        throw new IOException("testing");
    else if (StringUtils.equals(idStr, "permission-exception"))
        throw new PermissionException(new TranslatableMessage("common.default", "Testing"), user);
    if (StringUtils.isBlank(idStr)) {
        // Check for pedid (point event detector id)
        String pedStr = request.getParameter("pedid");
        if (StringUtils.isBlank(pedStr)) {
            // Check if an XID was provided.
            String xid = request.getParameter("dpxid");
            if (!StringUtils.isBlank(xid)) {
                model.put("currentXid", xid);
                point = dataPointDao.getDataPoint(xid);
                id = point == null ? -2 : point.getId();
            }
        } else {
            int pedid = Integer.parseInt(pedStr);
            id = EventDetectorDao.instance.getSourceId(pedid, EventType.EventTypeNames.DATA_POINT);
        }
    } else
        id = Integer.parseInt(idStr);
    // Find accessible points for the goto list
    List<DataPointSummary> userPoints = ControllerUtils.addPointListDataToModel(user, id, model);
    // Get the point.
    if (point == null && id != -1)
        point = dataPointDao.getDataPoint(id);
    if (point == null && id != -2 && /* -2 means an explicit XID was provided but not found */
    !userPoints.isEmpty()) {
        // Load at least 1 point, there may be many points but some might not actually load if thier data source DNE anymore
        for (DataPointSummary userPoint : userPoints) {
            point = dataPointDao.getDataPoint(userPoint.getId());
            if (point != null)
                break;
        }
    }
    if (point != null) {
        // Check permissions
        Permissions.ensureDataPointReadPermission(user, point);
        // Put the point in the model.
        model.put("point", point);
        // Get the users that have access to this point.
        List<User> allUsers = UserDao.instance.getUsers();
        List<Map<String, Object>> users = new LinkedList<>();
        Map<String, Object> userData;
        int accessType;
        for (User mangoUser : allUsers) {
            accessType = Permissions.getDataPointAccessType(mangoUser, point);
            if (accessType != Permissions.DataPointAccessTypes.NONE) {
                userData = new HashMap<>();
                userData.put("user", mangoUser);
                userData.put("accessType", accessType);
                users.add(userData);
            }
        }
        model.put("users", users);
        // Determine whether the link to edit the point should be displayed
        model.put("pointEditor", Permissions.hasDataSourcePermission(user, point.getDataSourceId()));
        // Put the events in the model.
        model.put("events", EventDao.instance.getEventsForDataPoint(id, user.getId()));
        // Put the default history table count into the model. Default to 10.
        int historyLimit = 10;
        if (point.getChartRenderer() instanceof TableChartRenderer)
            historyLimit = ((TableChartRenderer) point.getChartRenderer()).getLimit();
        else if (point.getChartRenderer() instanceof ImageFlipbookRenderer)
            historyLimit = ((ImageFlipbookRenderer) point.getChartRenderer()).getLimit();
        model.put("historyLimit", historyLimit);
        // Determine our image chart rendering capabilities.
        if (ImageChartRenderer.getDefinition().supports(point.getPointLocator().getDataTypeId())) {
            // This point can render an image chart. Carry on...
            int periodType = Common.TimePeriods.DAYS;
            int periodCount = 1;
            if (point.getChartRenderer() instanceof ImageChartRenderer) {
                ImageChartRenderer r = (ImageChartRenderer) point.getChartRenderer();
                periodType = r.getTimePeriod();
                periodCount = r.getNumberOfPeriods();
            }
            model.put("periodType", periodType);
            model.put("periodCount", periodCount);
        }
        // Determine out flipbook rendering capabilities
        if (ImageFlipbookRenderer.getDefinition().supports(point.getPointLocator().getDataTypeId()))
            model.put("flipbookLimit", 10);
        // Set the point in the session for the dwr.
        user.setEditPoint(point);
        model.put("currentXid", point.getXid());
        model.put("hierPath", CollectionUtils.implode(dataPointDao.getPointHierarchy(true).getPath(id), " &raquo; "));
    }
    return null;
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) TableChartRenderer(com.serotonin.m2m2.view.chart.TableChartRenderer) DataPointSummary(com.serotonin.m2m2.vo.DataPointSummary) User(com.serotonin.m2m2.vo.User) DataPointDao(com.serotonin.m2m2.db.dao.DataPointDao) IOException(java.io.IOException) ImageChartRenderer(com.serotonin.m2m2.view.chart.ImageChartRenderer) LinkedList(java.util.LinkedList) ImageFlipbookRenderer(com.serotonin.m2m2.view.chart.ImageFlipbookRenderer) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with PermissionException

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

the class DataPointSummaryStreamCallback method writeJson.

/**
 * Do the work of writing the VO
 * @param vo
 * @throws IOException
 */
@Override
protected void writeJson(DataPointVO vo) throws IOException {
    try {
        if (Permissions.hasDataPointReadPermission(user, vo)) {
            DataPointSummary model = this.controller.createModel(vo);
            this.jgen.writeObject(model);
        }
    } catch (PermissionException e) {
    // Munched
    }
}
Also used : PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) DataPointSummary(com.serotonin.m2m2.vo.DataPointSummary)

Example 4 with PermissionException

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

the class ReportVO method validate.

@Override
public void validate(ProcessResult response) {
    super.validate(response);
    if (points.isEmpty())
        response.addContextualMessage("points", "reports.validate.needPoint");
    if (dateRangeType != ReportVO.DATE_RANGE_TYPE_RELATIVE && dateRangeType != ReportVO.DATE_RANGE_TYPE_SPECIFIC)
        response.addGenericMessage("reports.validate.invalidDateRangeType");
    if (relativeDateType != ReportVO.RELATIVE_DATE_TYPE_PAST && relativeDateType != ReportVO.RELATIVE_DATE_TYPE_PREVIOUS)
        response.addGenericMessage("reports.validate.invalidRelativeDateType");
    if (previousPeriodCount < 1)
        response.addContextualMessage("previousPeriodCount", "reports.validate.periodCountLessThan1");
    if (pastPeriodCount < 1)
        response.addContextualMessage("pastPeriodCount", "reports.validate.periodCountLessThan1");
    UserDao dao = UserDao.instance;
    User user = dao.getUser(userId);
    if (user == null) {
        response.addContextualMessage("userId", "reports.validate.userDNE");
    }
    File t = ReportCommon.instance.getTemplateFile(template);
    if (!t.isFile())
        response.addContextualMessage("template", "reports.validate.template");
    DataPointDao dataPointDao = DataPointDao.instance;
    for (ReportPointVO point : points) {
        DataPointVO vo = dataPointDao.getDataPoint(point.getPointId(), false);
        String pointXid = "unknown";
        if (vo != null) {
            pointXid = vo.getXid();
            try {
                Permissions.ensureDataPointReadPermission(user, dataPointDao.getDataPoint(point.getPointId(), false));
            } catch (PermissionException e) {
                response.addContextualMessage("points", "reports.vaildate.pointDNE");
            }
        } else {
            response.addContextualMessage("points", "reports.validate.pointPermissions", user.getUsername(), pointXid);
        }
        try {
            if (!StringUtils.isBlank(point.getColour()))
                ColorUtils.toColor(point.getColour());
        } catch (InvalidArgumentException e) {
            response.addContextualMessage("points", "reports.validate.colour", point.getColour(), pointXid);
        }
        if (point.getWeight() <= 0)
            response.addContextualMessage("points", "reports.validate.weight");
    }
    // Validate the schedule
    if (schedule) {
        if (schedulePeriod == SCHEDULE_CRON) {
            try {
                new CronTimerTrigger(scheduleCron);
            } catch (ParseException e) {
                response.addContextualMessage("scheduleCron", "validate.invalidValue");
            }
        }
    }
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) User(com.serotonin.m2m2.vo.User) DataPointDao(com.serotonin.m2m2.db.dao.DataPointDao) InvalidArgumentException(com.serotonin.InvalidArgumentException) UserDao(com.serotonin.m2m2.db.dao.UserDao) CronTimerTrigger(com.serotonin.timer.CronTimerTrigger) ParseException(java.text.ParseException) File(java.io.File)

Example 5 with PermissionException

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

the class DataPointEventsByWatchlistQueryDefinition method createQuery.

/* (non-Javadoc)
     * @see com.serotonin.m2m2.module.ModuleQueryDefinition#createQuery(com.fasterxml.jackson.databind.JsonNode)
     */
@Override
public ASTNode createQuery(User user, JsonNode parameters) throws IOException {
    // Lookup data points by watchlist
    WatchListVO vo = WatchListDao.instance.getByXid(parameters.get("watchListXid").asText());
    if (vo == null)
        throw new NotFoundException();
    if (!WatchListRestController.hasReadPermission(user, vo))
        throw new PermissionException(new TranslatableMessage("common.default", "Unauthorized access"), user);
    List<Object> args = new ArrayList<>();
    args.add("typeRef1");
    WatchListDao.instance.getPoints(vo.getId(), new MappedRowCallback<DataPointVO>() {

        @Override
        public void row(DataPointVO dp, int index) {
            if (Permissions.hasDataPointReadPermission(user, dp)) {
                args.add(Integer.toString(dp.getId()));
            }
        }
    });
    // Create Event Query for these Points
    ASTNode query = new ASTNode("in", args);
    query = addAndRestriction(query, new ASTNode("eq", "userId", user.getId()));
    query = addAndRestriction(query, new ASTNode("eq", "typeName", "DATA_POINT"));
    // TODO Should we force a limit if none is supplied?
    if (parameters.has("limit")) {
        int offset = 0;
        int limit = parameters.get("limit").asInt();
        if (parameters.has("offset"))
            offset = parameters.get("offset").asInt();
        query = addAndRestriction(query, new ASTNode("limit", limit, offset));
    }
    return query;
}
Also used : PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) DataPointVO(com.serotonin.m2m2.vo.DataPointVO) ArrayList(java.util.ArrayList) ASTNode(net.jazdw.rql.parser.ASTNode) NotFoundException(com.serotonin.m2m2.vo.exception.NotFoundException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage)

Aggregations

PermissionException (com.serotonin.m2m2.vo.permission.PermissionException)42 User (com.serotonin.m2m2.vo.User)34 RestProcessResult (com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult)29 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)28 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)25 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)25 NotFoundRestException (com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException)13 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)12 ValidationFailedRestException (com.infiniteautomation.mango.rest.v2.exception.ValidationFailedRestException)11 RTException (com.serotonin.m2m2.rt.RTException)11 RestValidationFailedException (com.serotonin.m2m2.web.mvc.rest.v1.exception.RestValidationFailedException)11 RestValidationResult (com.infiniteautomation.mango.rest.v2.model.RestValidationResult)10 ArrayList (java.util.ArrayList)10 List (java.util.List)9 DataPointModel (com.serotonin.m2m2.web.mvc.rest.v1.model.DataPointModel)8 AbstractDataSourceModel (com.serotonin.m2m2.web.mvc.rest.v1.model.dataSource.AbstractDataSourceModel)7 RecentPointValueTimeModel (com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.RecentPointValueTimeModel)7 URI (java.net.URI)7 HashMap (java.util.HashMap)7 AnnotatedPointValueTime (com.serotonin.m2m2.rt.dataImage.AnnotatedPointValueTime)6