Skip to content

Commit

Permalink
Use DumpErrors
Browse files Browse the repository at this point in the history
  • Loading branch information
VahidN committed Jul 24, 2023
1 parent 96c4161 commit d2c1f6f
Show file tree
Hide file tree
Showing 8 changed files with 109 additions and 88 deletions.
1 change: 1 addition & 0 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
<PropertyGroup>
<LangVersion>latest</LangVersion>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
<AccelerateBuildsInVisualStudio>true</AccelerateBuildsInVisualStudio>
<AnalysisLevel>latest</AnalysisLevel>
<AnalysisMode>AllEnabledByDefault</AnalysisMode>
<CodeAnalysisTreatWarningsAsErrors>true</CodeAnalysisTreatWarningsAsErrors>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public static string DumpErrors(this IdentityResult result, bool useHtmlNewLine
var results = new StringBuilder();
if (!result.Succeeded)
{
foreach (var errorDescription in result.Errors.Select(x => x.Description))
foreach (var errorDescription in result.Errors.Select(x => x.Description).Distinct())
{
if (string.IsNullOrWhiteSpace(errorDescription))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,6 @@
<ItemGroup>
<!-- extends watching group to include *.js files -->
<Watch Include="**\*.js" Exclude="node_modules\**\*;**\*.js.map;obj\**\*;bin\**\*;wwwroot\**\*;src\**\*" />
<None Include="*.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@

namespace ASPNETCoreIdentitySample.Areas.Identity.Controllers;

[Authorize, Area(AreaConstants.IdentityArea),
BreadCrumb(Title = "تغییر کلمه‌ی عبور", UseDefaultRouteUrl = true, Order = 0)]
[Authorize]
[Area(AreaConstants.IdentityArea)]
[BreadCrumb(Title = "تغییر کلمه‌ی عبور", UseDefaultRouteUrl = true, Order = 0)]
public class ChangePasswordController : Controller
{
private readonly IEmailSender _emailSender;
Expand Down Expand Up @@ -47,12 +48,13 @@ public async Task<IActionResult> Index()
var userId = User.Identity?.GetUserId<int>() ?? 0;
var passwordChangeDate = await _usedPasswordsService.GetLastUserPasswordChangeDateAsync(userId);
return View(new ChangePasswordViewModel
{
LastUserPasswordChangeDate = passwordChangeDate
});
{
LastUserPasswordChangeDate = passwordChangeDate,
});
}

[HttpPost, ValidateAntiForgeryToken]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index(ChangePasswordViewModel model)
{
if (model is null)
Expand Down Expand Up @@ -80,36 +82,38 @@ public async Task<IActionResult> Index(ChangePasswordViewModel model)
await _signInManager.RefreshSignInAsync(user);

await _emailSender.SendEmailAsync(
user.Email,
"اطلاع رسانی تغییر کلمه‌ی عبور",
"~/Areas/Identity/Views/EmailTemplates/_ChangePasswordNotification.cshtml",
new ChangePasswordNotificationViewModel
{
User = user,
EmailSignature = _siteOptions.Value.Smtp.FromName,
MessageDateTime = DateTime.UtcNow.ToLongPersianDateTimeString()
});
user.Email,
"اطلاع رسانی تغییر کلمه‌ی عبور",
"~/Areas/Identity/Views/EmailTemplates/_ChangePasswordNotification.cshtml",
new ChangePasswordNotificationViewModel
{
User = user,
EmailSignature = _siteOptions.Value.Smtp.FromName,
MessageDateTime = DateTime.UtcNow.ToLongPersianDateTimeString(),
});

return RedirectToAction(nameof(Index), "UserCard", new { id = user.Id });
}

foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
ModelState.AddModelError("", result.DumpErrors(true));

return View(model);
}

/// <summary>
/// For [Remote] validation
/// </summary>
[AjaxOnly, HttpPost, ValidateAntiForgeryToken, ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
[AjaxOnly]
[HttpPost]
[ValidateAntiForgeryToken]
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
public async Task<IActionResult> ValidatePassword(string newPassword)
{
var user = await _userManager.GetCurrentUserAsync();
var result = await _passwordValidator.ValidateAsync(
(UserManager<User>)_userManager, user, newPassword);
(UserManager<User>)_userManager,
user,
newPassword);
return Json(result.Succeeded ? "true" : result.DumpErrors(true));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@

namespace ASPNETCoreIdentitySample.Areas.Identity.Controllers;

[Authorize(Roles = ConstantRoles.Admin), Area(AreaConstants.IdentityArea),
BreadCrumb(Title = "تغییر کلمه‌ی عبور كاربر توسط مدير سيستم", UseDefaultRouteUrl = true, Order = 0)]
[Authorize(Roles = ConstantRoles.Admin)]
[Area(AreaConstants.IdentityArea)]
[BreadCrumb(Title = "تغییر کلمه‌ی عبور كاربر توسط مدير سيستم", UseDefaultRouteUrl = true, Order = 0)]
public class ChangeUserPasswordController : Controller
{
private readonly IEmailSender _emailSender;
Expand Down Expand Up @@ -57,13 +58,14 @@ public async Task<IActionResult> Index(int? id)
}

return View(new ChangeUserPasswordViewModel
{
UserId = user.Id,
Name = user.UserName
});
{
UserId = user.Id,
Name = user.UserName,
});
}

[HttpPost, ValidateAntiForgeryToken]
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index(ChangeUserPasswordViewModel model)
{
if (model is null)
Expand Down Expand Up @@ -91,36 +93,38 @@ public async Task<IActionResult> Index(ChangeUserPasswordViewModel model)
await _signInManager.RefreshSignInAsync(user);

await _emailSender.SendEmailAsync(
user.Email,
"اطلاع رسانی تغییر کلمه‌ی عبور",
"~/Areas/Identity/Views/EmailTemplates/_ChangePasswordNotification.cshtml",
new ChangePasswordNotificationViewModel
{
User = user,
EmailSignature = _siteOptions.Value.Smtp.FromName,
MessageDateTime = DateTime.UtcNow.ToLongPersianDateTimeString()
});
user.Email,
"اطلاع رسانی تغییر کلمه‌ی عبور",
"~/Areas/Identity/Views/EmailTemplates/_ChangePasswordNotification.cshtml",
new ChangePasswordNotificationViewModel
{
User = user,
EmailSignature = _siteOptions.Value.Smtp.FromName,
MessageDateTime = DateTime.UtcNow.ToLongPersianDateTimeString(),
});

return RedirectToAction(nameof(Index), "UserCard", new { id = user.Id });
}

foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
ModelState.AddModelError("", result.DumpErrors(true));

return View(model);
}

/// <summary>
/// For [Remote] validation
/// </summary>
[AjaxOnly, HttpPost, ValidateAntiForgeryToken, ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
[AjaxOnly]
[HttpPost]
[ValidateAntiForgeryToken]
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
public async Task<IActionResult> ValidatePassword(string newPassword, int userId)
{
var user = await _userManager.FindByIdAsync(userId.ToString(CultureInfo.InvariantCulture));
var result = await _passwordValidator.ValidateAsync(
(UserManager<User>)_userManager, user, newPassword);
(UserManager<User>)_userManager,
user,
newPassword);
return Json(result.Succeeded ? "true" : result.DumpErrors(true));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,9 @@ public async Task<IActionResult> ValidatePassword(string password, string email)
}

var result = await _passwordValidator.ValidateAsync(
(UserManager<User>)_userManager, user, password);
(UserManager<User>)_userManager,
user,
password);
return Json(result.Succeeded ? "true" : result.DumpErrors(true));
}

Expand Down Expand Up @@ -131,10 +133,7 @@ public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
return RedirectToAction(nameof(ResetPasswordConfirmation));
}

foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
ModelState.AddModelError("", result.DumpErrors(true));

return View();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,12 @@
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Language = DNTCaptcha.Core.Language;

namespace ASPNETCoreIdentitySample.Areas.Identity.Controllers;

[Area(AreaConstants.IdentityArea), AllowAnonymous, BreadCrumb(Title = "ثبت نام", UseDefaultRouteUrl = true, Order = 0)]
[Area(AreaConstants.IdentityArea)]
[AllowAnonymous]
[BreadCrumb(Title = "ثبت نام", UseDefaultRouteUrl = true, Order = 0)]
public class RegisterController : Controller
{
private readonly IEmailSender _emailSender;
Expand All @@ -42,22 +43,31 @@ public RegisterController(
/// <summary>
/// For [Remote] validation
/// </summary>
[AjaxOnly, HttpPost, ValidateAntiForgeryToken, ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
[AjaxOnly]
[HttpPost]
[ValidateAntiForgeryToken]
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
public async Task<IActionResult> ValidateUsername(string username, string email)
{
var result = await _userValidator.ValidateAsync(
(UserManager<User>)_userManager, new User { UserName = username, Email = email });
(UserManager<User>)_userManager,
new User { UserName = username, Email = email });
return Json(result.Succeeded ? "true" : result.DumpErrors(true));
}

/// <summary>
/// For [Remote] validation
/// </summary>
[AjaxOnly, HttpPost, ValidateAntiForgeryToken, ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
[AjaxOnly]
[HttpPost]
[ValidateAntiForgeryToken]
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
public async Task<IActionResult> ValidatePassword(string password, string username)
{
var result = await _passwordValidator.ValidateAsync(
(UserManager<User>)_userManager, new User { UserName = username }, password);
(UserManager<User>)_userManager,
new User { UserName = username },
password);
return Json(result.Succeeded ? "true" : result.DumpErrors(true));
}

Expand All @@ -80,18 +90,14 @@ public async Task<IActionResult> ConfirmEmail(string userId, string code)
}

[BreadCrumb(Title = "تائیدیه ایمیل", Order = 1)]
public IActionResult ConfirmedRegisteration()
{
return View();
}
public IActionResult ConfirmedRegisteration() => View();

[BreadCrumb(Title = "ایندکس", Order = 1)]
public IActionResult Index()
{
return View();
}
public IActionResult Index() => View();

[HttpPost, ValidateAntiForgeryToken, ValidateDNTCaptcha]
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateDNTCaptcha]
public async Task<IActionResult> Index(RegisterViewModel model)
{
if (model is null)
Expand All @@ -102,12 +108,12 @@ public async Task<IActionResult> Index(RegisterViewModel model)
if (ModelState.IsValid)
{
var user = new User
{
UserName = model.Username,
Email = model.Email,
FirstName = model.FirstName,
LastName = model.LastName
};
{
UserName = model.Username,
Email = model.Email,
FirstName = model.FirstName,
LastName = model.LastName,
};
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
Expand All @@ -117,35 +123,30 @@ public async Task<IActionResult> Index(RegisterViewModel model)
//ControllerExtensions.ShortControllerName<RegisterController>(), //TODO: use everywhere .................

await _emailSender.SendEmailAsync(
user.Email,
"لطفا اکانت خود را تائید کنید",
"~/Areas/Identity/Views/EmailTemplates/_RegisterEmailConfirmation.cshtml",
new RegisterEmailConfirmationViewModel
{
User = user,
EmailConfirmationToken = code,
EmailSignature = _siteOptions.Value.Smtp.FromName,
MessageDateTime = DateTime.UtcNow.ToLongPersianDateTimeString()
});
user.Email,
"لطفا اکانت خود را تائید کنید",
"~/Areas/Identity/Views/EmailTemplates/_RegisterEmailConfirmation.cshtml",
new RegisterEmailConfirmationViewModel
{
User = user,
EmailConfirmationToken = code,
EmailSignature = _siteOptions.Value.Smtp.FromName,
MessageDateTime =
DateTime.UtcNow.ToLongPersianDateTimeString(),
});

return RedirectToAction(nameof(ConfirmYourEmail));
}

return RedirectToAction(nameof(ConfirmedRegisteration));
}

foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
ModelState.AddModelError("", result.DumpErrors(true));
}

return View(model);
}

[BreadCrumb(Title = "ایمیل خود را تائید کنید", Order = 1)]
public IActionResult ConfirmYourEmail()
{
return View();
}
public IActionResult ConfirmYourEmail() => View();
}
11 changes: 11 additions & 0 deletions src/ASPNETCoreIdentitySample/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning",
"System": "Information",
"Microsoft": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}

0 comments on commit d2c1f6f

Please sign in to comment.