Esempio n. 1
0
        public async Task <IActionResult> Edit([FromBody] object @object, string serviceName)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var apiInfo = new ApiInfo(serviceName.ToLowerInvariant(), method: "command");

            ApiScopeResult scope = _authProvider.IsApiInScope(apiInfo);

            if (!scope.IsInScope)
            {
                return(NotFound());
            }

            if (scope.ScopeToUser)
            {
                string id = Request.Path.Value.Split('/').Last();

                var checkResponse = await _apiClient.GetAsync <UserIdResponse>(
                    new ApiInfo(name : apiInfo.Name, method : "query"),
                    pathWithQuery : $"/service/{apiInfo.Name}?id={id}"
                    );

                if (checkResponse?.Content?.UserId != _authProvider.GetUserId())
                {
                    return(BadRequest($"No {apiInfo.Name} found to edit"));
                }

                PropertyInfo propertyInfo = @object.GetType().GetProperty("UserId");

                if (propertyInfo == null)
                {
                    return(BadRequest("The requested type requires a UserId"));
                }

                propertyInfo.SetValue(@object, _authProvider.GetUserId());
            }

            var pathWithQuery = Request.QueryString.HasValue ? Request.Path.Value + Request.QueryString : Request.Path.Value;

            @object = await _nameResolver.ResolveNamesAsync(@object);

            var response = await _apiClient.EditAsync <object, object>(apiInfo, @object, pathWithQuery);

            if (response.IsError)
            {
                if (response.ResponseError == ResponseError.Http)
                {
                    if (response.HttpStatusCode == HttpStatusCode.NotFound)
                    {
                        return(NotFound());
                    }

                    if (response.HttpStatusCode == HttpStatusCode.BadRequest)
                    {
                        ModelState.AddModelError(string.Empty, response.Raw);
                        return(BadRequest(ModelState));
                    }

                    return(StatusCode((int)response.HttpStatusCode, response.Error));
                }

                return(StatusCode(500, response.Error));
            }

            return(Ok(response.Content));
        }