//for IdentityCookie private async Task <ClaimsPrincipal> GetApplicationPrincipalAsync(AppUserEntity entity) { var principal = await _signInManager.CreateUserPrincipalAsync(entity); var identity = principal.Identity as ClaimsIdentity; identity.AddClaim(new Claim(ClaimTypes.Name, $"{entity.Id}")); var claims = new List <Claim>(); var roles = await _userManager.GetRolesAsync(entity); foreach (var r in roles) { claims.Add(new Claim(ClaimTypes.Role, r)); } identity.AddClaims(claims); return(principal); }
private async Task <Result <AppUserEntity> > GetAppUser() { string userId = _identityUIUserInfoService.GetUserId(); AppUserEntity appUser = await _userManager.FindByIdAsync(userId); if (appUser == null) { _logger.LogError($"No user. UserId {userId}"); return(Result.Fail <AppUserEntity>("No User", "no_user")); } if (appUser.TwoFactorEnabled) { _logger.LogError($"User already has TwoFactorAuthentication enabled. UserId {userId}"); return(Result.Fail <AppUserEntity>("2fa_already_enabled", "Two factor authentication is already enabled")); } return(Result.Ok(appUser)); }
public async Task <IActionResult> Create(AddUserViewModel model) { if (ModelState.IsValid) { model.UserTypeId = 1; var user = await AddUser(model); if (user == null) { ModelState.AddModelError(string.Empty, "Este email ya existe."); model.UserTypes = _combosHelper.GetComboUserTypes(); return(View(model)); } var appUser = new AppUserEntity { User = user, }; _dataContext.AppUsers.Add(appUser); await _dataContext.SaveChangesAsync(); var myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user); var tokenLink = Url.Action("ConfirmEmail", "Account", new { userid = user.Id, token = myToken }, protocol: HttpContext.Request.Scheme); _mailHelper.SendMail(model.Username, "Confirmación de E-Mail", $"<h1>Confirmación de E-Mail</h1>" + $"Para habilitar el Usuario, " + $"por favor haga clic en el siguiente link: </br></br><a href = \"{tokenLink}\">Confirmar E-mail</a>"); ViewBag.Message = "Las instrucciones para habilitar su Usuario han sido enviadas por mail."; return(View(model)); } model.UserTypes = _combosHelper.GetComboUserTypes(); return(View(model)); }
public async Task <Result> ResetPassword(ResetPasswordRequest request) { ValidationResult validationResult = _recoverPasswordValidator.Validate(request); if (!validationResult.IsValid) { _logger.LogWarning($"Invlid RecoverPassword request"); return(Result.Fail(validationResult.Errors)); } AppUserEntity appUser = await _userManager.FindByEmailAsync(request.Email); if (appUser == null) { _logger.LogWarning($"No user. Email {request.Email}"); return(Result.Ok()); } bool emailConfirmed = await _userManager.IsEmailConfirmedAsync(appUser); if (!emailConfirmed || !appUser.Enabled || appUser.LockoutEnd != null) { _logger.LogWarning($"User email not confirmed. UserId {appUser.Id}"); return(Result.Ok()); } string code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(request.Code)); IdentityResult identityResult = await _userManager.ResetPasswordAsync(appUser, code, request.Password); if (!identityResult.Succeeded) { _logger.LogWarning($"Faild to reset password for user. User {appUser.Id}"); return(Result.Fail(identityResult.Errors)); } await _emailSender.SendEmailAsync(appUser.Email, "Password changed", $"Your password has been changed"); _logger.LogInformation($"Password reset. UserId {appUser.Id}"); return(Result.Ok()); }
private async Task <Result <IEnumerable <string> > > AddTwoFactorAuthentication(string userId, TwoFactorAuthenticationType twoFactorAuthenticationType, string token) { AppUserEntity appUser = await _userManager.FindByIdAsync(userId); if (appUser == null) { _logger.LogError($"No user. UserId {userId}"); return(Result.Fail <IEnumerable <string> >("no_user", "No User")); } bool isCodeValid = await _userManager.VerifyTwoFactorTokenAsync(appUser, twoFactorAuthenticationType.ToProvider(), token); if (!isCodeValid) { _logger.LogError($"Invalid TwoFactor Verification code. User {userId}"); return(Result.Fail <IEnumerable <string> >("invlid_code", "Invalid Code")); } await _userManager.SetTwoFactorEnabledAsync(appUser, true); appUser.TwoFactor = twoFactorAuthenticationType; if (twoFactorAuthenticationType == TwoFactorAuthenticationType.Phone) { appUser.PhoneNumberConfirmed = true; //HACK: try to do this before you add 2fa } await _userManager.UpdateAsync(appUser); _logger.LogInformation($"TwoFactorAuthentication enabled. User {appUser.Id}"); Result loginResult = await _loginService.Login(userId); if (loginResult.Failure) { _logger.LogError($"Failed to login user after enabling 2fa. UserId {userId}"); } IEnumerable <string> recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(appUser, _identityUIEndpoints.NumberOfRecoveryCodes); return(Result.Ok(recoveryCodes)); }
public async Task <Result> SetNewPassword(string userId, SetNewPasswordRequest setNewPasswordRequest, string adminId) { ValidationResult validationResult = _setNewPasswordValidator.Validate(setNewPasswordRequest); if (!validationResult.IsValid) { _logger.LogError($"Invlid SetNewPasswordRequest. Admin {adminId}"); return(Result.Fail(ResultUtils.ToResultError(validationResult.Errors))); } AppUserEntity appUser = await _userManager.FindByIdAsync(userId); if (appUser == null) { _logger.LogError($"No User with id {userId}. Admin {adminId}"); return(Result.Fail("no_user", "No User")); } _logger.LogInformation($"Seting new password for with id {userId}. Admin id {adminId}"); string passwordResetToken = await _userManager.GeneratePasswordResetTokenAsync(appUser); IdentityResult changePasswordResult = await _userManager.ResetPasswordAsync(appUser, passwordResetToken, setNewPasswordRequest.Password); if (!changePasswordResult.Succeeded) { _logger.LogError($"Faild to reset password. UserId {appUser.Id}, admin {adminId}"); return(Result.Fail(changePasswordResult.Errors)); } Result logoutUserResult = await _sessionService.LogoutUser(new Auth.Session.Models.LogoutUserSessionsRequest(appUser.Id), adminId); if (logoutUserResult.Failure) { return(logoutUserResult); } _logger.LogInformation($"Added new password to user with id {userId}. Admin id {adminId}"); return(Result.Ok()); }
public async Task <Result> RemoveExternalLogin() { string userId = _httpContextAccessor.HttpContext.User.GetUserId(); AppUserEntity appUser = await _userManager.FindByIdAsync(userId); if (appUser == null) { _logger.LogError($"No User. UserId {userId}"); return(Result.Fail("no_user", "No User")); } _logger.LogTrace($"Removing external login provider. UserId {userId}"); IList <UserLoginInfo> loginProviders = await _userManager.GetLoginsAsync(appUser); UserLoginInfo userLoginInfo = loginProviders.SingleOrDefault(); //TODO: only support one login provider if (userLoginInfo == null) { _logger.LogWarning($"User does not have a external login provider. UserId {userId}"); return(Result.Ok()); } IdentityResult identityResult = await _userManager.RemoveLoginAsync(appUser, userLoginInfo.LoginProvider, userLoginInfo.ProviderKey); if (!identityResult.Succeeded) { _logger.LogError($"Failed to remove external login provider. UserId {userId}"); return(Result.Fail("failed_to_remove_external_login_provider", "Failed to remove external login provider")); } Result loginResult = await _loginService.Login(userId); if (loginResult.Failure) { _logger.LogError($"Failed to log in user after external login provider was removed. UserId {userId}"); } return(Result.Ok()); }
public Result EditUser(string id, EditProfileRequest editProfileRequest) { ValidationResult validationResult = _editProfileValidator.Validate(editProfileRequest); if (!validationResult.IsValid) { _logger.LogWarning($"Invlid EditProfileRequest. UserId {id}"); return(Result.Fail(validationResult.Errors)); } BaseSpecification <AppUserEntity> userSpecification = new BaseSpecification <AppUserEntity>(); userSpecification.AddFilter(x => x.Id == id); AppUserEntity appUser = _userRepository.SingleOrDefault(userSpecification); if (appUser == null) { _logger.LogWarning($"No User. UserId {id}"); return(Result.Fail("no_user", "No user")); } appUser.FirstName = editProfileRequest.FirstName; appUser.LastName = editProfileRequest.LastName; if (appUser.PhoneNumber != editProfileRequest.PhoneNumber) { appUser.PhoneNumber = editProfileRequest.PhoneNumber; appUser.PhoneNumberConfirmed = false; } bool updateResult = _userRepository.Update(appUser); if (!updateResult) { _logger.LogError($"Faild to update user. UserId {id}"); return(Result.Fail("error", "Error")); } return(Result.Ok()); }
public async Task <Result> AddRoles(string userId, List <string> roles, string adminId) { AppUserEntity appUser = await _userManager.FindByIdAsync(userId); if (appUser == null) { _logger.LogError($"No user {userId}"); return(Result.Fail("no_user", "No User")); } IdentityResult result = await _userManager.AddToRolesAsync(appUser, roles); if (!result.Succeeded) { _logger.LogError($"Admin with id {adminId} faild to add roles to user with id {userId}"); return(Result.Fail(ResultUtils.ToResultError(result.Errors))); } _logger.LogInformation($"Admin with id {adminId} added roles to user with id {userId}. Role ids: {Newtonsoft.Json.JsonConvert.SerializeObject(roles)}"); return(Result.Ok()); }
public AppUserEntity GetAppUser(string username) { // find the id associated with username try { Guid userId = checkNetDbContext.AspnetUsers.Where(u => u.UserName == username.Trim()).FirstOrDefault().UserId; AspnetAppUsers aspnetAppUserModel = checkNetDbContext.AspnetAppUsers.Find(userId); // find the appuser with this id and construct entity AppUserEntity appUserEntity = AppUserFactory.Create(aspnetAppUserModel.UserId, aspnetAppUserModel.FkAspnetAppCustomersCustNo , aspnetAppUserModel.CurrentUserProviderKey, aspnetAppUserModel.SelectedFileGroup, aspnetAppUserModel.SelectedFileGuid , aspnetAppUserModel.StatusCode, aspnetAppUserModel.EmailAddress, aspnetAppUserModel.FirstName, aspnetAppUserModel.LastName , aspnetAppUserModel.ReceiveStatusEmails, aspnetAppUserModel.ExportType, aspnetAppUserModel.LastUpdatedBy , aspnetAppUserModel.LastUpdateDate, aspnetAppUserModel.FileUploadMode); return(appUserEntity); }catch (NullReferenceException e) { return(null); } }
public async Task <Result <AddEmailTwoFactorAuthenticationViewModel> > GetEmailViewModel() { Result <AppUserEntity> getAppUserResult = await GetAppUser(); if (getAppUserResult.Failure) { return(Result.Fail <AddEmailTwoFactorAuthenticationViewModel>(getAppUserResult.Errors)); } AppUserEntity appUser = getAppUserResult.Value; if (string.IsNullOrEmpty(appUser.Email)) { _logger.LogError($"User does not have a phone number"); return(Result.Fail <AddEmailTwoFactorAuthenticationViewModel>("no_email_address", "No Email address")); } AddEmailTwoFactorAuthenticationViewModel emailTwoFactorAuthenticationViewModel = new AddEmailTwoFactorAuthenticationViewModel(); return(Result.Ok(emailTwoFactorAuthenticationViewModel)); }
/// <summary> /// 修改用户状态 /// </summary> /// <param name="keyValue">主键值</param> /// <param name="State">状态:1-启动;0-禁用</param> public void UpdateState(string keyValue, int State) { try { service.UpdateState(keyValue, State); CacheFactory.Cache().RemoveCache(cacheKey); if (State == 0) { UpdateIMUserList(keyValue, false, null); } else { AppUserEntity entity = service.GetEntity(keyValue); UpdateIMUserList(keyValue, true, entity); } } catch (Exception) { throw; } }
/// <summary> /// 登录验证 /// </summary> /// <param name="username">用户名</param> /// <param name="password">密码</param> /// <returns></returns> public AppUserEntity CheckLogin(string username, string password) { AppUserEntity userEntity = service.CheckLogin(username); if (userEntity != null) { if (!(bool)userEntity.IsLocked) { //string clientdbPassword = Md5Helper.MD5(DESEncrypt.Decrypt(password, userEntity.Password).ToLower(), 32).ToLower(); string dbPassword = CEncoder.Decode(userEntity.Password); dbPassword = Md5Helper.MD5(dbPassword, 32).ToLower(); if (dbPassword == password) { DateTime LastVisit = DateTime.Now; //int LogOnCount = (userEntity.LogOnCount).ToInt() + 1; //if (userEntity.LastLoginTime != null) //{ // userEntity.LastLoginTime = userEntity.LastLoginTime.ToDate(); //} //userEntity.LastLoginTime = LastLoginTime; //userEntity.LogOnCount = LogOnCount; //userEntity.UserOnLine = 1; service.UpdateEntity(userEntity); return(userEntity); } else { throw new Exception("密码和账户名不匹配"); } } else { throw new Exception("账户名被系统锁定,请联系管理员"); } } else { throw new Exception("账户不存在,请重新输入"); } }
public async Task RegisterAsync(RegisterModel model) { #region Validation var userInfo = contextProvider.BusinessContext.PrincipalInfo; var validationData = new ValidationData(resultLocalizer); // validation logic here if (!validationData.IsValid) { throw validationData.BuildException(); } #endregion IdentityResult result; using (var trans = dbContext.Database.BeginTransaction()) { var appUser = new AppUserEntity { UserName = model.Username, FullName = model.FullName, Email = model.Email }; result = await CreateUserWithRolesTransactionAsync(appUser, model.Password); if (result.Succeeded) { trans.Commit(); return; } } foreach (var err in result.Errors) { validationData.Fail(code: ResultCode.Identity_FailToRegisterUser, data: err); } throw validationData.BuildException(); }
private static void Seed(string emailDomain, string password, UserManager <AppUserEntity> userManager, RoleManager <RoleEntity> roleManager, ILogger logger) { AppUserEntity[] sampleUsers = new AppUserEntity[] { new AppUserEntity { FirstName = "Carson", LastName = "Alexander", UserName = $"carson.alexander@{emailDomain}", Email = $"carson.alexander@{emailDomain}", EmailConfirmed = true, Enabled = true }, new AppUserEntity { FirstName = "Meredith", LastName = "Alonso", UserName = $"merdith.alonso@{emailDomain}", Email = $"merdith.alonso@{emailDomain}", EmailConfirmed = true, Enabled = true }, new AppUserEntity { FirstName = "Arturo", LastName = "Anand", UserName = $"arturo.anad@{emailDomain}", Email = $"arturo.anad@{emailDomain}", EmailConfirmed = true, Enabled = true }, new AppUserEntity { FirstName = "Gytis", LastName = "Barzdukas", UserName = $"gytis.barzdukas@{emailDomain}", Email = $"gytis.barzdukas@{emailDomain}", EmailConfirmed = true }, new AppUserEntity { FirstName = "Yan", LastName = "Li", UserName = $"yan.li@{emailDomain}", Email = $"yan.li@{emailDomain}", Enabled = true }, new AppUserEntity { FirstName = "Peggy", LastName = "Justice", UserName = $"peggy.justice@{emailDomain}", Email = $"peggy.justice@{emailDomain}" }, new AppUserEntity { FirstName = "Laura", LastName = "Norman", UserName = $"laura.norman@{emailDomain}", Email = $"laura.norman@{emailDomain}", EmailConfirmed = true, Enabled = true }, new AppUserEntity { FirstName = "Nino", LastName = "Olivetto", UserName = $"nino.olivetto@{emailDomain}", Email = $"nino.olivetto@{emailDomain}" } }; foreach (var user in sampleUsers) { Task.WaitAll(userManager.CreateAsync(user, password)); } Task.WaitAll(roleManager.CreateAsync(new RoleEntity("Admin", "Admin role"))); Task.WaitAll(roleManager.CreateAsync(new RoleEntity("Normal", "Normal role"))); logger.LogInformation($"Identity database was Seeded"); }
public void UpdateIdentity(AppUserEntity adminUser) { using (var connection = _dbConnectionFactory.CreateConnection()) { connection.Open(); using (var transaction = connection.BeginTransaction()) { var parameters = new DynamicParameters(); parameters.Add("@Id", adminUser.Id, DbType.Int32); parameters.Add("@IsBlocked", adminUser.IsBlocked, DbType.Boolean); parameters.Add("@MobilePhone", adminUser.MobilePhone, DbType.String); parameters.Add("@LockoutEnabled", adminUser.LockoutEnabled, DbType.Boolean); parameters.Add("@TwoFactorEnabled", adminUser.TwoFactorEnabled, DbType.Boolean); parameters.Add("@MobilePhoneConfirmed", adminUser.MobilePhoneConfirmed, DbType.Boolean); parameters.Add("@LockoutEndDateUtc", adminUser.LockoutEndDateUtc, DbType.DateTimeOffset); parameters.Add("@AccessFailedCount", adminUser.AccessFailedCount, DbType.Int32); parameters.Add("@EmailConfirmed", adminUser.EmailConfirmed, DbType.Boolean); parameters.Add("@PasswordHash", adminUser.PasswordHash, DbType.String); parameters.Add("@SecurityStamp", adminUser.SecurityStamp, DbType.String); parameters.Add("@UserName", adminUser.UserName, DbType.String); parameters.Add("@FullName", adminUser.FullName, DbType.String); parameters.Add("@Email", adminUser.Email, DbType.String); int result = connection.Execute( sql: "UsersWithIdentityUpdate", commandType: CommandType.StoredProcedure, transaction: transaction, param: parameters ); UserClaimsSet(connection, transaction, claims: adminUser.Claims, user: adminUser, cleanup: true); UserRealmsSet(connection, transaction, realms: adminUser.Realms, user: adminUser, cleanup: true); UserRolesSet(connection, transaction, roles: adminUser.Roles, user: adminUser, cleanup: true); transaction.Commit(); } } }
public async Task <Result <AddPhoneTwoFactorAuthenticationViewModel> > GetPhoneViewModel() { Result <AppUserEntity> getAppUserResult = await GetAppUser(); if (getAppUserResult.Failure) { return(Result.Fail <AddPhoneTwoFactorAuthenticationViewModel>(getAppUserResult.Errors)); } AppUserEntity appUser = getAppUserResult.Value; if (string.IsNullOrEmpty(appUser.PhoneNumber)) { _logger.LogError($"User does not have a phone number"); return(Result.Fail <AddPhoneTwoFactorAuthenticationViewModel>("no_phone_number", "No Phone number")); } AddPhoneTwoFactorAuthenticationViewModel addPhoneTwoFactorAuthenticationViewModel = new AddPhoneTwoFactorAuthenticationViewModel( phoneNumber: appUser.PhoneNumber); return(Result.Ok(addPhoneTwoFactorAuthenticationViewModel)); }
/// <summary> /// 更新实时通信用户列表 /// </summary> private void UpdateIMUserList(string keyValue, bool isAdd, AppUserEntity userEntity) { try { IMUserModel entity = new IMUserModel(); AppOrganizeBLL bll = new AppOrganizeBLL(); AppDepartmentBLL dbll = new AppDepartmentBLL(); entity.UserId = keyValue; if (userEntity != null) { entity.RealName = userEntity.UserName; entity.DepartmentId = "";// dbll.GetEntity(userEntity.DepartmentId).FullName; //entity.Gender = (int)userEntity.Gender; //entity.HeadIcon = userEntity.HeadIcon; //entity.OrganizeId = bll.GetEntity(userEntity.OrganizeId).FullName; ; } SendHubs.callMethod("upDateUserList", entity, isAdd); } catch { } }
public async Task <Result> Disable(string userId) { AppUserEntity appUser = await _userManager.FindByIdAsync(userId); if (appUser == null) { _logger.LogWarning($"No user. UserId {userId}"); return(Result.Fail("no_user", "No user")); } appUser.TwoFactor = TwoFactorAuthenticationType.None; IdentityResult disable2faResult = await _userManager.SetTwoFactorEnabledAsync(appUser, false); if (!disable2faResult.Succeeded) { _logger.LogWarning($"Failed to disable 2fa. UserId {userId}"); return(Result.Fail(disable2faResult.Errors)); } IdentityResult resetKeyResult = await _userManager.ResetAuthenticatorKeyAsync(appUser); if (!resetKeyResult.Succeeded) { _logger.LogWarning($"Failed to reset authentication key. UserId {userId}"); return(Result.Fail(resetKeyResult.Errors)); } _logger.LogInformation($"Authentication key reset. UserId {userId}"); Result loginResult = await _loginService.Login(userId); if (loginResult.Failure) { _logger.LogError($"Failed to login user after 2fa reset. UserId {userId}"); } return(Result.Ok()); }
public async Task <Result> CreatePassword(CreatePasswordRequest createPasswordRequest) { ValidationResult validationResult = _createPasswordValidator.Validate(createPasswordRequest); if (!validationResult.IsValid) { _logger.LogWarning($"Invalid {nameof(CreatePasswordRequest)} model"); return(Result.Fail(validationResult.Errors)); } string userId = _httpContextAccessor.HttpContext.User.GetUserId(); AppUserEntity appUser = await _userManager.FindByIdAsync(userId); if (appUser == null) { _logger.LogError($"No User. UserId {userId}"); return(Result.Fail("no_user", "No User")); } _logger.LogTrace($"Creating password. UserId {userId}"); IdentityResult identityResult = await _userManager.AddPasswordAsync(appUser, createPasswordRequest.NewPassword); if (!identityResult.Succeeded) { _logger.LogError($"Failed to add password. UserId {userId}"); return(Result.Fail(identityResult.Errors)); } Result loginResult = await _loginService.Login(userId); if (loginResult.Failure) { _logger.LogError($"Failed to log in user after password was added. UserId {userId}"); } return(Result.Ok()); }
private async Task <Result> Start(AppUserEntity appUser) { string impersonizerId = _identityUIUserInfoService.GetImpersonatorId(); if (!string.IsNullOrEmpty(impersonizerId)) { _logger.LogError($"User is already impersonating somebody"); return(Result.Fail(ALREADY_IMPERSONATING)); } string userId = _identityUIUserInfoService.GetUserId(); if (userId == appUser.Id) { _logger.LogError($"Can not impersonate self"); return(Result.Fail(CAN_NOT_IMPERSONATE_SELF)); } appUser.SessionCode = Guid.NewGuid().ToString(); Result addSessionResult = await _sessionService.Add(appUser.SessionCode, appUser.Id); if (addSessionResult.Failure) { return(Result.Fail(FAILED_TO_ADD_SESSION)); } string loggedInUserId = _identityUIUserInfoService.GetUserId(); appUser.ImpersonatorId = loggedInUserId; _logger.LogInformation($"User is starting to impersonate another user. ImpersnonazerId {loggedInUserId}, user to be impersonalized {appUser.Id}"); await _signInManager.SignOutAsync(); await _signInManager.SignInAsync(appUser, false); return(Result.Ok()); }
public async Task <Result> RecoverPassword(RecoverPasswordRequest request) { ValidationResult validationResult = _forgotPasswordValidator.Validate(request); if (!validationResult.IsValid) { _logger.LogWarning($"No user. User Email {request.Email}"); return(Result.Fail(validationResult.Errors)); } AppUserEntity appUser = await _userManager.FindByEmailAsync(request.Email); if (appUser == null) { _logger.LogWarning($"No user. User emil {request.Email}"); return(Result.Ok()); } bool emailConfirmed = await _userManager.IsEmailConfirmedAsync(appUser); if (!emailConfirmed || !appUser.Enabled || appUser.LockoutEnd != null) { _logger.LogWarning($"User email not confirmed. UserId {appUser.Id}"); return(Result.Ok()); } string code = await _userManager.GeneratePasswordResetTokenAsync(appUser); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); string calbackUrl = QueryHelpers.AddQueryString($"{_identityManagementOptions.BasePath}{_identityManagementEndpoints.ResetPassword}", "code", code); await _emailSender.SendEmailAsync(appUser.Email, "Reset Password", $"Please reset your password by <a href='{HtmlEncoder.Default.Encode(calbackUrl)}'>clicking here</a>"); _logger.LogInformation($"Password recovery email send. UserId {appUser.Id}"); return(Result.Ok()); }
public async Task <Result <(string sharedKey, string authenticatorUri)> > Generate2faCode(string userId, string sessionCode, string ip) { AppUserEntity appUser = await _userManager.FindByIdAsync(userId); if (appUser == null) { _logger.LogError($"No user. UserId {userId}"); return(Result.Fail <(string sharedKey, string authenticatorUri)>($"no_user", $"No User")); } string key = await _userManager.GetAuthenticatorKeyAsync(appUser); if (string.IsNullOrEmpty(key)) { IdentityResult identityResult = await _userManager.ResetAuthenticatorKeyAsync(appUser); if (!identityResult.Succeeded) { _logger.LogWarning($"Faild to reset authentication key. UserId {userId}"); return(Result.Fail <(string, string)>(identityResult.Errors)); } Result loginResult = await _loginService.Login(userId, sessionCode, ip); if (loginResult.Failure) { _logger.LogError($"Faild to login user after 2fa reset. UserId {userId}"); } key = await _userManager.GetAuthenticatorKeyAsync(appUser); } string sharedKey = FormatKey(key); string authenticatorUri = GenerateQrCodeUri(appUser.UserName, key); _logger.LogInformation($"2fa code generated. UserId {userId}"); return(Result.Ok((sharedKey: sharedKey, authenticatorUri: authenticatorUri))); }
public async Task Seed() { _context.Database.EnsureCreated(); AppUserEntity userOne = await _userManager.FindByEmailAsync(userOneUserName); if (userOne == null) { userOne = new AppUserEntity { Email = userOneUserName, UserName = userOneUserName }; var result = await _userManager.CreateAsync(userOne, password); if (result != IdentityResult.Success) { throw new InvalidOperationException($"Error seeding user {userOneUserName}."); } } AppUserEntity userTwo = await _userManager.FindByEmailAsync(userTwoUserName); if (userTwo == null) { userTwo = new AppUserEntity { Email = userTwoUserName, UserName = userTwoUserName }; var result = await _userManager.CreateAsync(userTwo, password); if (result != IdentityResult.Success) { throw new InvalidOperationException($"Error seeding user {userTwoUserName}."); } } }
public async Task <Result> GenerateSmsCode(string userId) { string timeoutKey = string.Format(SEND_SMS_KEY, userId); bool timeout = _memoryCache.TryGetValue(timeoutKey, out string temp); if (timeout) { return(Result.Fail("to_many_requests", "To many requests")); } _memoryCache.Set(timeoutKey, "temp", TimeSpan.FromSeconds(SEND_TIMEOUT_SECONDS)); AppUserEntity appUser = await _userManager.FindByIdAsync(userId); if (appUser == null) { _logger.LogError($"No user. UserId {userId}"); return(Result.Fail($"no_user", "No User")); } if (string.IsNullOrEmpty(appUser.PhoneNumber)) { _logger.LogError($"User does not have a phone number. UserId {userId}"); return(Result.Fail($"phone_number_not_found", "Phone number not found")); } string code = await _userManager.GenerateTwoFactorTokenAsync(appUser, TwoFactorAuthenticationType.Phone.ToProvider()); Result smsSendResult = await _smsSender.Send(appUser.PhoneNumber, $"Authentication code: {code}"); if (smsSendResult.Failure) { return(Result.Fail(smsSendResult.Errors)); } return(Result.Ok()); }
public async Task <Result> GenerateAndSendEmailCode(string userId) { string timeoutKey = string.Format(SEND_EMAIL_KEY, userId); bool timeout = _memoryCache.TryGetValue(timeoutKey, out string temp); if (timeout) { return(Result.Fail("to_many_requests", "To many requests")); } _memoryCache.Set(timeoutKey, "temp", TimeSpan.FromSeconds(SEND_TIMEOUT_SECONDS)); AppUserEntity appUser = await _userManager.FindByIdAsync(userId); if (appUser == null) { _logger.LogError($"No user. UserId {userId}"); return(Result.Fail <string>($"no_user", "No User")); } if (string.IsNullOrEmpty(appUser.Email)) { _logger.LogError($"User does not have an email address"); return(Result.Fail <string>("no_email", "No email")); } string code = await _userManager.GenerateTwoFactorTokenAsync(appUser, TwoFactorAuthenticationType.Email.ToProvider()); Result sendTokenResult = await _emailService.Send2faToken(appUser.Email, code); if (sendTokenResult.Failure) { return(Result.Fail(sendTokenResult.Errors)); } return(Result.Ok()); }
/// <summary> /// Used to login user after password change, 2fa change /// </summary> /// <param name="userId"></param> /// <param name="sessionCode"></param> /// <param name="ip"></param> /// <returns></returns> public async Task <Result> Login(string userId, string sessionCode, string ip) { await _signInManager.SignOutAsync(); AppUserEntity appUser = await _userManager.FindByIdAsync(userId); if (appUser == null) { _logger.LogInformation($"No user with username {userId}"); return(Result.Fail("error", "Error")); } if (sessionCode != null) { _sessionService.Logout(sessionCode, appUser.Id, SessionEndTypes.SecurityCodeChange); } if (!appUser.CanLogin()) { _logger.LogInformation($"User is not allowd to login. User {appUser.Id}"); return(Result.Fail("error", "Error")); } appUser.SessionCode = Guid.NewGuid().ToString(); Result addSessionResult = _sessionService.Add(appUser.SessionCode, appUser.Id, ip); if (addSessionResult.Failure) { return(Result.Fail("error", "error")); } await _signInManager.SignInAsync(appUser, false); _logger.LogInformation($"User loged in. UserId {appUser.Id}"); return(Result.Ok()); }
public async Task <Result> ChangePassword(string userId, string sessionCode, string ip, ChangePasswordRequest request) { ValidationResult validationResult = _changePasswordValidator.Validate(request); if (!validationResult.IsValid) { _logger.LogWarning($"Invalid ChangePasswordrequest. UserId {userId}"); return(Result.Fail(validationResult.Errors)); } AppUserEntity appUser = await _userManager.FindByIdAsync(userId); if (appUser == null) { _logger.LogError($"No user. UserId {userId}"); return(Result.Fail("no_user", "No user")); } IdentityResult identityResult = await _userManager.ChangePasswordAsync(appUser, request.OldPassword, request.NewPassword); if (!identityResult.Succeeded) { _logger.LogWarning($"Failed to change password. UserId {userId}"); return(Result.Fail(identityResult.Errors)); } _logger.LogInformation($"Changed password. UserId {userId}"); Result loginResult = await _loginService.Login(userId, sessionCode, ip); if (loginResult.Failure) { _logger.LogError($"Failed to log in user after password change. UserId {userId}"); } return(Result.Ok()); }
public static AppUserEntity Create(Guid UserId, int FkAspnetAppCustomersCustNo, int?CurrentUserProviderKey, int?SelectedFileGroup, Guid?SelectedFileGuid, string StatusCode, string EmailAddress , string FirstName, string LastName, bool?ReceiveStatusEmails, string ExportType, string LastUpdatedBy , DateTime?LastUpdateDate, string FileUploadMode) { AppUserEntity appUser = new AppUserEntity() { UserId = UserId, CurrentUserProviderKey = CurrentUserProviderKey, SelectedFileGroup = SelectedFileGroup, SelectedFileGuid = SelectedFileGuid, StatusCode = StatusCode, EmailAddress = EmailAddress, FirstName = FirstName, LastName = LastName, ReceiveStatusEmails = ReceiveStatusEmails, ExportType = ExportType, LastUpdatedBy = LastUpdatedBy, LastUpdateDate = LastUpdateDate, FileUploadMode = FileUploadMode }; return(appUser); }
/// <summary> /// Used only when admin is adding new user /// </summary> /// <param name="newUserRequest"></param> /// <param name="adminId"></param> /// <returns></returns> public async Task <Result <string> > AddUser(NewUserRequest newUserRequest, string adminId) { ValidationResult validationResult = _newUserValidator.Validate(newUserRequest); if (!validationResult.IsValid) { _logger.LogError($"Invalid NewUserRequest. Admin {adminId}"); return(Result.Fail <string>(ResultUtils.ToResultError(validationResult.Errors))); } AppUserEntity appUser = new AppUserEntity( userName: newUserRequest.UserName, email: newUserRequest.Email, firstName: newUserRequest.FirstName, lastName: newUserRequest.LastName, emailConfirmed: false, enabled: true); IdentityResult result = await _userManager.CreateAsync(appUser); if (!result.Succeeded) { _logger.LogError($"Admin with id {adminId} failed to add new user"); return(Result.Fail <string>(ResultUtils.ToResultError(result.Errors))); } appUser = await _userManager.FindByNameAsync(newUserRequest.UserName); if (appUser == null) { _logger.LogError($"Failed to find new user with UserName {newUserRequest.UserName}. Admin {adminId}"); return(Result.Fail <string>("no_user", "No user")); } return(Result.Ok(appUser.Id)); }