Search in sources :

Example 16 with Permissions

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

the class JsonConfigImportWebSocketHandler method afterConnectionEstablished.

@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
    // Check for permissions
    User user = this.getUser(session);
    if (user == null) {
        return;
    } else if (!user.isAdmin()) {
        if (session.isOpen()) {
            session.close(MangoWebSocketPublisher.NOT_AUTHORIZED);
        }
        return;
    }
    super.afterConnectionEstablished(session);
    sessions.add(session);
}
Also used : User(com.serotonin.m2m2.vo.User)

Example 17 with Permissions

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

the class PointValueWebSocketHandler method handleTextMessage.

@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) {
    try {
        User user = getUser(session);
        if (user == null) {
            return;
        }
        PointValueRegistrationModel model = this.jacksonMapper.readValue(message.getPayload(), PointValueRegistrationModel.class);
        // Handle message.getPayload() here
        DataPointVO vo = DataPointDao.instance.getByXid(model.getDataPointXid());
        if (vo == null) {
            this.sendErrorMessage(session, MangoWebSocketErrorType.SERVER_ERROR, new TranslatableMessage("rest.error.pointNotFound", model.getDataPointXid()));
            return;
        }
        // Check permissions
        if (!Permissions.hasDataPointReadPermission(user, vo)) {
            this.sendErrorMessage(session, MangoWebSocketErrorType.PERMISSION_DENIED, new TranslatableMessage("permission.exception.readDataPoint", user.getUsername()));
            return;
        }
        Set<PointValueEventType> eventsTypes = model.getEventTypes();
        int dataPointId = vo.getId();
        synchronized (pointIdToListenerMap) {
            if (this.connectionClosed) {
                return;
            }
            PointValueWebSocketListener publisher = pointIdToListenerMap.get(dataPointId);
            if (publisher != null) {
                if (eventsTypes.isEmpty()) {
                    publisher.terminate();
                    pointIdToListenerMap.remove(dataPointId);
                } else {
                    publisher.setEventTypes(eventsTypes);
                }
            } else if (!eventsTypes.isEmpty()) {
                publisher = new PointValueWebSocketListener(vo, eventsTypes);
                publisher.initialize();
                // Immediately send the most recent Point Value and the status of the data point
                publisher.sendPointStatus();
                pointIdToListenerMap.put(dataPointId, publisher);
            }
        }
    } catch (Exception e) {
        // TODO Mango 3.4 add new exception type for closed session and don't try and send error if it was a closed session exception
        try {
            this.sendErrorMessage(session, MangoWebSocketErrorType.SERVER_ERROR, new TranslatableMessage("rest.error.serverError", e.getMessage()));
        } catch (Exception e1) {
            log.error(e.getMessage(), e);
        }
    }
    if (log.isDebugEnabled())
        log.debug(message.getPayload());
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) User(com.serotonin.m2m2.vo.User) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 18 with Permissions

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

the class PointLinksDwr method validateScript.

@DwrPermission(user = true)
public ProcessResult validateScript(String script, int sourcePointId, int targetPointId, ScriptPermissions permissions, int logLevel) {
    ProcessResult response = new ProcessResult();
    TranslatableMessage message;
    DataPointRT source = Common.runtimeManager.getDataPoint(sourcePointId);
    if (source == null) {
        DataPointVO sourceVo = DataPointDao.instance.getDataPoint(sourcePointId, false);
        if (sourceVo == null) {
            message = new TranslatableMessage("pointLinks.validate.sourceRequired");
            response.addMessage("script", message);
            return response;
        }
        if (sourceVo.getDefaultCacheSize() == 0)
            sourceVo.setDefaultCacheSize(1);
        source = new DataPointRT(sourceVo, sourceVo.getPointLocator().createRuntime(), DataSourceDao.instance.getDataSource(sourceVo.getDataSourceId()), null);
        source.resetValues();
    }
    DataPointRT target = Common.runtimeManager.getDataPoint(targetPointId);
    if (target == null) {
        DataPointVO targetVo = DataPointDao.instance.getDataPoint(targetPointId, false);
        if (targetVo == null) {
            message = new TranslatableMessage("pointLinks.validate.targetRequired");
            response.addMessage("script", message);
            return response;
        }
        if (targetVo.getDefaultCacheSize() == 0)
            targetVo.setDefaultCacheSize(1);
        target = new DataPointRT(targetVo, targetVo.getPointLocator().createRuntime(), DataSourceDao.instance.getDataSource(targetVo.getDataSourceId()), null);
        target.resetValues();
    }
    Map<String, IDataPointValueSource> context = new HashMap<String, IDataPointValueSource>();
    context.put(PointLinkRT.CONTEXT_SOURCE_VAR_NAME, source);
    context.put(PointLinkRT.CONTEXT_TARGET_VAR_NAME, target);
    int targetDataType = target.getDataTypeId();
    final StringWriter scriptOut = new StringWriter();
    final PrintWriter scriptWriter = new PrintWriter(scriptOut);
    ScriptLog scriptLog = new ScriptLog(scriptWriter, logLevel);
    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 {
        CompiledScript compiledScript = CompiledScriptExecutor.compile(script);
        PointValueTime pvt = CompiledScriptExecutor.execute(compiledScript, context, null, System.currentTimeMillis(), targetDataType, -1, permissions, scriptWriter, scriptLog, loggingSetter, null, true);
        if (pvt.getValue() == null)
            message = new TranslatableMessage("event.pointLink.nullResult");
        else if (pvt.getValue() == CompiledScriptExecutor.UNCHANGED)
            message = new TranslatableMessage("pointLinks.validate.successNoValue");
        else if (pvt.getTime() == -1)
            message = new TranslatableMessage("pointLinks.validate.success", pvt.getValue());
        else
            message = new TranslatableMessage("pointLinks.validate.successTs", pvt.getValue(), Functions.getTime(pvt.getTime()));
        // Add the script logging output
        response.addData("out", scriptOut.toString().replaceAll("\n", "<br/>"));
    } catch (ScriptException e) {
        message = new TranslatableMessage("pointLinks.validate.scriptError", e.getMessage());
    } catch (ResultTypeException e) {
        message = e.getTranslatableMessage();
    }
    response.addMessage("script", message);
    return response;
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) CompiledScript(javax.script.CompiledScript) ScriptPointValueSetter(com.serotonin.m2m2.rt.script.ScriptPointValueSetter) HashMap(java.util.HashMap) ProcessResult(com.serotonin.m2m2.i18n.ProcessResult) ScriptLog(com.serotonin.m2m2.rt.script.ScriptLog) Date(java.util.Date) ScriptException(javax.script.ScriptException) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) StringWriter(java.io.StringWriter) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) SimpleDateFormat(java.text.SimpleDateFormat) PrintWriter(java.io.PrintWriter) DwrPermission(com.serotonin.m2m2.web.dwr.util.DwrPermission)

Example 19 with Permissions

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

the class WatchListVO method validate.

public void validate(ProcessResult response) {
    if (StringUtils.isBlank(name))
        response.addMessage("name", new TranslatableMessage("validate.required"));
    else if (StringValidation.isLengthGreaterThan(name, 50))
        response.addMessage("name", new TranslatableMessage("validate.notLongerThan", 50));
    if (StringUtils.isBlank(xid))
        response.addMessage("xid", new TranslatableMessage("validate.required"));
    else if (StringValidation.isLengthGreaterThan(xid, 50))
        response.addMessage("xid", new TranslatableMessage("validate.notLongerThan", 50));
    else if (!WatchListDao.instance.isXidUnique(xid, id))
        response.addMessage("xid", new TranslatableMessage("validate.xidUsed"));
    // Validate the points
    UserDao dao = UserDao.instance;
    User user = dao.getUser(userId);
    if (user == null) {
        response.addContextualMessage("userId", "watchlists.validate.userDNE");
    }
    // Using the owner of the report to validate against permissions if there is no current user
    User currentUser = Common.getUser();
    if (currentUser == null)
        currentUser = user;
    // Validate Points
    for (DataPointVO vo : pointList) try {
        Permissions.ensureDataPointReadPermission(user, vo);
    } catch (PermissionException e) {
        response.addContextualMessage("points", "watchlist.vaildate.pointNoReadPermission", vo.getXid());
    }
    // Validate the permissions
    Permissions.validateAddedPermissions(this.readPermission, currentUser, response, "readPermission");
    Permissions.validateAddedPermissions(this.editPermission, currentUser, response, "editPermission");
// TODO Validate new members
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) User(com.serotonin.m2m2.vo.User) UserDao(com.serotonin.m2m2.db.dao.UserDao) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage)

Example 20 with Permissions

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

the class WatchListHandler method prepareModel.

protected void prepareModel(HttpServletRequest request, Map<String, Object> model, User user) {
    // The user's permissions may have changed since the last session, so make sure the watch lists are correct.
    List<WatchListVO> watchLists = WatchListDao.instance.getWatchLists(user);
    if (watchLists.size() == 0) {
        // Add a default watch list if none exist.
        WatchListVO watchList = new WatchListVO();
        watchList.setName(ControllerUtils.getTranslations(request).translate("common.newName"));
        watchLists.add(WatchListDao.instance.createNewWatchList(watchList, user.getId()));
    }
    int selected = 0;
    WatchListVO selectedWatchList = WatchListDao.instance.getSelectedWatchList(user.getId());
    if (selectedWatchList != null)
        selected = selectedWatchList.getId();
    // Check if a parameter was provided.
    String wlid = request.getParameter("wlid");
    if (!StringUtils.isBlank(wlid)) {
        try {
            selected = Integer.parseInt(wlid);
        } catch (NumberFormatException e) {
        // ignore
        }
    }
    String wlxid = request.getParameter("wlxid");
    UserDao userDao = UserDao.instance;
    boolean found = false;
    List<Map<String, String>> watchListsData = new ArrayList<Map<String, String>>(watchLists.size());
    List<IntStringPair> watchListUsers = new ArrayList<>(watchLists.size());
    List<IntStringPair> userWatchLists = new ArrayList<>(watchLists.size());
    Set<String> users = new HashSet<String>();
    for (WatchListVO watchList : watchLists) {
        if (!found) {
            if (StringUtils.equals(watchList.getXid(), wlxid)) {
                found = true;
                selected = watchList.getId();
            } else if (watchList.getId() == selected)
                found = true;
        }
        if (watchList.isOwner(user)) {
            // If this is the owner, check that the user still has access to the points. If not, remove the
            // unauthorized points, resave, and continue.
            boolean changed = false;
            List<DataPointVO> list = watchList.getPointList();
            List<DataPointVO> copy = new ArrayList<>(list);
            for (DataPointVO point : copy) {
                if (point == null || !Permissions.hasDataPointReadPermission(user, point)) {
                    list.remove(point);
                    changed = true;
                }
            }
            if (changed)
                WatchListDao.instance.saveWatchList(watchList);
        }
        User watchListUser = userDao.getUser(watchList.getUserId());
        String username;
        if (watchListUser == null) {
            username = Common.translate("watchlist.userDNE");
        } else {
            username = watchListUser.getUsername();
            users.add(watchListUser.getUsername());
        }
        watchListUsers.add(new IntStringPair(watchList.getId(), username));
        // Add the Username to the name to know who's it is
        userWatchLists.add(new IntStringPair(watchList.getId(), watchList.getName() + " (" + username + ")"));
        Map<String, String> wlData = new HashMap<String, String>();
        wlData.put("id", Integer.toString(watchList.getId()));
        wlData.put("name", watchList.getName());
        wlData.put("username", username);
        watchListsData.add(wlData);
    }
    if (!found) {
        // The user's default watch list was not found. It was either deleted or unshared from them. Find a new one.
        // The list will always contain at least one, so just use the id of the first in the list.
        selected = watchLists.get(0).getId();
        WatchListDao.instance.saveSelectedWatchList(user.getId(), selected);
    }
    Collections.sort(watchListsData, new Comparator<Map<String, String>>() {

        @Override
        public int compare(Map<String, String> o1, Map<String, String> o2) {
            return o1.get("name").compareTo(o2.get("name"));
        }
    });
    model.put(KEY_WATCHLISTS, watchListsData);
    model.put(KEY_SELECTED_WATCHLIST, selected);
    model.put(KEY_WATCHLIST_USERS, watchListUsers);
    model.put(KEY_USER_WATCHLISTS, userWatchLists);
    model.put(KEY_USERNAME, user.getUsername());
    List<String> sortedUsers = new ArrayList<String>(users);
    Collections.sort(sortedUsers);
    model.put("usernames", sortedUsers);
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) User(com.serotonin.m2m2.vo.User) IntStringPair(com.serotonin.db.pair.IntStringPair) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) UserDao(com.serotonin.m2m2.db.dao.UserDao) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

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