public async Task <IHttpActionResult> AddUserToRole([FromBody] AddUserToRoleBindingModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var role = await _roleManager.FindByNameAsync(model.RoleName); if (role == null) { return(NotFound()); } var user = await _userManager.FindByNameAsync(model.Username); if (user == null) { return(NotFound()); } var result = await _userManager.AddToRoleAsync(user.Id, role.Name); if (!result.Succeeded) { return(GetErrorResult(result)); } return(Ok()); }
public OldHouseUser GetTestFackUser(string nickName, string userName, string password) { var user = MyUserManager.FindByNameAsync(userName).Result; if (user != null) { return(user); } user = new OldHouseUser { NickName = nickName, UserName = userName, PasswordHash = password }; //todo put all oldhouse user roles in consts //todo use a fake user iu data base later user.Roles.Add("User"); //it has no profile yet //todo may return a fake profile in data base var profile = CreateAFakeProfile(); user.Profiles.Add(OldHouseUserProfile.PROFILENBAME, profile.Id); MyUserManager.CreateAsync(user).Wait(); ProfileService.SaveOne(profile); return(user); }
public async Task <TokenAuthorizeModel> RegisterExternalAsync(MyUserManager userManager, RegisterExternalViewModel viewModel) { var identity = viewModel.ToEntity(); var authenticationType = Enum.Parse <ExternalAuthenticationType>(viewModel.Provider, true); _externalAuthenticationFactory.Create(authenticationType).GetUserDetails(identity, viewModel.ProviderIdToken); identity.UserName = identity.Email; //If user exist in the system var user = await userManager.FindByNameAsync(identity.UserName); if (user != null) { return(await user.AuthorizeAsync(userManager, _extensionSettings.appSettings)); } //if user is not exist in the system IdentityResult result = await userManager.CreateAsync(identity); if (result.Succeeded) { await updateOtherInfoForIdentity(userManager, identity); return(await identity.AuthorizeAsync(userManager, _extensionSettings.appSettings)); } throw new FoodCourtException(ErrorMessage.USER_CREATE_FAIL); }
public async Task <string> Login([FromBody] LoginRequest request) { var user = await _userManager.FindByNameAsync(request.UserName); var loginResult = await _userManager.CheckPasswordAsync(user, request.Password); return(loginResult ? "登录成功" : "用户名或密码错误"); }
public async Task <ActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (ModelState.IsValid) { var user = await UserManager.FindByNameAsync(model.Email); if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id))) { // Don't reveal that the user does not exist or is not confirmed return(View("ForgotPasswordConfirmation")); } // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id); // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>"); // return RedirectToAction("ForgotPasswordConfirmation", "Account"); } // If we got this far, something failed, redisplay form return(View(model)); }
public async Task <TokenAuthorizeModel> AuthorizeAsync(MyUserManager userManager, LoginViewModel viewModel) { MyIdentity identity = viewModel.ToEntity(); var user = await userManager.FindByNameAsync(identity.UserName); if (user == null) { throw new FoodCourtException(ErrorMessage.USER_IS_NOT_EXIST); } bool result = await userManager.CheckPasswordAsync(user, viewModel.Password); if (result) { return(await user.AuthorizeAsync(userManager, _extensionSettings.appSettings)); } throw new FoodCourtException(ErrorMessage.PASSWORD_NOT_VALID); }
public async Task <ActionResult> ResetPassword(ResetPasswordInputModel model) { //model.OldPassword = ""; #if DEBUG Debug.WriteLine("UserName="******"Password="******"ConfirmPassword="******"OldPassword="******"Id=" + model.Id.ToString()); #endif if (ModelState.IsValid) { #if DEBUG Debug.WriteLine("Model is valid"); #endif var user = await _userManager.FindByNameAsync(model.UserName); if (user != null) { #if DEBUG Debug.WriteLine("user is not null"); #endif /* * var checkOldPassword =await _userManager.CheckPasswordAsync(user, model.OldPassword); * * if (checkOldPassword) * { */ var result = await _userManager.RemovePasswordAsync(user.UserID); if (result.Succeeded) { #if DEBUG Debug.WriteLine("Password is removed to succeeded"); #endif var result2 = await _userManager.AddPasswordAsync(user.UserID, model.Password); if (result2.Succeeded) { #if DEBUG Debug.WriteLine("Password is added to succeeded"); #endif var result3 = await _userManager.SetSigninEndDateAsync(user); #if DEBUG if (result3) { Debug.WriteLine("SetSigninEndDateAsync is well done"); } #endif var result4 = await _userManager.ResetAccessFailedCountAsync(user.UserID); #if DEBUG if (result4.Succeeded) { Debug.WriteLine("ResetAccessFailedCountAsync is executed."); } #endif /* * result4 = await _userManager.SetChangePasswordEndDateAsync(user); #if DEBUG * if (result4.Succeeded) * { * Debug.WriteLine("SetChangePasswordEndDateAsync is executed."); * } #endif * * result4 = await _userManager.SetPasswordEnabledAsync(user, false); #if DEBUG * if (result4.Succeeded) * { * Debug.WriteLine("SetPasswordEnabledAsync is executed."); * } #endif */ return(RedirectToAction("List")); } } // } /* else * { * // Активизирована ли функция блокировки учётки в системе * if (_userManager.LockoutEnabled) * { * #if DEBUG * Debug.WriteLine("++++ GetLockoutEnabledAsync is enabled"); #endif * // Увелечение счётчика неудачных попыток ввода пароля * if (await _userManager.AccessFailedAsync(user.UserID) == IdentityResult.Success) * { #if DEBUG * Debug.WriteLine("~~~ AccessFailedAsync is working!"); #endif * if (await _userManager.IsLockedOutAsync(user.UserID)) * { #if DEBUG * Debug.WriteLine("Account is locked out!"); #endif * //Заблокировать учётку * return View("Lockout"); * } * * * } * * * } * * } */ } } #if DEBUG Debug.WriteLine("Error is occured in ResetPassword"); #endif return(View(model)); }
/// <summary> /// Comprueba el inicio de sesión de un usuario y devuelve un estado que indica si ha sido exitoso o no. De no serlo, la respuesta indica la razón. /// </summary> /// <param name="username">Nombre de usuario.</param> /// <param name="password">Contraseña.</param> /// <param name="skipEmailConfirmed">¿Debe validarse que el email haya sido confirmado?</param> /// <returns></returns> public async Task <LogInResult> CheckCredentialsAsync(string username, string password, bool skipEmailConfirmed = false) { LogInResult result = new LogInResult(LoginStatusTypes.UnknownError); try { var user = await uM.FindByNameAsync(username); result = new LogInResult(LoginStatusTypes.UnknownError, user); if (user == null) { //No existe result.Status = LoginStatusTypes.DoesNotExist; return(result); } if (user.LockoutEnabled) { bool haltAndReturn = true; //Usuario bloqueado if (user.LockoutEnd.HasValue) { //El bloqueo es temporal. if (user.LockoutEnd.Value <= DateTimeOffset.Now) { //El bloqueo ha expirado: desbloquear & continuar. await uM.SetLockoutEnabledAsync(user, false); haltAndReturn = false; } else { ///El bloqueo sigue activo. result.Status = LoginStatusTypes.UserLocked_Temporal; } } else { //El bloqueo es permanente result.Status = LoginStatusTypes.UserLocked_Permanent; } if (haltAndReturn) { return(result); } } if (!skipEmailConfirmed) { if (!user.EmailConfirmed) { result.Status = LoginStatusTypes.EmailNotConfirmed; } return(result); } bool isPasswordValid = await uM.CheckPasswordAsync(user, password); if (!isPasswordValid) { result.Status = LoginStatusTypes.PasswordNotValid; return(result); } else { result.Status = LoginStatusTypes.Success; } } catch (Exception) { } return(result); }