From ead69ee63a2bae510c38b72b39310eeb399bc350 Mon Sep 17 00:00:00 2001 From: Iman Abidi Date: Sat, 7 Nov 2020 11:30:40 +0100 Subject: [PATCH] Persian errors for identity methods --- RMuseum/Startup.cs | 46 +++---- .../Controllers/AppUserControllerBase.cs | 122 +++++++++--------- .../Services/Implementation/AppUserService.cs | 38 +++--- .../PersianIdentityErrorDescriber.cs | 33 +++++ 4 files changed, 131 insertions(+), 108 deletions(-) create mode 100644 RSecurityBackend/Utilities/PersianIdentityErrorDescriber.cs diff --git a/RMuseum/Startup.cs b/RMuseum/Startup.cs index 8e57af40..e1f5da81 100644 --- a/RMuseum/Startup.cs +++ b/RMuseum/Startup.cs @@ -1,10 +1,4 @@ -using System; -using System.IO; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; -using Audit.Core; -using Audit.WebApi; +using Audit.WebApi; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; @@ -33,6 +27,11 @@ using RSecurityBackend.Services; using RSecurityBackend.Services.Implementation; using RSecurityBackend.Utilities; using Swashbuckle.AspNetCore.Filters; +using System; +using System.IO; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; namespace RMuseum { @@ -66,8 +65,6 @@ namespace RMuseum Audit.Core.Configuration.JsonSettings.ContractResolver = AuditNetEnvironmentSkippingContractResolver.Instance; Audit.Core.Configuration.DataProvider = new RAuditDataProvider(Configuration.GetConnectionString("DefaultConnection")); - - services.AddIdentityCore( options => { @@ -85,29 +82,26 @@ namespace RMuseum options.Lockout.AllowedForNewUsers = true; // User settings. - options.User.AllowedUserNameCharacters = - "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+"; + options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+"; options.User.RequireUniqueEmail = false; } - ); + ).AddErrorDescriber(); + new IdentityBuilder(typeof(RAppUser), typeof(RAppRole), services) .AddRoleManager>() .AddSignInManager>() - .AddEntityFrameworkStores(); - ; + .AddEntityFrameworkStores() + .AddErrorDescriber(); - - services.AddMvc - ( - mvc => + services.AddMvc(mvc => mvc.AddAuditFilter(config => config .LogRequestIf(r => r.Method != "GET") .WithEventType("{controller}/{action} ({verb})") .IncludeHeaders(ctx => !ctx.ModelState.IsValid) .IncludeRequestBody() - .IncludeModelState() + .IncludeModelState() )).SetCompatibilityVersion(CompatibilityVersion.Latest); services.AddMemoryCache(); @@ -155,7 +149,7 @@ namespace RMuseum services.AddAuthorization(options => { //this is the default policy to make sure the use session has not yet been deleted by him/her from another client - //or by an addmin (Authorize with no policy should fail on deleted sessions) + //or by an admin (Authorize with no policy should fail on deleted sessions) var defPolicy = new AuthorizationPolicyBuilder(); defPolicy.Requirements.Add(new UserGroupPermissionRequirement("null", "null")); options.DefaultPolicy = defPolicy.Build(); @@ -202,7 +196,7 @@ namespace RMuseum In = ParameterLocation.Header, Name = "Authorization", Type = SecuritySchemeType.ApiKey - + }); @@ -214,7 +208,7 @@ namespace RMuseum //IHttpContextAccessor services.TryAddSingleton(); - + //authorization handler services.AddScoped(); @@ -227,13 +221,13 @@ namespace RMuseum services.AddTransient(); - //generic image file sercie + //generic image file service services.AddTransient(); //app user services services.AddTransient(); - //user groups servicess + //user groups services services.AddTransient(); //audit service @@ -243,7 +237,7 @@ namespace RMuseum services.AddTransient(); //secret generator - services.AddTransient(); + services.AddTransient(); // email service services.AddTransient(); @@ -301,7 +295,7 @@ namespace RMuseum c.SwaggerEndpoint("/swagger/v1/swagger.json", "RMuseum API V1"); c.RoutePrefix = string.Empty; }); - + app.UseAuthentication(); diff --git a/RSecurityBackend/Controllers/AppUserControllerBase.cs b/RSecurityBackend/Controllers/AppUserControllerBase.cs index fff412b0..3d2eb2b8 100644 --- a/RSecurityBackend/Controllers/AppUserControllerBase.cs +++ b/RSecurityBackend/Controllers/AppUserControllerBase.cs @@ -1,22 +1,21 @@ -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Cors; +using Audit.WebApi; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Configuration; +using RSecurityBackend.Models.Auth.Db; using RSecurityBackend.Models.Auth.Memory; using RSecurityBackend.Models.Auth.ViewModels; using RSecurityBackend.Models.Generic; +using RSecurityBackend.Models.Image; +using RSecurityBackend.Services; using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Net; using System.Threading.Tasks; -using RSecurityBackend.Services; -using Microsoft.AspNetCore.Identity.UI.Services; -using RSecurityBackend.Models.Auth.Db; -using RSecurityBackend.Models.Image; -using System.IO; -using Microsoft.Extensions.Configuration; -using Audit.WebApi; namespace RSecurityBackend.Controllers { @@ -39,13 +38,13 @@ namespace RSecurityBackend.Controllers [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(string))] public async Task Login( [AuditIgnore] - [FromBody] + [FromBody] LoginViewModel loginViewModel ) { string clientIPAddress = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString(); RServiceResult res = await _appUserService.Login(loginViewModel, clientIPAddress); - if(res.Result == null) + if (res.Result == null) { return BadRequest(res.ExceptionString); } @@ -96,16 +95,16 @@ namespace RSecurityBackend.Controllers { Guid loggedOnUserId = new Guid(User.Claims.FirstOrDefault(c => c.Type == "UserId").Value); if (loggedOnUserId != userId) - { - RServiceResult canLogoutAllUsers = + { + RServiceResult canLogoutAllUsers = await _userPermissionChecker.Check ( - loggedOnUserId, - new Guid(User.Claims.FirstOrDefault(c => c.Type == "SessionId").Value), - SecurableItem.UserEntityShortName, - SecurableItem.DelOtherUserSessionOperationShortName + loggedOnUserId, + new Guid(User.Claims.FirstOrDefault(c => c.Type == "SessionId").Value), + SecurableItem.UserEntityShortName, + SecurableItem.DelOtherUserSessionOperationShortName ); - + if (!string.IsNullOrEmpty(canLogoutAllUsers.ExceptionString)) return BadRequest(canLogoutAllUsers.ExceptionString); if (!canLogoutAllUsers.Result) @@ -130,13 +129,13 @@ namespace RSecurityBackend.Controllers [Authorize] [Route("checkmysession")] [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(IEnumerable))] - [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(string))] + [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(string))] public async Task IsSessionValid(Guid sessionId) { Guid loggedOnUserId = new Guid(User.Claims.FirstOrDefault(c => c.Type == "UserId").Value); RServiceResult res = await _appUserService.SessionExists(loggedOnUserId, sessionId); - + if (!string.IsNullOrEmpty(res.ExceptionString)) { return BadRequest(res.ExceptionString); @@ -159,12 +158,12 @@ namespace RSecurityBackend.Controllers { Guid loggedOnUserId = new Guid(User.Claims.FirstOrDefault(c => c.Type == "UserId").Value); - RServiceResult canViewAllUsersInformation = + RServiceResult canViewAllUsersInformation = await _userPermissionChecker.Check ( - loggedOnUserId, - new Guid(User.Claims.FirstOrDefault(c => c.Type == "SessionId").Value), - SecurableItem.UserEntityShortName, + loggedOnUserId, + new Guid(User.Claims.FirstOrDefault(c => c.Type == "SessionId").Value), + SecurableItem.UserEntityShortName, SecurableItem.ViewAllOperationShortName ); if (!string.IsNullOrEmpty(canViewAllUsersInformation.ExceptionString)) @@ -206,15 +205,15 @@ namespace RSecurityBackend.Controllers { Guid loggedOnUserId = new Guid(User.Claims.FirstOrDefault(c => c.Type == "UserId").Value); - if(loggedOnUserId != id) + if (loggedOnUserId != id) { - RServiceResult canViewAllUsersInformation = + RServiceResult canViewAllUsersInformation = await _userPermissionChecker.Check ( - loggedOnUserId, - new Guid(User.Claims.FirstOrDefault(c => c.Type == "SessionId").Value), - SecurableItem.UserEntityShortName, - SecurableItem.ViewAllOperationShortName + loggedOnUserId, + new Guid(User.Claims.FirstOrDefault(c => c.Type == "SessionId").Value), + SecurableItem.UserEntityShortName, + SecurableItem.ViewAllOperationShortName ); if (!string.IsNullOrEmpty(canViewAllUsersInformation.ExceptionString)) return BadRequest(canViewAllUsersInformation.ExceptionString); @@ -223,7 +222,7 @@ namespace RSecurityBackend.Controllers return Forbid(); } - + RServiceResult userInfo = await _appUserService.GetUserInformation(id); if (userInfo.Result == null) { @@ -234,7 +233,7 @@ namespace RSecurityBackend.Controllers return Ok(userInfo.Result); } - + /// /// add a new user (if you are trying to add an admin user you yourself should be admin) /// @@ -245,17 +244,17 @@ namespace RSecurityBackend.Controllers [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(RegisterRAppUser))] [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(string))] [ProducesResponseType((int)HttpStatusCode.Forbidden)] - public virtual async Task Post([FromBody]RegisterRAppUser newUserInfo) + public virtual async Task Post([FromBody] RegisterRAppUser newUserInfo) { Guid loggedOnUserId = new Guid(User.Claims.FirstOrDefault(c => c.Type == "UserId").Value); - if(newUserInfo.IsAdmin) + if (newUserInfo.IsAdmin) { RServiceResult isAdmin = await _appUserService.IsAdmin(loggedOnUserId); if (!string.IsNullOrEmpty(isAdmin.ExceptionString)) return BadRequest(isAdmin.ExceptionString); if (!isAdmin.Result) return Forbid();//Only admin users can create admin users - } + } RServiceResult result = await _appUserService.AddUser(newUserInfo); if (result.Result == null) return BadRequest(result.ExceptionString); @@ -285,7 +284,7 @@ namespace RSecurityBackend.Controllers [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(bool))] [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(string))] [ProducesResponseType((int)HttpStatusCode.Forbidden)] - public virtual async Task Put(Guid id, [FromBody]RegisterRAppUser existingUserInfo) + public virtual async Task Put(Guid id, [FromBody] RegisterRAppUser existingUserInfo) { Guid loggedOnUserId = new Guid(User.Claims.FirstOrDefault(c => c.Type == "UserId").Value); RServiceResult isAdmin = await _appUserService.IsAdmin(loggedOnUserId); @@ -294,16 +293,16 @@ namespace RSecurityBackend.Controllers RServiceResult userInfo = await _appUserService.GetUserInformation(id); if (!isAdmin.Result) { - + if (!string.IsNullOrEmpty(userInfo.ExceptionString)) return BadRequest(userInfo.ExceptionString); - + if (existingUserInfo.IsAdmin) return Forbid();//You should be admin to make other users admin RServiceResult isEditingUserAdmin = await _appUserService.IsAdmin(id); if (!string.IsNullOrEmpty(isEditingUserAdmin.ExceptionString)) return BadRequest(isEditingUserAdmin.ExceptionString); - if(isEditingUserAdmin.Result) + if (isEditingUserAdmin.Result) return Forbid();//You can not modify admin users. if (loggedOnUserId != id) @@ -350,7 +349,7 @@ namespace RSecurityBackend.Controllers [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(bool))] [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(string))] [ProducesResponseType((int)HttpStatusCode.Forbidden)] - public virtual async Task SetMyPassword([AuditIgnore][FromBody]SetPasswordModel model) + public virtual async Task SetMyPassword([AuditIgnore][FromBody] SetPasswordModel model) { Guid loggedOnUserId = new Guid(User.Claims.FirstOrDefault(c => c.Type == "UserId").Value); @@ -388,7 +387,7 @@ namespace RSecurityBackend.Controllers return Forbid();//You can not delete admin users. } - if(loggedOnUserId == id) + if (loggedOnUserId == id) { return BadRequest("SOS! Suicide attempt detected!"); } @@ -448,7 +447,7 @@ namespace RSecurityBackend.Controllers loggedOnUserId, new Guid(User.Claims.FirstOrDefault(c => c.Type == "SessionId").Value), SecurableItem.UserEntityShortName, - SecurableItem.SessionsOperationShortName + SecurableItem.SessionsOperationShortName ); if (!string.IsNullOrEmpty(canViewAllUsersInformation.ExceptionString)) return BadRequest(canViewAllUsersInformation.ExceptionString); @@ -479,8 +478,8 @@ namespace RSecurityBackend.Controllers public async Task SetUserImage() { try - { - if(!Request.Form.TryGetValue("id", out Microsoft.Extensions.Primitives.StringValues tmp)) + { + if (!Request.Form.TryGetValue("id", out Microsoft.Extensions.Primitives.StringValues tmp)) { return BadRequest("id is null"); } @@ -508,19 +507,19 @@ namespace RSecurityBackend.Controllers RServiceResult res = await _appUserService.SetUserImage(userId, Request.Form.Files); - if(!string.IsNullOrEmpty(res.ExceptionString)) + if (!string.IsNullOrEmpty(res.ExceptionString)) { return BadRequest(res.ExceptionString); } - if(res.Result == null) + if (res.Result == null) { return Ok(""); } return Ok(res.Result.ToString()); } - catch(Exception exp) + catch (Exception exp) { return BadRequest(exp.ToString()); } @@ -553,7 +552,7 @@ namespace RSecurityBackend.Controllers RServiceResult imgPath = _imageFileService.GetImagePath(img.Result); if (!string.IsNullOrEmpty(imgPath.ExceptionString)) - return BadRequest(imgPath.ExceptionString); + return BadRequest(imgPath.ExceptionString); return new ObjectResult(Convert.ToBase64String(System.IO.File.ReadAllBytes(imgPath.Result))); @@ -582,7 +581,7 @@ namespace RSecurityBackend.Controllers { RServiceResult img = await _appUserService.GetUserImage(id); - if(!string.IsNullOrEmpty(img.ExceptionString)) + if (!string.IsNullOrEmpty(img.ExceptionString)) { return BadRequest(img.ExceptionString); @@ -668,7 +667,7 @@ namespace RSecurityBackend.Controllers public async Task RemoveFromRole(Guid id, string role) { Guid loggedOnUserId = new Guid(User.Claims.FirstOrDefault(c => c.Type == "UserId").Value); - if(loggedOnUserId == id) + if (loggedOnUserId == id) { return BadRequest("You cannot modify your own roles."); } @@ -684,7 +683,7 @@ namespace RSecurityBackend.Controllers return Forbid();//You can not delete admin users roles. } - + RServiceResult res = await _appUserService.RemoveFromRole(id, role); if (!res.Result) @@ -757,7 +756,7 @@ namespace RSecurityBackend.Controllers return Ok(img.Result.Id); } - + /// /// signup @@ -769,19 +768,16 @@ namespace RSecurityBackend.Controllers [Route("signup")] [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(bool))] [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(string))] - public async Task SignUp( - [FromBody] - UnverifiedSignUpViewModel signUpViewModel - ) + public async Task SignUp([FromBody] UnverifiedSignUpViewModel signUpViewModel) { if (!IsSignupEnabled()) return BadRequest("ثبت نام غیرفعال است."); - RServiceResult captchaRes = await _captchaService.Evaluate(signUpViewModel.CaptchaImageId, signUpViewModel.CaptchaValue); + RServiceResult captchaRes = await _captchaService.Evaluate(signUpViewModel.CaptchaImageId, signUpViewModel.CaptchaValue); if (!string.IsNullOrEmpty(captchaRes.ExceptionString)) return BadRequest(captchaRes.ExceptionString); - if(!captchaRes.Result) + if (!captchaRes.Result) return BadRequest("مقدار تصویر امنیتی درست وارد نشده است."); string clientIPAddress = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString(); @@ -800,7 +796,7 @@ namespace RSecurityBackend.Controllers GetSignUpEmailHtmlContent(res.Result.Secret) ); } - catch(Exception exp) + catch (Exception exp) { return BadRequest("Error sending email: " + exp.ToString()); } @@ -853,7 +849,7 @@ namespace RSecurityBackend.Controllers } if (string.IsNullOrWhiteSpace(res.Result)) { - return NotFound(); + return NotFound("رمز وارد شده تطابق ندارد"); } return Ok(res.Result); } @@ -869,7 +865,7 @@ namespace RSecurityBackend.Controllers [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(bool))] [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(string))] [ProducesResponseType((int)HttpStatusCode.NotFound)] - public async Task FinalizeSignUp([AuditIgnore][FromBody]VerifiedSignUpViewModel newUserInfo) + public async Task FinalizeSignUp([AuditIgnore][FromBody] VerifiedSignUpViewModel newUserInfo) { RServiceResult result = await _appUserService.FinalizeSignUp(newUserInfo.Email, newUserInfo.Secret, newUserInfo.Password, newUserInfo.FirstName, newUserInfo.SureName); if (!result.Result) @@ -912,7 +908,7 @@ namespace RSecurityBackend.Controllers await _emailSender.SendEmailAsync ( fpwdViewModel.Email, - GetForgotPasswordEmailSubject( res.Result.Secret), + GetForgotPasswordEmailSubject(res.Result.Secret), GetForgotPasswordEmailHtmlContent(res.Result.Secret) ); } @@ -966,7 +962,7 @@ namespace RSecurityBackend.Controllers [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(bool))] [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(string))] [ProducesResponseType((int)HttpStatusCode.NotFound)] - public async Task ResetPassword([AuditIgnore][FromBody]ResetPasswordViewModel pwd) + public async Task ResetPassword([AuditIgnore][FromBody] ResetPasswordViewModel pwd) { string clientIPAddress = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString(); RServiceResult result = await _appUserService.ResetPassword(pwd.Email, pwd.Secret, pwd.Password, clientIPAddress); diff --git a/RSecurityBackend/Services/Implementation/AppUserService.cs b/RSecurityBackend/Services/Implementation/AppUserService.cs index 74b859f9..59ea62d9 100644 --- a/RSecurityBackend/Services/Implementation/AppUserService.cs +++ b/RSecurityBackend/Services/Implementation/AppUserService.cs @@ -213,7 +213,7 @@ namespace RSecurityBackend.Services.Implementation if (dbUserInfo == null) { - return new RServiceResult(false, $"User not found"); + return new RServiceResult(false, $"کاربر مورد نظر با ایمیل {userId} پیدا نشد "); } if (!await _roleManager.RoleExistsAsync(roleName)) @@ -384,7 +384,7 @@ namespace RSecurityBackend.Services.Implementation RAppUser dbUserInfo = await _userManager.FindByIdAsync(userId.ToString()); if (dbUserInfo == null) { - return new RServiceResult(false, "user not found"); + return new RServiceResult(false, "کاربر مورد نظر یافت نشد"); } bool res = await _userManager.IsInRoleAsync(dbUserInfo, AdministratorRoleName); @@ -409,7 +409,7 @@ namespace RSecurityBackend.Services.Implementation RAppUser dbUserInfo = await _userManager.FindByIdAsync(userId.ToString()); if (dbUserInfo == null) { - return new RServiceResult(false, "user not found"); + return new RServiceResult(false, "کاربر مورد نظر یافت نشد"); } foreach(string roleName in roleNames) @@ -442,7 +442,7 @@ namespace RSecurityBackend.Services.Implementation RAppUser dbUserInfo = await _userManager.FindByIdAsync(userId.ToString()); if (dbUserInfo == null) { - return new RServiceResult>(null, "user not found"); + return new RServiceResult>(null, "کاربر مورد نظر یافت نشد"); } return new RServiceResult>(await _userManager.GetRolesAsync(dbUserInfo)); @@ -466,7 +466,7 @@ namespace RSecurityBackend.Services.Implementation RAppUser dbUserInfo = await _userManager.FindByIdAsync(id.ToString()); if (dbUserInfo == null) { - return new RServiceResult(false, "user not found"); + return new RServiceResult(false, "کاربر مورد نظر یافت نشد"); } IdentityResult result = await _userManager.RemoveFromRoleAsync(dbUserInfo, role); @@ -496,7 +496,7 @@ namespace RSecurityBackend.Services.Implementation RAppUser dbUserInfo = await _userManager.FindByIdAsync(id.ToString()); if (dbUserInfo == null) { - return new RServiceResult(false, "user not found"); + return new RServiceResult(false, "کاربر مورد نظر یافت نشد"); } IdentityResult result = await _userManager.AddToRoleAsync(dbUserInfo, role); @@ -688,7 +688,7 @@ namespace RSecurityBackend.Services.Implementation RAppUser existingInfo = await _userManager.FindByIdAsync(userId.ToString()); if (existingInfo == null) { - return new RServiceResult(false, "username not found"); + return new RServiceResult(false, "کاربر مورد نظر یافت نشد"); } RServiceResult isAdmin = await IsAdmin(userId); @@ -720,7 +720,7 @@ namespace RSecurityBackend.Services.Implementation if(anotheruserWithUserName != null) { - return new RServiceResult(false, "duplicated username"); + return new RServiceResult(false, "کلمه عبور تکراری می باشد"); } existingInfo.UserName = updateUserInfo.Username; @@ -782,7 +782,7 @@ namespace RSecurityBackend.Services.Implementation if (appUser == null) { - return new RServiceResult(false, "Invalid user."); + return new RServiceResult(false, "کاربر مورد نظر یافت نشد"); } var result = await _userManager.ChangePasswordAsync(appUser, oldPassword, newPassword); @@ -816,7 +816,7 @@ namespace RSecurityBackend.Services.Implementation } return new RServiceResult(true); } - return new RServiceResult(false, "user not found."); + return new RServiceResult(false, "کاربر مورد نظر یافت نشد"); } catch (Exception exp) { @@ -972,13 +972,13 @@ namespace RSecurityBackend.Services.Implementation RAppUser existingUser = await _userManager.FindByEmailAsync(email); if (existingUser != null) { - return new RServiceResult(null, "user already registered using same email"); + return new RServiceResult(null, "این آدرس ایمیل قبلا استفاده شده است"); } existingUser = await _userManager.FindByNameAsync(email); if (existingUser != null) { - return new RServiceResult(null, "user already registered using same username"); + return new RServiceResult(null, "این نام کاربری قبلا استفاده شده است"); } //checking this queue for previous signup attempts is unnecessary and is not done intentionally @@ -1056,13 +1056,13 @@ namespace RSecurityBackend.Services.Implementation RAppUser existingUser = await _userManager.FindByEmailAsync(email); if (existingUser != null) { - return new RServiceResult(false, "user already registered using same email"); + return new RServiceResult(false, "این آدرس ایمیل قبلا استفاده شده است"); } existingUser = await _userManager.FindByNameAsync(email); if (existingUser != null) { - return new RServiceResult(false, "user already registered using same username"); + return new RServiceResult(false, "این نام کاربری قبلا استفاده شده است"); } if( @@ -1071,7 +1071,7 @@ namespace RSecurityBackend.Services.Implementation (await RetrieveEmailFromQueueSecret(RVerifyQueueType.SignUp, secret)).Result ) { - return new RServiceResult(false, "secret mismatch"); + return new RServiceResult(false, "کلمه عبور اشتباه وارد شده است"); } secret = secret.Replace(" ", "");//TODO: check this @@ -1138,7 +1138,7 @@ namespace RSecurityBackend.Services.Implementation RAppUser rAppUser = await _userManager.FindByEmailAsync(email); if (rAppUser == null) { - return new RServiceResult(null, "user not found"); + return new RServiceResult(null, "کاربر مورد نظر یافت نشد"); } //checking this queue for previous signup attempts is unnecessary and is not done intentionally @@ -1201,7 +1201,7 @@ namespace RSecurityBackend.Services.Implementation RAppUser existingUser = await _userManager.FindByEmailAsync(email); if (existingUser == null) { - return new RServiceResult(false, "user not found"); + return new RServiceResult(false, "کاربر مورد نظر با این آدرس ایمیل یافت نشد"); } @@ -1211,7 +1211,7 @@ namespace RSecurityBackend.Services.Implementation (await RetrieveEmailFromQueueSecret(RVerifyQueueType.ForgotPassword, secret)).Result ) { - return new RServiceResult(false, "secret mismatch"); + return new RServiceResult(false, "کلمه عبور اشتباه وارد شده است"); } foreach (var passwordValidator in _userManager.PasswordValidators) @@ -1350,7 +1350,7 @@ namespace RSecurityBackend.Services.Implementation { var user = await _userManager.FindByIdAsync(userId.ToString()); if (user == null) - return new RServiceResult(null, "user not found"); + return new RServiceResult(null, "کاربر مورد نظر یافت نشد"); var claims = new List { diff --git a/RSecurityBackend/Utilities/PersianIdentityErrorDescriber.cs b/RSecurityBackend/Utilities/PersianIdentityErrorDescriber.cs new file mode 100644 index 00000000..66a29980 --- /dev/null +++ b/RSecurityBackend/Utilities/PersianIdentityErrorDescriber.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Text; +using Microsoft.AspNetCore.Identity; + +namespace RSecurityBackend.Utilities +{ + public class PersianIdentityErrorDescriber : IdentityErrorDescriber + { + public override IdentityError DefaultError() => new IdentityError { Code = nameof(DefaultError), Description = $"یک خطای ناشناخته رخ داده است." }; + public override IdentityError ConcurrencyFailure() => new IdentityError { Code = nameof(ConcurrencyFailure), Description = "رکورد جاری پیشتر ویرایش شده‌است و تغییرات شما آن‌را بازنویسی خواهد کرد." }; + public override IdentityError PasswordMismatch() => new IdentityError { Code = nameof(PasswordMismatch), Description = "کلمه عبور نادرست است." }; + public override IdentityError InvalidToken() => new IdentityError { Code = nameof(InvalidToken), Description = "کلمه عبور نامعتبر است." }; + public override IdentityError LoginAlreadyAssociated() => new IdentityError { Code = nameof(LoginAlreadyAssociated), Description = "این کاربر قبلأ اضافه شده‌است." }; + public override IdentityError InvalidUserName(string userName) => new IdentityError { Code = nameof(InvalidUserName), Description = $"نام کاربری '{userName}' نامعتبر است، فقط می تواند حاوی حروف ویا اعداد باشد." }; + public override IdentityError InvalidEmail(string email) => new IdentityError { Code = nameof(InvalidEmail), Description = $"ایمیل '{email}' نامعتبر است." }; + public override IdentityError DuplicateUserName(string userName) => new IdentityError { Code = nameof(DuplicateUserName), Description = $"این نام کاربری '{userName}' به کاربر دیگری اختصاص یافته است." }; + public override IdentityError DuplicateEmail(string email) => new IdentityError { Code = nameof(DuplicateEmail), Description = $"ایمیل '{email}' به کاربر دیگری اختصاص یافته است." }; + public override IdentityError InvalidRoleName(string role) => new IdentityError { Code = nameof(InvalidRoleName), Description = $"نام نقش '{role}' نامعتبر است." }; + public override IdentityError DuplicateRoleName(string role) => new IdentityError { Code = nameof(DuplicateRoleName), Description = $"این نام نقش '{role}' به کاربر دیگری اختصاص یافته است." }; + public override IdentityError UserAlreadyHasPassword() => new IdentityError { Code = nameof(UserAlreadyHasPassword), Description = "کلمه‌ی عبور کاربر قبلأ تنظیم شده‌است." }; + public override IdentityError UserLockoutNotEnabled() => new IdentityError { Code = nameof(UserLockoutNotEnabled), Description = "این کاربر فعال است." }; + public override IdentityError UserAlreadyInRole(string role) => new IdentityError { Code = nameof(UserAlreadyInRole), Description = $"این نقش '{role}' قبلأ به این کاربر اختصاص یافته است." }; + public override IdentityError UserNotInRole(string role) => new IdentityError { Code = nameof(UserNotInRole), Description = $"این نقش '{role}' قبلأ به این کاربر اختصاص نیافته است." }; + public override IdentityError PasswordTooShort(int length) => new IdentityError { Code = nameof(PasswordTooShort), Description = $"کلمه عبور باید حداقل {length} کاراکتر باشد." }; + public override IdentityError PasswordRequiresNonAlphanumeric() => new IdentityError { Code = nameof(PasswordRequiresNonAlphanumeric), Description = "کلمه عبور باید حداقل یک کاراکتر غیر از حروف الفبا داشته باشد." }; + public override IdentityError PasswordRequiresDigit() => new IdentityError { Code = nameof(PasswordRequiresDigit), Description = "کلمه عبور باید حداقل یک عدد داشته باشد." }; + public override IdentityError PasswordRequiresLower() => new IdentityError { Code = nameof(PasswordRequiresLower), Description = "کلمه عبور باید حداقل یک حرف کوچک داشته باشد." }; + public override IdentityError PasswordRequiresUpper() => new IdentityError { Code = nameof(PasswordRequiresUpper), Description = "کلمه عبور باید حداقل یک حرف بزرگ داشته باشد." }; + public override IdentityError RecoveryCodeRedemptionFailed() => new IdentityError { Code = nameof(RecoveryCodeRedemptionFailed), Description = "بازیابی ناموفق بود." }; + public override IdentityError PasswordRequiresUniqueChars(int uniqueChars) => new IdentityError { Code = nameof(PasswordRequiresUniqueChars), Description = $"کلمه عبور باید حداقل داراى {uniqueChars} حرف متفاوت باشد." }; + } +}