Search in sources :

Example 71 with Permissions

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

the class UserRestController method updateUser.

@ApiOperation(value = "Updates a user")
@RequestMapping(method = RequestMethod.PUT, consumes = { "application/json", "text/csv" }, produces = { "application/json", "text/csv" }, value = "/{username}")
public ResponseEntity<UserModel> updateUser(@PathVariable String username, @RequestBody(required = true) UserModel model, UriComponentsBuilder builder, 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();
            }
            // Cannot make yourself disabled or not admin
            if (user.getId() == u.getId()) {
                if (!(authentication instanceof UsernamePasswordAuthenticationToken)) {
                    throw new AccessDeniedException(new TranslatableMessage("rest.error.usernamePasswordOnly"));
                }
                boolean failed = false;
                if (!model.isAdmin()) {
                    model.addValidationMessage(new ProcessMessage("permissions", new TranslatableMessage("users.validate.adminInvalid")));
                    failed = true;
                }
                if (model.getDisabled()) {
                    model.addValidationMessage(new ProcessMessage("disabled", new TranslatableMessage("users.validate.adminDisable")));
                    failed = true;
                }
                if (failed) {
                    result.addRestMessage(getValidationFailedError());
                    return result.createResponseEntity(model);
                }
            }
            // Cannot Rename a User to an existing Username
            if (!model.getUsername().equals(username)) {
                User existingUser = UserDao.instance.getUser(model.getUsername());
                if (existingUser != null) {
                    model.addValidationMessage(new ProcessMessage("username", new TranslatableMessage("users.validate.usernameInUse")));
                    result.addRestMessage(getValidationFailedError());
                    return result.createResponseEntity(model);
                }
            }
            // Set the ID for the user for validation
            model.getData().setId(u.getId());
            if (!model.validate()) {
                result.addRestMessage(this.getValidationFailedError());
            } else {
                User newUser = model.getData();
                newUser.setId(u.getId());
                if (!StringUtils.isBlank(model.getData().getPassword()))
                    newUser.setPassword(Common.encrypt(model.getData().getPassword()));
                else
                    newUser.setPassword(u.getPassword());
                UserDao.instance.saveUser(newUser);
                sessionRegistry.userUpdated(request, newUser);
            }
            return result.createResponseEntity(model);
        } else {
            if (u.getId() != user.getId()) {
                LOG.warn("Non admin user: " + user.getUsername() + " attempted to update user : " + u.getUsername());
                result.addRestMessage(this.getUnauthorizedMessage());
                return result.createResponseEntity();
            } else {
                if (!(authentication instanceof UsernamePasswordAuthenticationToken)) {
                    throw new AccessDeniedException(new TranslatableMessage("rest.error.usernamePasswordOnly"));
                }
                // Allow users to update themselves
                User newUser = model.getData();
                newUser.setId(u.getId());
                if (!StringUtils.isBlank(model.getData().getPassword()))
                    newUser.setPassword(Common.encrypt(model.getData().getPassword()));
                else
                    newUser.setPassword(u.getPassword());
                // If we are not Admin we cannot modify our own privs
                if (!u.isAdmin()) {
                    if (!StringUtils.equals(u.getPermissions(), newUser.getPermissions())) {
                        model.addValidationMessage(new ProcessMessage("permissions", new TranslatableMessage("users.validate.cannotChangePermissions")));
                        result.addRestMessage(this.getValidationFailedError());
                        return result.createResponseEntity(model);
                    }
                }
                if (!model.validate()) {
                    result.addRestMessage(this.getValidationFailedError());
                } else {
                    // Cannot make yourself disabled admin or not admin
                    boolean failed = false;
                    if (user.getId() == u.getId()) {
                        if (model.getDisabled()) {
                            model.addValidationMessage(new ProcessMessage("disabled", new TranslatableMessage("users.validate.adminDisable")));
                            failed = true;
                        }
                        if (u.isAdmin()) {
                            // We were superadmin, so we must still have it
                            if (!model.getData().isAdmin()) {
                                model.addValidationMessage(new ProcessMessage("permissions", new TranslatableMessage("users.validate.adminInvalid")));
                                failed = true;
                            }
                        } else {
                            // We were not superadmin so we must not have it
                            if (model.getData().isAdmin()) {
                                model.addValidationMessage(new ProcessMessage("permissions", new TranslatableMessage("users.validate.adminGrantInvalid")));
                                failed = true;
                            }
                        }
                        if (failed) {
                            result.addRestMessage(getValidationFailedError());
                            return result.createResponseEntity(model);
                        }
                    }
                    UserDao.instance.saveUser(newUser);
                    sessionRegistry.userUpdated(request, newUser);
                    URI location = builder.path("v1/users/{username}").buildAndExpand(model.getUsername()).toUri();
                    result.addRestMessage(getResourceCreatedMessage(location));
                }
                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) ProcessMessage(com.serotonin.m2m2.i18n.ProcessMessage) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) URI(java.net.URI) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 72 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'", 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")
public ResponseEntity<Set<String>> getAllUserGroups(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()));
        }
        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)

Example 73 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, exclude provided groups in query", 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/{query}")
public ResponseEntity<List<PermissionDetails>> getUserPermissions(@ApiParam(value = "Query of permissions to show as already added", required = true, allowMultiple = false) @PathVariable String query, 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, query, 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 74 with Permissions

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

the class ScriptPermissionsModel method toPermissions.

public ScriptPermissions toPermissions() {
    ScriptPermissions permissions = new ScriptPermissions();
    permissions.setDataPointReadPermissions(dataPointReadPermissions);
    permissions.setDataPointSetPermissions(dataPointSetPermissions);
    permissions.setDataSourcePermissions(dataSourcePermissions);
    return permissions;
}
Also used : ScriptPermissions(com.serotonin.m2m2.rt.script.ScriptPermissions)

Example 75 with Permissions

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

the class PointLinksDwr method savePointLink.

@DwrPermission(user = true)
public ProcessResult savePointLink(int id, String xid, int sourcePointId, int targetPointId, String script, int event, boolean writeAnnotation, boolean disabled, ScriptPermissions permissions, int logLevel) {
    // Validate the given information. If there is a problem, return an appropriate error message.
    PointLinkVO vo = new PointLinkVO();
    vo.setId(id);
    vo.setXid(xid);
    vo.setSourcePointId(sourcePointId);
    vo.setTargetPointId(targetPointId);
    vo.setScript(script);
    vo.setEvent(event);
    vo.setWriteAnnotation(writeAnnotation);
    vo.setDisabled(disabled);
    vo.setScriptPermissions(permissions);
    vo.setLogLevel(logLevel);
    ProcessResult response = new ProcessResult();
    PointLinkDao pointLinkDao = PointLinkDao.instance;
    if (StringUtils.isBlank(xid))
        response.addContextualMessage("xid", "validate.required");
    else if (!pointLinkDao.isXidUnique(xid, id))
        response.addContextualMessage("xid", "validate.xidUsed");
    vo.validate(response);
    // Save it
    if (!response.getHasMessages())
        RTMDefinition.instance.savePointLink(vo);
    response.addData("plId", vo.getId());
    return response;
}
Also used : ProcessResult(com.serotonin.m2m2.i18n.ProcessResult) DwrPermission(com.serotonin.m2m2.web.dwr.util.DwrPermission)

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