Search in sources :

Example 6 with BadRequestException

use of com.infiniteautomation.mango.rest.v2.exception.BadRequestException in project ma-modules-public by infiniteautomation.

the class DataPointRestController method bulkDataPointOperation.

@ApiOperation(value = "Bulk get/create/update/delete data points", notes = "User must have read/edit permission for the data point")
@RequestMapping(method = RequestMethod.POST, value = "/bulk")
public ResponseEntity<TemporaryResource<DataPointBulkResponse, AbstractRestV2Exception>> bulkDataPointOperation(@RequestBody DataPointBulkRequest requestBody, @AuthenticationPrincipal User user, UriComponentsBuilder builder) {
    VoAction defaultAction = requestBody.getAction();
    DataPointModel defaultBody = requestBody.getBody();
    List<DataPointIndividualRequest> requests = requestBody.getRequests();
    if (requests == null) {
        throw new BadRequestException(new TranslatableMessage("rest.error.mustNotBeNull", "requests"));
    }
    String resourceId = requestBody.getId();
    Long expiration = requestBody.getExpiration();
    Long timeout = requestBody.getTimeout();
    TemporaryResource<DataPointBulkResponse, AbstractRestV2Exception> responseBody = bulkResourceManager.newTemporaryResource(RESOURCE_TYPE_BULK_DATA_POINT, resourceId, user.getId(), expiration, timeout, (resource) -> {
        DataPointBulkResponse bulkResponse = new DataPointBulkResponse();
        int i = 0;
        resource.progress(bulkResponse, i++, requests.size());
        for (DataPointIndividualRequest request : requests) {
            UriComponentsBuilder reqBuilder = UriComponentsBuilder.newInstance();
            DataPointIndividualResponse individualResponse = doIndividualRequest(request, defaultAction, defaultBody, user, reqBuilder);
            bulkResponse.addResponse(individualResponse);
            resource.progressOrSuccess(bulkResponse, i++, requests.size());
        }
    });
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(builder.path("/v2/data-points/bulk/{id}").buildAndExpand(responseBody.getId()).toUri());
    return new ResponseEntity<TemporaryResource<DataPointBulkResponse, AbstractRestV2Exception>>(responseBody, headers, HttpStatus.CREATED);
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) VoAction(com.infiniteautomation.mango.rest.v2.bulk.VoAction) DataPointModel(com.infiniteautomation.mango.rest.v2.model.dataPoint.DataPointModel) AbstractRestV2Exception(com.infiniteautomation.mango.rest.v2.exception.AbstractRestV2Exception) ResponseEntity(org.springframework.http.ResponseEntity) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) BadRequestException(com.infiniteautomation.mango.rest.v2.exception.BadRequestException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 7 with BadRequestException

use of com.infiniteautomation.mango.rest.v2.exception.BadRequestException in project ma-modules-public by infiniteautomation.

the class PasswordResetController method sendEmail.

@ApiOperation(value = "Sends the user an email containing a password reset link")
@RequestMapping(method = RequestMethod.POST, value = "/send-email")
public ResponseEntity<Void> sendEmail(@RequestBody SendEmailRequestBody body) throws AddressException, TemplateException, IOException {
    User user = UserDao.instance.getUser(body.getUsername());
    if (user == null) {
        throw new NotFoundRestException();
    }
    String email = body.getEmail();
    if (email == null) {
        throw new BadRequestException(new TranslatableMessage("rest.error.emailRequired"));
    }
    String providedEmail = email.toLowerCase(Locale.ROOT);
    String userEmail = user.getEmail().toLowerCase(Locale.ROOT);
    if (!providedEmail.equals(userEmail)) {
        throw new BadRequestException(new TranslatableMessage("rest.error.incorrectEmail"));
    }
    if (user.isDisabled()) {
        throw new BadRequestException(new TranslatableMessage("rest.error.userIsDisabled"));
    }
    passwordResetService.sendEmail(user);
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
Also used : NotFoundRestException(com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException) ResponseEntity(org.springframework.http.ResponseEntity) User(com.serotonin.m2m2.vo.User) BadRequestException(com.infiniteautomation.mango.rest.v2.exception.BadRequestException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 8 with BadRequestException

use of com.infiniteautomation.mango.rest.v2.exception.BadRequestException in project ma-modules-public by infiniteautomation.

the class PasswordResetController method createTokenForUser.

@ApiOperation(value = "Creates a password reset token and link for the given user")
@RequestMapping(method = RequestMethod.POST, value = "/create")
@PreAuthorize("isAdmin() and isPasswordAuthenticated()")
public CreateTokenResponse createTokenForUser(@RequestBody CreateTokenRequest requestBody, @AuthenticationPrincipal User currentUser) throws AddressException, TemplateException, IOException {
    String username = requestBody.getUsername();
    boolean lockPassword = requestBody.isLockPassword();
    boolean sendEmail = requestBody.isSendEmail();
    Date expiry = requestBody.getExpiry();
    User user = UserDao.instance.getUser(username);
    if (user == null) {
        throw new BadRequestException(new TranslatableMessage("rest.error.unknownUser", username));
    }
    if (user.getId() == currentUser.getId()) {
        throw new AccessDeniedException(new TranslatableMessage("rest.error.cantResetOwnUser"));
    }
    if (lockPassword) {
        UserDao.instance.lockPassword(user);
    }
    CreateTokenResponse response = new CreateTokenResponse();
    String token = passwordResetService.generateToken(user, expiry);
    response.setToken(token);
    response.setFullUrl(passwordResetService.generateResetUrl(token));
    response.setRelativeUrl(passwordResetService.generateRelativeResetUrl(token));
    if (sendEmail) {
        passwordResetService.sendEmail(user, token);
    }
    return response;
}
Also used : AccessDeniedException(com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException) User(com.serotonin.m2m2.vo.User) BadRequestException(com.infiniteautomation.mango.rest.v2.exception.BadRequestException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) Date(java.util.Date) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 9 with BadRequestException

use of com.infiniteautomation.mango.rest.v2.exception.BadRequestException in project ma-modules-public by infiniteautomation.

the class JsonEmportV2Controller method uploadConfigurationFile.

@PreAuthorize("isAdmin()")
@ApiOperation(value = "Upload 1 configuration json file", notes = "Files should only contain the json object to be imported")
@RequestMapping(method = RequestMethod.POST, value = "/upload-file", consumes = { "multipart/form-data", "multipart/form-data;boundary=-----SWAG_BOUND" })
public ResponseEntity<ImportStatusProvider> uploadConfigurationFile(MultipartHttpServletRequest multipartRequest, UriComponentsBuilder builder, HttpServletRequest request, @ApiParam(value = "timeout for Status Resource to Expire, defaults to 5 minutes", required = false, allowMultiple = false) @RequestParam(value = "timeout", required = false) Long timeout, @AuthenticationPrincipal User user) throws RestValidationFailedException, IOException, JsonException {
    Map<String, MultipartFile> map = multipartRequest.getFileMap();
    if (map.size() != 1)
        throw new BadRequestException(new TranslatableMessage("rest.error.oneFileOnly"));
    Iterator<String> itr = multipartRequest.getFileNames();
    MultipartFile file = multipartRequest.getFile(itr.next());
    if (!file.isEmpty()) {
        JsonReader jr = new JsonReader(Common.JSON_CONTEXT, new String(file.getBytes()));
        JsonObject jo = jr.read(JsonObject.class);
        String resourceId = importStatusResources.generateResourceId();
        ImportStatusProvider statusProvider = new ImportStatusProvider(importStatusResources, resourceId, websocket, timeout, jo, user);
        // Setup the Temporary Resource
        this.importStatusResources.put(resourceId, statusProvider);
        URI location = builder.path("/v2/json-emport/import/{id}").buildAndExpand(resourceId).toUri();
        return getResourceCreated(statusProvider, location);
    } else {
        throw new BadRequestException(new TranslatableMessage("rest.error.noFileProvided"));
    }
}
Also used : MultipartFile(org.springframework.web.multipart.MultipartFile) BadRequestException(com.infiniteautomation.mango.rest.v2.exception.BadRequestException) JsonReader(com.serotonin.json.JsonReader) JsonObject(com.serotonin.json.type.JsonObject) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) URI(java.net.URI) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 10 with BadRequestException

use of com.infiniteautomation.mango.rest.v2.exception.BadRequestException 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);
}
Also used : AccessDeniedException(com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException) ResponseEntity(org.springframework.http.ResponseEntity) User(com.serotonin.m2m2.vo.User) BadRequestException(com.infiniteautomation.mango.rest.v2.exception.BadRequestException) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) Date(java.util.Date) TokenModel(com.infiniteautomation.mango.rest.v2.model.jwt.TokenModel) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

BadRequestException (com.infiniteautomation.mango.rest.v2.exception.BadRequestException)17 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)17 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)10 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)10 NotFoundRestException (com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException)6 ResponseEntity (org.springframework.http.ResponseEntity)6 AccessDeniedException (com.infiniteautomation.mango.rest.v2.exception.AccessDeniedException)5 JsonNode (com.fasterxml.jackson.databind.JsonNode)4 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)4 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)4 AbstractRestV2Exception (com.infiniteautomation.mango.rest.v2.exception.AbstractRestV2Exception)4 DataPointModel (com.infiniteautomation.mango.rest.v2.model.dataPoint.DataPointModel)4 HttpHeaders (org.springframework.http.HttpHeaders)4 PreAuthorize (org.springframework.security.access.prepost.PreAuthorize)4 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)3 User (com.serotonin.m2m2.vo.User)3 URI (java.net.URI)3 VoAction (com.infiniteautomation.mango.rest.v2.bulk.VoAction)2 JsonObject (com.serotonin.json.type.JsonObject)2 DataPointPropertiesTemplateVO (com.serotonin.m2m2.vo.template.DataPointPropertiesTemplateVO)2