Skip to content

JADNC: Add required on post validator. #765

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Examples/JsonApiDotNetCoreExample/Models/Article.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ namespace JsonApiDotNetCoreExample.Models
public sealed class Article : Identifiable
{
[Attr]
[RequiredOnPost]
public string Name { get; set; }

[HasOne]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using Microsoft.AspNetCore.Http;
using System;
using System.ComponentModel.DataAnnotations;

namespace JsonApiDotNetCore.Models
{
[AttributeUsage(AttributeTargets.Property)]
public sealed class RequiredOnPostAttribute : ValidationAttribute
{
private string Error { get; set; }

/// <summary>
/// Validates that the value is not null or empty on POST operations.
/// </summary>
/// <param name="error"></param>
public RequiredOnPostAttribute(string error = null)
{
Error = error;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var httpContextAccessor = (IHttpContextAccessor)validationContext.GetService(typeof(IHttpContextAccessor));
var request = httpContextAccessor.HttpContext.Request;
if (request.Method == "POST")
{
if (Error == null)
{
Error = string.Format("{0} is required.", validationContext.MemberName);
}

if (value == null)
{
return new ValidationResult(Error);
}

var propertyType = value.GetType();
if (propertyType.Equals(typeof(System.String)))
{
if (string.IsNullOrEmpty(Convert.ToString(value)))
{
return new ValidationResult(Error);
}
}
}
return ValidationResult.Success;
}
}
}
22 changes: 13 additions & 9 deletions src/JsonApiDotNetCore/Serialization/Server/RequestDeserializer.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Linq;
using JsonApiDotNetCore.Exceptions;
using JsonApiDotNetCore.Internal;
using JsonApiDotNetCore.Internal.Contracts;
Expand Down Expand Up @@ -36,16 +37,19 @@ protected override void AfterProcessField(IIdentifiable entity, IResourceField f
{
if (field is AttrAttribute attr)
{
if (attr.Capabilities.HasFlag(AttrCapabilities.AllowMutate))
{
_targetedFields.Attributes.Add(attr);
}
else
{
if (!attr.Capabilities.HasFlag(AttrCapabilities.AllowMutate))
throw new InvalidRequestBodyException(
"Changing the value of the requested attribute is not allowed.",
$"Changing the value of '{attr.PublicAttributeName}' is not allowed.", null);
}
"Changing the value of the requested attribute is not allowed.",
$"Changing the value of '{attr.PublicAttributeName}' is not allowed.", null);

var property = attr.PropertyInfo;
var requiredOnPost = property.GetCustomAttributes(typeof(RequiredOnPostAttribute), false);
if (requiredOnPost?.FirstOrDefault() != null && attr.GetValue(entity) == null)
throw new InvalidRequestBodyException("Changing the value of a required attribute to null is not allowed.",
$"Attribute '{attr.PublicAttributeName}' is required and therefore cannot be updated to null.", null);

_targetedFields.Attributes.Add(attr);

}
else if (field is RelationshipAttribute relationship)
_targetedFields.Relationships.Add(relationship);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,10 @@ public async Task Can_Create_Many_To_Many()
data = new
{
type = "articles",
attributes = new Dictionary<string, object>
{
{"name", "An article with relationships"}
},
relationships = new Dictionary<string, dynamic>
{
{ "author", new {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -609,5 +609,256 @@ public async Task Cascade_Permission_Error_Delete_ToMany_Relationship()
Assert.Equal("You are not allowed to update fields or relationships of locked todo items.", errorDocument.Errors[0].Title);
Assert.Null(errorDocument.Errors[0].Detail);
}

[Fact]
public async Task Create_Article_With_RequiredOnPost_Name_Attribute_Succeeds()
{
// Arrange
string name = "Article Title";
var context = _fixture.GetService<AppDbContext>();
var author = new Author();
context.AuthorDifferentDbContextName.Add(author);
await context.SaveChangesAsync();

var route = "/api/v1/articles";
var request = new HttpRequestMessage(new HttpMethod("POST"), route);
var content = new
{
data = new
{
type = "articles",
attributes = new Dictionary<string, object>
{
{"name", name}
},
relationships = new Dictionary<string, dynamic>
{
{ "author", new {
data = new
{
type = "authors",
id = author.StringId
}
} }
}
}
};
request.Content = new StringContent(JsonConvert.SerializeObject(content));
request.Content.Headers.ContentType = new MediaTypeHeaderValue(HeaderConstants.MediaType);

// Act
var response = await _fixture.Client.SendAsync(request);

// Assert
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.Created, response.StatusCode);

var articleResponse = _fixture.GetDeserializer().DeserializeSingle<Article>(body).Data;
Assert.NotNull(articleResponse);

var persistedArticle = await _fixture.Context.Articles
.SingleAsync(a => a.Id == articleResponse.Id);

Assert.Equal(name, persistedArticle.Name);
}

[Fact]
public async Task Create_Article_With_RequiredOnPost_Name_Attribute_Explicitly_Null_Fails()
{
// Arrange
var context = _fixture.GetService<AppDbContext>();
var author = new Author();
context.AuthorDifferentDbContextName.Add(author);
await context.SaveChangesAsync();

var route = "/api/v1/articles";
var request = new HttpRequestMessage(new HttpMethod("POST"), route);
var content = new
{
data = new
{
type = "articles",
attributes = new Dictionary<string, object>
{
{"name", null}
},
relationships = new Dictionary<string, dynamic>
{
{ "author", new {
data = new
{
type = "authors",
id = author.StringId
}
} }
}
}
};
request.Content = new StringContent(JsonConvert.SerializeObject(content));
request.Content.Headers.ContentType = new MediaTypeHeaderValue(HeaderConstants.MediaType);

// Act
var response = await _fixture.Client.SendAsync(request);

// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
}

[Fact]
public async Task Create_Article_With_RequiredOnPost_Name_Attribute_Missing_Fails()
{
// Arrange
var context = _fixture.GetService<AppDbContext>();
var author = new Author();
context.AuthorDifferentDbContextName.Add(author);
await context.SaveChangesAsync();

var route = "/api/v1/articles";
var request = new HttpRequestMessage(new HttpMethod("POST"), route);
var content = new
{
data = new
{
type = "articles",
relationships = new Dictionary<string, dynamic>
{
{ "author", new {
data = new
{
type = "authors",
id = author.StringId
}
} }
}
}
};
request.Content = new StringContent(JsonConvert.SerializeObject(content));
request.Content.Headers.ContentType = new MediaTypeHeaderValue(HeaderConstants.MediaType);

// Act
var response = await _fixture.Client.SendAsync(request);

// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
}


[Fact]
public async Task Update_Article_With_RequiredOnPost_Name_Attribute_Succeeds()
{
// Arrange
var name = "Article Name";
var context = _fixture.GetService<AppDbContext>();
var article = _articleFaker.Generate();
context.Articles.Add(article);
await context.SaveChangesAsync();

var route = $"/api/v1/articles/{article.Id}";
var request = new HttpRequestMessage(new HttpMethod("PATCH"), route);
var content = new
{
data = new
{
type = "articles",
id = article.StringId,
attributes = new Dictionary<string, object>
{
{"name", name}
}
}
};

request.Content = new StringContent(JsonConvert.SerializeObject(content));
request.Content.Headers.ContentType = new MediaTypeHeaderValue(HeaderConstants.MediaType);

// Act
var response = await _fixture.Client.SendAsync(request);

// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);

_fixture.ReloadDbContext();
var persistedArticle = await _fixture.Context.Articles
.SingleOrDefaultAsync(a => a.Id == article.Id);

var updatedName = persistedArticle.Name;
Assert.Equal(name, updatedName);
}

[Fact]
public async Task Update_Article_With_RequiredOnPost_Name_Attribute_Missing_Succeeds()
{
// Arrange
var context = _fixture.GetService<AppDbContext>();
var tag = _tagFaker.Generate();
var article = _articleFaker.Generate();
context.Tags.Add(tag);
context.Articles.Add(article);
await context.SaveChangesAsync();

var route = $"/api/v1/articles/{article.Id}";
var request = new HttpRequestMessage(new HttpMethod("PATCH"), route);
var content = new
{
data = new
{
type = "articles",
id = article.StringId,
relationships = new Dictionary<string, dynamic>
{
{ "tags", new {
data = new [] { new
{
type = "tags",
id = tag.StringId
} }
} }
}
}
};

request.Content = new StringContent(JsonConvert.SerializeObject(content));
request.Content.Headers.ContentType = new MediaTypeHeaderValue(HeaderConstants.MediaType);

// Act
var response = await _fixture.Client.SendAsync(request);

// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}

[Fact]
public async Task Update_Article_With_RequiredOnPost_Name_Attribute_Explicitly_Null_Fails()
{
// Arrange
var context = _fixture.GetService<AppDbContext>();
var article = _articleFaker.Generate();
context.Articles.Add(article);
await context.SaveChangesAsync();

var route = $"/api/v1/articles/{article.Id}";
var request = new HttpRequestMessage(new HttpMethod("PATCH"), route);
var content = new
{
data = new
{
type = "articles",
id = article.StringId,
attributes = new Dictionary<string, object>
{
{"name", null}
}
}
};

request.Content = new StringContent(JsonConvert.SerializeObject(content));
request.Content.Headers.ContentType = new MediaTypeHeaderValue(HeaderConstants.MediaType);

// Act
var response = await _fixture.Client.SendAsync(request);

// Assert
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
}
}
}
5 changes: 3 additions & 2 deletions test/UnitTests/Serialization/Client/RequestSerializerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public RequestSerializerTests()
public void SerializeSingle_ResourceWithDefaultTargetFields_CanBuild()
{
// Arrange
var entity = new TestResource { Id = 1, StringField = "value", NullableIntField = 123 };
var entity = new TestResource { Id = 1, StringField = "value", RequiredOnPostField = "value", NullableIntField = 123 };

// Act
string serialized = _serializer.Serialize(entity);
Expand All @@ -33,8 +33,9 @@ public void SerializeSingle_ResourceWithDefaultTargetFields_CanBuild()
""data"":{
""type"":""testResource"",
""id"":""1"",
""attributes"":{
""attributes"":{
""stringField"":""value"",
""requiredOnPostField"":""value"",
""dateTimeField"":""0001-01-01T00:00:00"",
""nullableDateTimeField"":null,
""intField"":0,
Expand Down
Loading