use of com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException in project ma-modules-public by infiniteautomation.
the class AuthenticationTokenRestController method createToken.
@ApiOperation(value = "Create auth token", notes = "Creates an authentication token for the current user or for the username specified (admin only)")
@RequestMapping(path = "/create", method = RequestMethod.POST)
@PreAuthorize("isAuthenticated() and isPasswordAuthenticated()")
public ResponseEntity<TokenModel> createToken(@RequestBody CreateTokenRequest requestBody, @AuthenticationPrincipal User currentUser) {
Date expiry = requestBody.getExpiry();
String username = requestBody.getUsername();
User user = currentUser;
if (username != null && !username.equals(currentUser.getUsername())) {
if (!currentUser.isAdmin()) {
throw new AccessDeniedException(new TranslatableMessage("rest.error.onlyAdminsCanCreateTokens"));
}
user = UserDao.instance.getUser(username);
if (user == null) {
throw new BadRequestException(new TranslatableMessage("rest.error.unknownUser", username));
}
}
String token = tokenAuthService.generateToken(user, expiry);
return new ResponseEntity<>(new TokenModel(token), HttpStatus.CREATED);
}
use of com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException in project ma-modules-public by infiniteautomation.
the class PointValueRestController method buildMap.
/**
* Build and validate the map of Requested Data Points
* @param user
* @param xids
* @return
*/
protected Map<Integer, DataPointVO> buildMap(User user, String[] xids, RollupEnum rollup) {
// Build the map, check permissions
Map<Integer, DataPointVO> voMap = new HashMap<Integer, DataPointVO>();
for (String xid : xids) {
DataPointVO vo = DataPointDao.instance.getByXid(xid);
if (vo == null) {
throw new NotFoundRestException();
} else {
if (!Permissions.hasDataPointReadPermission(user, vo))
throw new AccessDeniedException();
}
// TODO Add support for NONE Default Rollup
if (rollup == RollupEnum.POINT_DEFAULT && vo.getRollup() == RollupEnum.NONE.getId())
throw new BadRequestException(new TranslatableMessage("common.default", "Default point rollup of NONE is not yet supported for point with xid: " + xid));
;
// Validate the rollup
switch(vo.getPointLocator().getDataTypeId()) {
case DataTypes.ALPHANUMERIC:
case DataTypes.BINARY:
case DataTypes.IMAGE:
case DataTypes.MULTISTATE:
if (rollup.nonNumericSupport() == false)
throw new BadRequestException(new TranslatableMessage("rest.validate.rollup.incompatible", rollup.toString(), xid));
break;
case DataTypes.NUMERIC:
break;
}
voMap.put(vo.getId(), vo);
}
// Do we have any points
if (voMap.isEmpty())
throw new NotFoundRestException();
return voMap;
}
use of com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException in project ma-modules-public by infiniteautomation.
the class PointValueRestController method deletePointValues.
@ApiOperation(value = "Delete point values >= from and < to", notes = "The user must have set permission to the data point. If date is not supplied it defaults to now.")
@RequestMapping(method = RequestMethod.DELETE, value = "/{xid}", produces = { "application/json", "text/csv", "application/sero-json" })
public ResponseEntity<Long> deletePointValues(@ApiParam(value = "Point xids", required = true) @PathVariable String xid, @ApiParam(value = "From time", required = false, allowMultiple = false) @RequestParam(value = "from", required = false) @DateTimeFormat(iso = ISO.DATE_TIME) ZonedDateTime from, @ApiParam(value = "To time", required = false, allowMultiple = false) @RequestParam(value = "to", required = false) @DateTimeFormat(iso = ISO.DATE_TIME) ZonedDateTime to, @ApiParam(value = "Time zone", required = false, allowMultiple = false) @RequestParam(value = "timezone", required = false) String timezone, @AuthenticationPrincipal User user, UriComponentsBuilder builder, HttpServletRequest request) {
DataPointVO vo = DataPointDao.instance.getByXid(xid);
if (vo == null) {
throw new NotFoundRestException();
} else {
if (!Permissions.hasDataPointSetPermission(user, vo))
throw new AccessDeniedException();
}
ZoneId zoneId;
if (timezone == null) {
if (from != null) {
zoneId = from.getZone();
} else if (to != null)
zoneId = to.getZone();
else
zoneId = TimeZone.getDefault().toZoneId();
} else {
zoneId = ZoneId.of(timezone);
}
// Set the timezone on the from and to dates
long current = Common.timer.currentTimeMillis();
if (from != null)
from = from.withZoneSameInstant(zoneId);
else
from = ZonedDateTime.ofInstant(Instant.ofEpochMilli(current), zoneId);
if (to != null)
to = to.withZoneSameInstant(zoneId);
else
to = ZonedDateTime.ofInstant(Instant.ofEpochMilli(current), zoneId);
return ResponseEntity.ok(Common.runtimeManager.purgeDataPointValuesBetween(vo.getId(), from.toInstant().toEpochMilli(), to.toInstant().toEpochMilli()));
}
use of com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException in project ma-modules-public by infiniteautomation.
the class DataSourceRestController method enableDisable.
@ApiOperation(value = "Enable/disable/restart a data source")
@RequestMapping(method = RequestMethod.PUT, value = "/enable-disable/{xid}")
public ResponseEntity<DataPointModel> enableDisable(@AuthenticationPrincipal User user, @PathVariable String xid, @ApiParam(value = "Enable or disable the data source", required = true, allowMultiple = false) @RequestParam(required = true) boolean enabled, @ApiParam(value = "Restart the data source, enabled must equal true", required = false, defaultValue = "false", allowMultiple = false) @RequestParam(required = false, defaultValue = "false") boolean restart) {
DataSourceVO<?> dsvo = DataSourceDao.instance.getByXid(xid);
if (dsvo == null)
throw new NotFoundRestException();
try {
Permissions.ensureDataSourcePermission(user, dsvo);
} catch (PermissionException e) {
throw new AccessDeniedException("User does not have permission to edit the data source", e);
}
if (enabled && restart) {
dsvo.setEnabled(true);
// saving will restart it
Common.runtimeManager.saveDataSource(dsvo);
} else if (dsvo.isEnabled() != enabled) {
dsvo.setEnabled(enabled);
Common.runtimeManager.saveDataSource(dsvo);
}
return new ResponseEntity<>(HttpStatus.OK);
}
use of com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException 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();
}
Aggregations