//Sign in button private void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) { // Ensure the user name and password fields aren't empty. If a required field // is empty, set args.Cancel = true to keep the dialog open. if (string.IsNullOrEmpty(userNameTextBox.Text)) { args.Cancel = true; errorTextBlock.Text = "User name is required."; } else if (string.IsNullOrEmpty(passwordTextBox.Password)) { args.Cancel = true; errorTextBlock.Text = "Password is required."; } // If you're performing async operations in the button click handler, // get a deferral before you await the operation. Then, complete the // deferral when the async operation is complete. ContentDialogButtonClickDeferral deferral = args.GetDeferral(); //if (await SomeAsyncSignInOperation()) //{ this.Result = SignInResult.SignInOK; //} //else //{ // this.Result = SignInResult.SignInFail; //} deferral.Complete(); }
void SignInContentDialog_Opened(ContentDialog sender, ContentDialogOpenedEventArgs args) { this.Result = SignInResult.Nothing; // If the user name is saved, get it and populate the user name field. Windows.Storage.ApplicationDataContainer roamingSettings = Windows.Storage.ApplicationData.Current.RoamingSettings; if (roamingSettings.Values.ContainsKey("userName")) { userNameTextBox.Text = roamingSettings.Values["userName"].ToString(); saveUserNameCheckBox.IsChecked = true; } }
/// <summary> /// Called on any login attempt to update the AccessFailedCount and to raise events /// </summary> /// <param name="user"></param> /// <param name="username"></param> /// <param name="result"></param> /// <returns></returns> protected virtual async Task <SignInResult> HandleSignIn(TUser user, string username, SignInResult result) { // TODO: Here I believe we can do all (or most) of the usermanager event raising so that it is not in the AuthenticationController if (username.IsNullOrWhiteSpace()) { username = "******"; // could happen in 2fa or something else weird } if (result.Succeeded) { //track the last login date user.LastLoginDateUtc = DateTime.UtcNow; if (user.AccessFailedCount > 0) { //we have successfully logged in, reset the AccessFailedCount user.AccessFailedCount = 0; } await UserManager.UpdateAsync(user); Logger.LogInformation("User: {UserName} logged in from IP address {IpAddress}", username, Context.Connection.RemoteIpAddress); } else if (result.IsLockedOut) { Logger.LogInformation("Login attempt failed for username {UserName} from IP address {IpAddress}, the user is locked", username, Context.Connection.RemoteIpAddress); } else if (result.RequiresTwoFactor) { Logger.LogInformation("Login attempt requires verification for username {UserName} from IP address {IpAddress}", username, Context.Connection.RemoteIpAddress); } else if (!result.Succeeded || result.IsNotAllowed) { Logger.LogInformation("Login attempt failed for username {UserName} from IP address {IpAddress}", username, Context.Connection.RemoteIpAddress); } else { throw new ArgumentOutOfRangeException(); } return(result); }
//Cancel button private void ContentDialog_SecondaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) { // User clicked Cancel. this.Result = SignInResult.SignInCancel; }
public ContentDialogExample() { this.InitializeComponent(); this.Result = SignInResult.Nothing; }
public async Task <SignInResult> Login(string ip, string sessionCode, LoginRequest login) { ValidationResult validationResult = _loginValidator.Validate(login); if (!validationResult.IsValid) { _logger.LogError($"Invalid LoginRequest. UserName {login?.UserName}"); return(SignInResult.Failed); } await _signInManager.SignOutAsync(); AppUserEntity appUser = await _userManager.FindByNameAsync(login.UserName); if (appUser == null) { _logger.LogInformation($"No user with username {login.UserName}"); return(SignInResult.Failed); } if (sessionCode != null) { _sessionService.Logout(sessionCode, appUser.Id, SessionEndTypes.Expired); } if (!appUser.CanLogin()) { _logger.LogInformation($"User is not allowed to login. User {appUser.Id}"); return(SignInResult.Failed); } appUser.SessionCode = Guid.NewGuid().ToString(); Result addSessionResult = _sessionService.Add(appUser.SessionCode, appUser.Id, ip); if (addSessionResult.Failure) { return(SignInResult.Failed); } SignInResult result = await _signInManager.PasswordSignInAsync(appUser, login.Password, login.RememberMe, lockoutOnFailure : true); if (!result.Succeeded) { if (result.RequiresTwoFactor) { _logger.LogInformation($"Login Requires TwoFactor. User {appUser.Id}"); _sessionService.Logout(appUser.SessionCode, appUser.Id, SessionEndTypes.TwoFactorLogin); } if (!result.IsLockedOut) { _logger.LogInformation($"Failed to log in user. User {appUser.Id}"); _sessionService.Logout(appUser.SessionCode, appUser.Id, SessionEndTypes.InvalidLogin); } return(result); } _logger.LogInformation($"User id loged in. UserId {appUser.Id}"); return(result); }
public static Packet SignInResultPacket(SignInResult result) { return(new Packet(Type.SignInResult, result)); }
/// <summary> /// Returns a flag indication whether the user attempting to sign-in requires email confirmation . /// </summary> public static bool RequiresPasswordChange(this SignInResult result) => (result as ExtendedSigninResult)?.RequiresPasswordChange == true;
private void LogReasoning(SignInResult signInResult, LoginData data) { string message = GetMessage(signInResult, data); _logger.LogDebug(message); }
public async Task <SignInResult> SignInAsync(LoginUserViewModel model) { SignInResult result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, false); return(result); }
public ExtendedSignInResultViewModel(SignInResult result, IList <string> roles = null) { Result = result; Roles = roles; }
public static LoginResultModel MapFromSignInResult(this LoginResultModel loginResultModel, SignInResult signInResult) { //TODO:Move to resources const string _locked = "Your account has been locked out!"; if (loginResultModel == null) { loginResultModel.ErrorMessage = _invalid; return(loginResultModel); } loginResultModel.IsLockedOut = signInResult.IsLockedOut; loginResultModel.IsNotAllowed = signInResult.IsNotAllowed; loginResultModel.RequiresTwoFactor = signInResult.RequiresTwoFactor; loginResultModel.Succeeded = signInResult.Succeeded; if (loginResultModel.IsLockedOut) { loginResultModel.ErrorMessage = _locked; return(loginResultModel); } if (loginResultModel.IsNotAllowed || loginResultModel.RequiresTwoFactor) { return(loginResultModel); } if (!loginResultModel.Succeeded) { loginResultModel.ErrorMessage = _invalid; } return(loginResultModel); }
public async Task <bool> AuthenticateAsync(string email, string password, CancellationToken cancellationToken = default) { SignInResult result = await _signInManager.PasswordSignInAsync(email, password, false, false); return(result.Succeeded); }
/// <summary> /// Returns a flag indication whether the user attempting to sign-in requires phone number confirmation. /// </summary> /// <param name="result"></param> /// <returns></returns> public static bool RequiresPhoneNumberConfirmation(this SignInResult result) => (result as ExtendedSigninResult)?.RequiresPhoneNumberValidation == true;
public async Task <SignInResult> LoginAsync(string userName, string password, bool rememberMe, bool lockoutOnFailure) { SignInResult result = await signInManager.PasswordSignInAsync(userName, password, rememberMe, lockoutOnFailure : false); return(result); }
/// <summary> /// Returns a flag indication whether the user attempting to sign-in requires email confirmation . /// </summary> public static bool RequiresEmailConfirmation(this SignInResult result) => (result as ExtendedSigninResult)?.RequiresEmailValidation == true;
public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context) { string clientId = context.Request?.Client?.ClientId; AppUser user = await _userManager.FindByNameAsync(context.UserName); var loginInformationValidationResult = _informationValidator.ValidateLoginInfo(context); if (!loginInformationValidationResult.IsSuccess) { LoggerExtensions.LogInformation(_logger, "Login information is not formated correctly: {username}", new object[1] { context.UserName }); await _events.RaiseAsync(new UserLoginFailureEvent(context.UserName, "invalid username", interactive : false)); context.Result = new GrantValidationResult(TokenRequestErrors.InvalidRequest, "LoginInformation should be formated like this lan=99.99&lat=99.99&Imei=xxxx"); return; } if (user is null) { LoggerExtensions.LogInformation(_logger, "No user found matching username: {username}", new object[1] { context.UserName }); await _events.RaiseAsync(new UserLoginFailureEvent(context.UserName, "invalid credentials", interactive : false, clientId)); return; } if (clientId == "AdminBff") { var isAdmin = await _userManager.IsInRoleAsync(user, "Admin"); if (!isAdmin) { LoggerExtensions.LogInformation(_logger, "No user found matching username: {username}", new object[1] { context.UserName }); await _events.RaiseAsync(new UserLoginFailureEvent(context.UserName, "invalid credentials", interactive : false, clientId)); return; } } SignInResult val = await _signInManager.CheckPasswordSignInAsync(user, context.Password, lockoutOnFailure : true); if (val.Succeeded) { string sub = await _userManager.GetUserIdAsync(user); LoggerExtensions.LogInformation(_logger, "Credentials validated for username: {username}", new object[1] { context.UserName }); await _events.RaiseAsync(new UserLoginSuccessEvent(context.UserName, sub, context.UserName, interactive : false, clientId)); var login = _loginManager.UserLoggedIn(loginInformationValidationResult.LoginInformation, user.Id); var additionalAttrs = new Dictionary <string, object> { { "tokenId", login.Id.ToString() } }; context.Result = new GrantValidationResult(sub, "pwd", authTime: login.LoggedAt, customResponse: additionalAttrs); return; } if (val.IsLockedOut) { LoggerExtensions.LogInformation(_logger, "Authentication failed for username: {username}, reason: locked out", new object[1] { context.UserName }); await _events.RaiseAsync(new UserLoginFailureEvent(context.UserName, "locked out", interactive : false, clientId)); context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant); return; } else if (val.IsNotAllowed) { LoggerExtensions.LogInformation(_logger, "Authentication failed for username: {username}, reason: not allowed", new object[1] { context.UserName }); await _events.RaiseAsync(new UserLoginFailureEvent(context.UserName, "not allowed", interactive : false, clientId)); context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant); return; } else { LoggerExtensions.LogInformation(_logger, "Authentication failed for username: {username}, reason: invalid credentials", new object[1] { context.UserName }); await _events.RaiseAsync(new UserLoginFailureEvent(context.UserName, "invalid credentials", interactive : false, clientId)); context.Result = new GrantValidationResult(TokenRequestErrors.InvalidGrant); return; } }
protected virtual void WriteLog(string account, string password, string ip, SignInResult signInResult) { }
internal static bool Failed(this SignInResult result) => result == SignInResult.Failed;
public async Task <ApiResponse> Handle(LoginCommand request, CancellationToken cancellationToken) { ApiResponse response = new ApiResponse(); try { // model validate if (request.UserName == null || request.Password == null) { throw new Exception(StaticResource.InvalidUserCredentials); } // validate user SignInResult result = await _signInManager.PasswordSignInAsync(request.UserName, request.Password, isPersistent : false, lockoutOnFailure : false); if (!result.Succeeded) { throw new Exception(StaticResource.InvalidUserCredentials); } var user = await _userManager.FindByNameAsync(request.UserName.Trim()); //var result1 = await _signInManager.CheckPasswordSignInAsync(user, request.Password, false); if (user == null) { throw new Exception(StaticResource.InvalidUserCredentials); } List <UserRolePermissionsModel> userRolePermissionsList = new List <UserRolePermissionsModel>(); List <RolePermissionModel> RolePermissionModelList = new List <RolePermissionModel>(); List <ApproveRejectPermissionModel> ApproveRejectRolePermissionModelList = new List <ApproveRejectPermissionModel>(); List <AgreeDisagreePermissionModel> AgreeDisagreeRolePermissionModelList = new List <AgreeDisagreePermissionModel>(); List <OrderSchedulePermissionModel> OrderSchedulePermissionModelList = new List <OrderSchedulePermissionModel>(); #region "Get CLAIMS & ROLES" var userClaims = await _userManager.GetClaimsAsync(user); var roles = await _userManager.GetRolesAsync(user); userClaims.Add(new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString())); // subject used for ClaimTypes.NameIdentifier userClaims.Add(new Claim(JwtRegisteredClaimNames.Email, user.Email)); userClaims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())); #endregion #region "Generate token" string k = _configuration["JwtKey"]; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(k)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var expires = DateTime.Now.AddDays(Convert.ToDouble(_configuration["JwtExpireDays"])); var token = new JwtSecurityTokenHandler() .WriteToken(new JwtSecurityToken( issuer: _configuration.GetSection("JwtIssuerOptions:Issuer").Value, audience: _configuration.GetSection("JwtIssuerOptions:Audience").Value, claims: userClaims, expires: DateTime.Now.AddYears(1), signingCredentials: creds )); #endregion #region "Approve / reject permissions" foreach (var role in roles) { UserRolePermissionsModel userRolePermissions = new UserRolePermissionsModel(); //userClaims.Add(new Claim("Roles", role)); //imp var roleid = await _roleManager.Roles.FirstOrDefaultAsync(x => x.Name == role); List <RolePermissions> rolePermissionsList = _dbContext.RolePermissions.Where(x => x.IsDeleted == false && x.RoleId == roleid.Id).ToList(); List <ApproveRejectPermission> approveRejectRolePermissionsList = _dbContext.ApproveRejectPermission.Where(x => x.IsDeleted == false && x.RoleId == roleid.Id).ToList(); List <AgreeDisagreePermission> agreeDisagreeRolePermissionsList = _dbContext.AgreeDisagreePermission.Where(x => x.IsDeleted == false && x.RoleId == roleid.Id).ToList(); List <OrderSchedulePermission> orderScheduleRolePermissionsList = _dbContext.OrderSchedulePermission.Where(x => x.IsDeleted == false && x.RoleId == roleid.Id).ToList(); if (rolePermissionsList.Any()) { foreach (RolePermissions rolePermissions in rolePermissionsList) { if (RolePermissionModelList.Any()) { RolePermissionModel rolePermissionModel = RolePermissionModelList.FirstOrDefault(x => x.PageId == rolePermissions.PageId); if (rolePermissionModel == null) { RolePermissionModel rolePermission = new RolePermissionModel(); rolePermission.CanEdit = rolePermissions.CanEdit; rolePermission.CanView = rolePermissions.CanView; rolePermission.ModuleId = rolePermissions.ModuleId; rolePermission.PageId = rolePermissions.PageId; rolePermission.RolesPermissionId = rolePermissions.RolesPermissionId; RolePermissionModelList.Add(rolePermission); } else { if (rolePermissionModel.CanView && !rolePermissionModel.CanEdit && rolePermissions.CanEdit) { rolePermissionModel.CanEdit = rolePermissions.CanEdit; } else if (!rolePermissionModel.CanView && !rolePermissionModel.CanEdit && rolePermissions.CanEdit) { rolePermissionModel.CanView = true; rolePermissionModel.CanEdit = true; } } } else { RolePermissionModel rolePermissionModel = new RolePermissionModel(); rolePermissionModel.CanEdit = rolePermissions.CanEdit; rolePermissionModel.CanView = rolePermissions.CanView; rolePermissionModel.ModuleId = rolePermissions.ModuleId; rolePermissionModel.PageId = rolePermissions.PageId; rolePermissionModel.RolesPermissionId = rolePermissions.RolesPermissionId; RolePermissionModelList.Add(rolePermissionModel); } } } if (approveRejectRolePermissionsList.Any()) { foreach (ApproveRejectPermission rolePermissions in approveRejectRolePermissionsList) { if (ApproveRejectRolePermissionModelList.Any()) { ApproveRejectPermissionModel rolePermissionModel = ApproveRejectRolePermissionModelList.FirstOrDefault(x => x.PageId == rolePermissions.PageId); if (rolePermissionModel == null) { ApproveRejectPermissionModel rolePermission = new ApproveRejectPermissionModel(); rolePermission.Approve = rolePermissions.Approve; rolePermission.Id = rolePermissions.Id; rolePermission.PageId = rolePermissions.PageId; rolePermission.PageId = rolePermissions.PageId; rolePermission.Reject = rolePermissions.Reject; rolePermission.RoleId = rolePermissions.RoleId; ApproveRejectRolePermissionModelList.Add(rolePermission); } else { if (rolePermissionModel.Approve && !rolePermissionModel.Reject && rolePermissions.Reject) { rolePermissionModel.Reject = rolePermissions.Reject; } else if (!rolePermissionModel.Approve && !rolePermissionModel.Reject && rolePermissions.Reject) { rolePermissionModel.Approve = true; rolePermissionModel.Reject = true; } } } else { ApproveRejectPermissionModel rolePermissionModel = new ApproveRejectPermissionModel(); rolePermissionModel.Approve = rolePermissions.Approve; rolePermissionModel.Reject = rolePermissions.Reject; rolePermissionModel.PageId = rolePermissions.PageId; rolePermissionModel.Id = rolePermissions.Id; rolePermissionModel.RoleId = rolePermissions.RoleId; ApproveRejectRolePermissionModelList.Add(rolePermissionModel); } } } if (agreeDisagreeRolePermissionsList.Any()) { foreach (AgreeDisagreePermission rolePermissions in agreeDisagreeRolePermissionsList) { if (AgreeDisagreeRolePermissionModelList.Any()) { AgreeDisagreePermissionModel rolePermissionModel = AgreeDisagreeRolePermissionModelList.FirstOrDefault(x => x.PageId == rolePermissions.PageId); if (rolePermissionModel == null) { AgreeDisagreePermissionModel rolePermission = new AgreeDisagreePermissionModel(); rolePermission.Agree = rolePermissions.Agree; rolePermission.Id = rolePermissions.Id; rolePermission.PageId = rolePermissions.PageId; rolePermission.PageId = rolePermissions.PageId; rolePermission.Disagree = rolePermissions.Disagree; rolePermission.RoleId = rolePermissions.RoleId; AgreeDisagreeRolePermissionModelList.Add(rolePermission); } else { if (rolePermissionModel.Agree && !rolePermissionModel.Disagree && rolePermissions.Disagree) { rolePermissionModel.Disagree = rolePermissions.Disagree; } else if (!rolePermissionModel.Agree && !rolePermissionModel.Disagree && rolePermissions.Disagree) { rolePermissionModel.Agree = true; rolePermissionModel.Disagree = true; } } } else { AgreeDisagreePermissionModel rolePermissionModel = new AgreeDisagreePermissionModel(); rolePermissionModel.Agree = rolePermissions.Agree; rolePermissionModel.Disagree = rolePermissions.Disagree; rolePermissionModel.PageId = rolePermissions.PageId; rolePermissionModel.Id = rolePermissions.Id; rolePermissionModel.RoleId = rolePermissions.RoleId; AgreeDisagreeRolePermissionModelList.Add(rolePermissionModel); } } } if (orderScheduleRolePermissionsList.Any()) { foreach (OrderSchedulePermission rolePermissions in orderScheduleRolePermissionsList) { if (OrderSchedulePermissionModelList.Any()) { OrderSchedulePermissionModel rolePermissionModel = OrderSchedulePermissionModelList.FirstOrDefault(x => x.PageId == rolePermissions.PageId); if (rolePermissionModel == null) { OrderSchedulePermissionModel rolePermission = new OrderSchedulePermissionModel(); rolePermission.OrderSchedule = rolePermissions.OrderSchedule; rolePermission.Id = rolePermissions.Id; rolePermission.PageId = rolePermissions.PageId; rolePermission.PageId = rolePermissions.PageId; rolePermission.RoleId = rolePermissions.RoleId; OrderSchedulePermissionModelList.Add(rolePermission); } else { if (rolePermissionModel.OrderSchedule) { rolePermissionModel.OrderSchedule = rolePermissions.OrderSchedule; } else if (!rolePermissionModel.OrderSchedule) { rolePermissionModel.OrderSchedule = true; } } } else { OrderSchedulePermissionModel rolePermissionModel = new OrderSchedulePermissionModel(); rolePermissionModel.OrderSchedule = rolePermissions.OrderSchedule; rolePermissionModel.PageId = rolePermissions.PageId; rolePermissionModel.Id = rolePermissions.Id; rolePermissionModel.RoleId = rolePermissions.RoleId; OrderSchedulePermissionModelList.Add(rolePermissionModel); } } } userRolePermissionsList.Add(userRolePermissions); } #endregion #region "Set responses" var User = _dbContext.UserDetails.AsNoTracking().FirstOrDefault(x => x.IsDeleted == false && x.AspNetUserId == user.Id); var Offices = _dbContext.UserDetailOffices.Where(x => x.IsDeleted == false && x.UserId == User.UserID).Select(x => x.OfficeId).ToList(); response.data.AspNetUserId = user.Id; response.data.Token = token; response.data.Roles = roles.ToList(); response.data.RolePermissionModelList = RolePermissionModelList; response.data.ApproveRejectPermissionsInRole = ApproveRejectRolePermissionModelList; response.data.AgreeDisagreePermissionsInRole = AgreeDisagreeRolePermissionModelList; response.data.OrderSchedulePermissionsInRole = OrderSchedulePermissionModelList; response.data.UserOfficeList = Offices.Count > 0 ? Offices : null; response.StatusCode = 200; response.Message = StaticResource.SuccessText; #endregion } catch (Exception ex) { response.StatusCode = StaticResource.failStatusCode; response.Message = ex.Message; } return(response); }
internal static bool Successful(this SignInResult result) => result == SignInResult.Success;
/// <summary> /// Метод авторизует пользователя. /// </summary> /// <param name="user">Объект данных юзера.</param> /// <returns>Статус true/false</returns> public async Task <object> LoginAsync(UserInput user) { try { SignInResult auth = null; bool isContinue = false; // Проверит, логин передан или email. bool isEmail = CustomValidatorExtension.CheckIsEmail(user.UserName); // Если нужно проверять по логину. if (!isEmail) { // Авторизует юзера. auth = await _signInManager.PasswordSignInAsync(user.UserName, user.UserPassword, user.RememberMe, false); } // Значит в UserName лежит email. else { // Найдет пользователя по почте. UserEntity findUser = await _userManager.FindByEmailAsync(user.UserName); if (findUser != null && findUser.UserPassword.Equals(user.UserPassword)) { isContinue = true; // Перезапишет UserName на логин выбранный из БД для фронта. user.UserName = findUser.UserName; } } // Если авторизация успешна. if ((auth != null && auth.Succeeded) || isContinue) { ClaimsIdentity claim = GetIdentityClaim(user); // Выбирает роли юзера. IEnumerable <string> aRoles = await GetUserRole(user.UserName); // Генерит токен юзеру. string sToken = GenerateToken(claim).Result; return(new { user = user.UserName, userToken = sToken, role = aRoles }); } throw new ArgumentException(); } catch (ArgumentNullException ex) { Logger _logger = new Logger(_db, ex.GetType().FullName, ex.Message.ToString(), ex.StackTrace); await _logger.LogError(); throw new ArgumentNullException("Такого пользователя не существует", ex.Message.ToString()); } catch (ArgumentException ex) { Logger _logger = new Logger(_db, ex.GetType().FullName, ex.Message.ToString(), ex.StackTrace); await _logger.LogError(); throw new ArgumentException("Логин и (или) пароль введены не верно", ex.Message.ToString()); } catch (Exception ex) { Logger _logger = new Logger(_db, ex.GetType().FullName, ex.Message.ToString(), ex.StackTrace); await _logger.LogCritical(); throw new Exception(ex.Message.ToString()); } }
private void ContentDialog_CloseButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args) { // User clicked Cancel, ESC, or the system back button. this.Result = SignInResult.SignInCancel; }
public XboxLiveUser( SignInResult xblResult ) { xboxLiveResult = xblResult; hasFailedLogin = (xblResult.SignInStatus == SignInStatus.UserCancel); }
public async Task <bool> ExternalLogin(ExternalLoginInfo info) { SignInResult result = await this.signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : false).ConfigureAwait(true); return(result.Succeeded); }
public SignInView() { this.InitializeComponent(); this.Result = SignInResult.Nothing; }