سفارشی سازی ASP.NET Core Identity - قسمت سوم - نرمال سازها و اعتبارسنجها
نویسنده: وحید نصیری
تاریخ: ۱۳۹۵/۱۱/۱۲ ۸:۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
public class UpperInvariantLookupNormalizer : ILookupNormalizer
identityOptionsUser.RequireUniqueEmail = true;
public override string Normalize(string key)
services.AddScoped<ILookupNormalizer, CustomNormalizer>(); services.AddScoped<UpperInvariantLookupNormalizer, CustomNormalizer>();
public class UserValidator<TUser> : IUserValidator<TUser> where TUser : class
public override async Task<IdentityResult> ValidateAsync(UserManager<User> manager, User user)
{
// First use the built-in validator
var result = await base.ValidateAsync(manager, user).ConfigureAwait(false);
var errors = result.Succeeded ? new List<IdentityError>() : result.Errors.ToList();
// Extending the built-in validator
validateEmail(user, errors);
validateUserName(user, errors);
return !errors.Any() ? IdentityResult.Success : IdentityResult.Failed(errors.ToArray());
} services.AddScoped<IUserValidator<User>, CustomUserValidator>(); services.AddScoped<UserValidator<User>, CustomUserValidator>();
public class PasswordValidator<TUser> : IPasswordValidator<TUser> where TUser : class
private static void setPasswordOptions(PasswordOptions identityOptionsPassword, SiteSettings siteSettings)
{
identityOptionsPassword.RequireDigit = siteSettings.PasswordOptions.RequireDigit;
identityOptionsPassword.RequireLowercase = siteSettings.PasswordOptions.RequireLowercase;
identityOptionsPassword.RequireNonAlphanumeric = siteSettings.PasswordOptions.RequireNonAlphanumeric;
identityOptionsPassword.RequireUppercase = siteSettings.PasswordOptions.RequireUppercase;
identityOptionsPassword.RequiredLength = siteSettings.PasswordOptions.RequiredLength;
} "PasswordOptions": {
"RequireDigit": false,
"RequiredLength": 6,
"RequireLowercase": false,
"RequireNonAlphanumeric": false,
"RequireUppercase": false
}, services.AddScoped<IPasswordValidator<User>, CustomPasswordValidator>(); services.AddScoped<PasswordValidator<User>, CustomPasswordValidator>();
public static void AddErrorsFromResult(this ModelStateDictionary modelStat, IdentityResult result)
public static string DumpErrors(this IdentityResult result, bool useHtmlNewLine = false)
[AjaxOnly, HttpPost, ValidateAntiForgeryToken] [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)] public async Task<IActionResult> ValidateUsername(string username, string email)
[AjaxOnly, HttpPost, ValidateAntiForgeryToken] [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)] public async Task<IActionResult> ValidatePassword(string password, string username)
IPasswordValidator<User> passwordValidator, IUserValidator<User> userValidator,
[Required(ErrorMessage = "(*)")]
[Display(Name = "نام کاربری")]
[Remote("ValidateUsername", "Register",
AdditionalFields = nameof(Email) + "," + ViewModelConstants.AntiForgeryToken, HttpMethod = "POST")]
[RegularExpression("^[a-zA-Z_]*$", ErrorMessage = "لطفا تنها از حروف انگلیسی استفاده نمائید")]
public string Username { get; set; } // Extending the built-in validator
validateEmail(user, errors); public static void AddCustomServices(this IServiceCollection services)
{
var siteSettings = GetSiteSettings(services);
AddCustomServicesExtensions.AddCustomServices(services); Could not load type 'Identity.CustomNormalizer' from assembly ', Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because the parent type is sealed.
public sealed class UpperInvariantLookupNormalizer : ILookupNormalizer
public class CustomNormalizer : ILookupNormalizer
public class CustomNormalizer : ILookupNormalizer
{
public string NormalizeName(string key)
{
key = Normalize(key);
key = key.ApplyCorrectYeKe()
.RemoveDiacritics()
.CleanUnderLines()
.RemovePunctuation();
key = key.Trim().Replace(" ", "");
return key;
}
public string NormalizeEmail(string key)
{
key = Normalize(key);
key = fixGmailDots(key);
return key;
}
public string Normalize(string key)
{
if (string.IsNullOrWhiteSpace(key))
{
return null;
}
key = key.Trim();
key = key.ToUpperInvariant();
return key;
}
private static string fixGmailDots(string email)
{
email = email.ToLowerInvariant().Trim();
var emailParts = email.Split('@');
var name = emailParts[0].Replace(".", string.Empty);
var plusIndex = name.IndexOf("+", StringComparison.OrdinalIgnoreCase);
if (plusIndex != -1)
{
name = name.Substring(0, plusIndex);
}
var emailDomain = emailParts[1];
emailDomain = emailDomain.Replace("googlemail.com", "gmail.com");
string[] domainsAllowedDots =
{
"gmail.com",
"facebook.com"
};
var isFromDomainsAllowedDots = domainsAllowedDots.Any(domain => emailDomain.Equals(domain));
return !isFromDomainsAllowedDots ? email : string.Format("{0}@{1}", name, emailDomain);
}
} #region Assembly Microsoft.Extensions.Identity.Core, Version=3.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
// C:\Users\kazemi\.nuget\packages\microsoft.extensions.identity.core\3.0.0-preview-18579-0056\lib\netstandard2.0\Microsoft.Extensions.Identity.Core.dll
#endregion
namespace Microsoft.AspNetCore.Identity
{
//
// Summary:
// Provides an abstraction for normalizing keys for lookup purposes.
public interface ILookupNormalizer
{
//
// Summary:
// Returns a normalized representation of the specified key.
//
// Parameters:
// key:
// The key to normalize.
//
// Returns:
// A normalized representation of the specified key.
string Normalize(string key);
}
} dotnet tool update --global dotnet-outdated dotnet outdated -u
dotnet --list-sdks dotnet new globaljson --sdk-version 2.2.106
public interface ILookupNormalizer
{
string Normalize(string key);
} public interface ILookupNormalizer
{
string NormalizeEmail(string email);
string NormalizeName(string name);
} services.AddMvc(options => options.UseYeKeModelBinder())
.AddViewOptions(options => options.HtmlHelperOptions.ClientValidationEnabled = false); foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
} نام کاربری 'admin' هم اکنون مورد استفادهاست. نام کاربری 'admin' هم اکنون مورد استفادهاست.