Skip to content

Commit

Permalink
Add validation and sanitization for SocialLink objects
Browse files Browse the repository at this point in the history
Introduce validation for each SocialLink in SettingsController.
Parse JsonData into SocialLink array and check Name, Icon, and Url.
Add errors to ModelState and return BadRequest for invalid data.
Validate Url as absolute URI and sanitize using Helper.SterilizeLink.
Assign validated SocialLinks to blogConfig.SocialLinkSettings.
  • Loading branch information
EdiWang committed Nov 10, 2024
1 parent 4656a9c commit dd1ff2f
Showing 1 changed file with 34 additions and 1 deletion.
35 changes: 34 additions & 1 deletion src/Moonglade.Web/Controllers/SettingsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -163,10 +163,43 @@ public async Task<IActionResult> SocialLink(SocialLinkSettingsJsonModel model)
return BadRequest(ModelState.CombineErrorMessages());
}

var links = model.JsonData.FromJson<SocialLink[]>();

// Check each link, if any link is invalid, return BadRequest
foreach (var link in links)
{
if (string.IsNullOrWhiteSpace(link.Name))
{
ModelState.AddModelError($"{nameof(Moonglade.Configuration.SocialLink)}.{nameof(Moonglade.Configuration.SocialLink.Name)}", "Name is required");
return BadRequest(ModelState.CombineErrorMessages());
}

if (string.IsNullOrWhiteSpace(link.Icon))
{
ModelState.AddModelError($"{nameof(Moonglade.Configuration.SocialLink)}.{nameof(Moonglade.Configuration.SocialLink.Icon)}", "Icon is required");
return BadRequest(ModelState.CombineErrorMessages());
}

if (string.IsNullOrWhiteSpace(link.Url))
{
ModelState.AddModelError($"{nameof(Moonglade.Configuration.SocialLink)}.{nameof(Moonglade.Configuration.SocialLink.Url)}", "Url is required");
return BadRequest(ModelState.CombineErrorMessages());
}

if (!Uri.TryCreate(link.Url, UriKind.Absolute, out _))
{
ModelState.AddModelError($"{nameof(Moonglade.Configuration.SocialLink)}.{nameof(Moonglade.Configuration.SocialLink.Url)}", "Url is invalid");
return BadRequest(ModelState.CombineErrorMessages());
}

// Sterilize
link.Url = Helper.SterilizeLink(link.Url);
}

blogConfig.SocialLinkSettings = new()
{
IsEnabled = model.IsEnabled,
Links = model.JsonData.FromJson<SocialLink[]>()
Links = links
};

await SaveConfigAsync(blogConfig.SocialLinkSettings);
Expand Down

0 comments on commit dd1ff2f

Please sign in to comment.