public async Task <AuthResponse> Handle(OTPLoginCommand request, CancellationToken cancellationToken) { var response = new AuthResponse { Status = new APIResponseStatus { IsSuccessful = true, Message = new APIResponseMessage() } }; try { var lockoutSetting = new List <ScrewIdentifierGrid>(); var cachedSetting = await _cacheService.GetCacheResponseAsync(CacheKeys.AuthSettings); if (!string.IsNullOrEmpty(cachedSetting)) { lockoutSetting = JsonConvert.DeserializeObject <List <ScrewIdentifierGrid> >(cachedSetting); } else { lockoutSetting = await _dataContext.ScrewIdentifierGrid.ToListAsync(); } await _cacheService.CatcheResponseAsync(CacheKeys.AuthSettings, lockoutSetting, TimeSpan.FromSeconds(3600)); var user = await _userManager.FindByEmailAsync(request.Email); await _measure.RemoveOtpAsync(request.OTP); var result = await _service.LoginAsync(user); var measure = Measures.CollectAsMuchAsPossible(user, result, request); await _measure.GetMeasuresAsync(measure); var session = _dataContext.SessionChecker.Find(user.Id); if (session != null) { session.LastRefreshed = DateTime.UtcNow.Add(lockoutSetting.FirstOrDefault(v => v.Module == (int)Modules.CENTRAL).InActiveSessionTimeout); session.Userid = user.Id; session.Module = (int)Modules.CENTRAL; _dataContext.Entry(session).CurrentValues.SetValues(session); await _dataContext.SaveChangesAsync(); } response.Token = result.Token; response.RefreshToken = result.RefreshToken; return(response); } catch (Exception ex) { response.Status.Message.FriendlyMessage = ex?.Message ?? ex?.InnerException?.Message; response.Status.Message.TechnicalMessage = ex.ToString(); return(response); } }
public async Task <AuthSettupGridResponder> Handle(ExposeOtherServiceAuthGrid request, CancellationToken cancellationToken) { var response = new AuthSettupGridResponder { Status = new APIResponseStatus { IsSuccessful = true, Message = new APIResponseMessage() } }; var lockoutSetting = new List <ScrewIdentifierGrid>(); var cachedSetting = await _cacheService.GetCacheResponseAsync(CacheKeys.AuthSettings); if (!string.IsNullOrEmpty(cachedSetting)) { lockoutSetting = JsonConvert.DeserializeObject <List <ScrewIdentifierGrid> >(cachedSetting); } else { lockoutSetting = await _context.ScrewIdentifierGrid.ToListAsync(); } response.AuthSettups = lockoutSetting.Select(q => new AuthSettup { ActiveOnMobileApp = q.ActiveOnMobileApp, ActiveOnWebApp = q.ActiveOnWebApp, AuthSettupId = q.ScrewIdentifierGridId, Module = q.Module, Media = q.Media, ShouldAthenticate = q.ShouldAthenticate, ModuleName = Convert.ToString((Modules)q.Module), NotifierName = Convert.ToString((Media)q.Media), UseActiveDirectory = q.UseActiveDirectory, SecuritySettingsActiveOnWebApp = q.SecuritySettingsActiveOnWebApp, SecuritySettingActiveOnMobileApp = q.SecuritySettingActiveOnMobileApp, PasswordUpdateCycle = q.PasswordUpdateCycle, NumberOfFailedLoginBeforeLockout = q.NumberOfFailedLoginBeforeLockout, ActiveDirectory = q.ActiveDirectory, EnableLoginFailedLockout = q.EnableLoginFailedLockout, InActiveSessionTimeout = (q.InActiveSessionTimeout).Minutes, ShouldRetryAfterLockoutEnabled = q.ShouldRetryAfterLockoutEnabled, RetryTimeInMinutes = (q.RetryTimeInMinutes).Minutes, EnableRetryOnWebApp = q.EnableRetryOnWebApp, EnableRetryOnMobileApp = q.EnableRetryOnMobileApp, EnableLoadBalance = q.EnableLoadBalance, LoadBalanceInHours = q.LoadBalanceInHours }).ToList() ?? new List <AuthSettup>(); response.Status.Message.FriendlyMessage = lockoutSetting.Count() > 0 ? string.Empty : "Search Record Complete"; return(response); }
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { var response = new MiddlewareResponse { Status = new APIResponseStatus { IsSuccessful = false, Message = new APIResponseMessage() } }; using (var scope = context.HttpContext.RequestServices.CreateScope()) { try { IServiceProvider scopedServices = scope.ServiceProvider; RedisCacheSettings redisSettings = scopedServices.GetRequiredService <RedisCacheSettings>(); if (!redisSettings.Enabled) { await next(); return; } DataContext _dataContext = scopedServices.GetRequiredService <DataContext>(); IResponseCacheService responseCacheService = scopedServices.GetRequiredService <IResponseCacheService>(); var cacheKey = Cache.GenerateCacheKeyFromRequest(context.HttpContext.Request); if (context.HttpContext.Request.Method != "GET") { await responseCacheService.ResetCacheAsync(cacheKey); } var cachedResponse = await responseCacheService.GetCacheResponseAsync(cacheKey); if (!string.IsNullOrEmpty(cachedResponse)) { var contentResult = new ContentResult { Content = cachedResponse, ContentType = "application/json", StatusCode = 200 }; context.Result = contentResult; return; } var executedContext = await next(); if (executedContext.Result is OkObjectResult okObjectResult) { await responseCacheService.CatcheResponseAsync(cacheKey, okObjectResult, TimeSpan.FromSeconds(1000)); context.HttpContext.Response.StatusCode = 200; context.Result = new OkObjectResult(okObjectResult); return; } await next(); } catch (Exception ex) { context.HttpContext.Response.StatusCode = 500; response.Status.IsSuccessful = false; response.Status.Message.FriendlyMessage = ex.Message; response.Status.Message.TechnicalMessage = ex.ToString(); context.Result = new InternalServerErrorObjectResult(response); return; } } }
public async Task <LogingFailedRespObj> CheckForFailedTrailsAsync(bool isSuccessful, int module, string userid) { var usergent = string.Empty; if (string.IsNullOrEmpty(userid)) { usergent = _detectionService.UserAgent.ToLower().Trim(); } else { usergent = userid; } var response = new LogingFailedRespObj { IsSecurityQuestion = false, Status = new APIResponseStatus { IsSuccessful = true, Message = new APIResponseMessage() } }; var lockoutSetting = new List <ScrewIdentifierGrid>(); var cachedSetting = await _cacheService.GetCacheResponseAsync(CacheKeys.AuthSettings); if (!string.IsNullOrEmpty(cachedSetting)) { lockoutSetting = JsonConvert.DeserializeObject <List <ScrewIdentifierGrid> >(cachedSetting); } else { lockoutSetting = await _security.ScrewIdentifierGrid.ToListAsync(); } if (lockoutSetting.Count() > 0) { await _cacheService.CatcheResponseAsync(CacheKeys.AuthSettings, lockoutSetting, TimeSpan.FromSeconds(3600)); } if (_detectionService.Device.Type.ToString() == Device.Desktop.ToString() && lockoutSetting.Any(e => e.EnableLoginFailedLockout && e.EnableRetryOnWebApp && e.Module == module)) { var setup = lockoutSetting.FirstOrDefault(e => e.EnableLoginFailedLockout && e.EnableRetryOnWebApp && e.Module == module); var loginFailed = _security.LogingFailedChecker.FirstOrDefault(r => r.Userid == usergent); if (isSuccessful) { if (loginFailed != null) { _security.LogingFailedChecker.Remove(loginFailed); await _security.SaveChangesAsync(); return(response); } } if (!isSuccessful) { if (loginFailed == null) { loginFailed = new LogingFailedChecker(); loginFailed.Counter = 1; loginFailed.QuestionTimeCount = 1; loginFailed.RetryTime = DateTime.UtcNow.Add(setup.RetryTimeInMinutes); loginFailed.Userid = usergent; _security.LogingFailedChecker.Add(loginFailed); await _security.SaveChangesAsync(); return(response); } else { if (loginFailed.QuestionTimeCount >= setup.NumberOfFailedAttemptsBeforeSecurityQuestions && !setup.ShouldRetryAfterLockoutEnabled && setup.Module != (int)Modules.CENTRAL) { response.Status.Message.FriendlyMessage = "Please proceed to answer security question"; response.IsSecurityQuestion = true; response.Status.IsSuccessful = false; return(response); } loginFailed.Counter = loginFailed.Counter + 1; loginFailed.QuestionTimeCount = loginFailed.QuestionTimeCount + 1; _security.Entry(loginFailed).CurrentValues.SetValues(loginFailed); await _security.SaveChangesAsync(); if (loginFailed.Counter >= setup.NumberOfFailedLoginBeforeLockout) { var timeRemain = (loginFailed.RetryTime - DateTime.UtcNow).Minutes + 1; if (DateTime.UtcNow < loginFailed.RetryTime) { string TimeVariable = string.Empty; TimeVariable = $"{timeRemain} minutes"; if (timeRemain == 1) { TimeVariable = $"{(loginFailed.RetryTime - DateTime.UtcNow).Seconds} seconds"; } response.Status.IsSuccessful = false; response.UnLockAt = loginFailed.RetryTime; response.Status.Message.FriendlyMessage = $"Please retry after {TimeVariable}"; return(response); } else { loginFailed.Counter = 0; loginFailed.QuestionTimeCount = loginFailed.QuestionTimeCount + 1; _security.Entry(loginFailed).CurrentValues.SetValues(loginFailed); await _security.SaveChangesAsync(); return(response); } } loginFailed.RetryTime = DateTime.UtcNow.Add(setup.RetryTimeInMinutes); loginFailed.Userid = usergent; loginFailed.QuestionTimeCount = loginFailed.QuestionTimeCount + 1; _security.Entry(loginFailed).CurrentValues.SetValues(loginFailed); await _security.SaveChangesAsync(); return(response); } } } if (_detectionService.Device.Type.ToString() == Device.Mobile.ToString() && lockoutSetting.Any(e => e.EnableLoginFailedLockout && e.EnableRetryOnMobileApp && e.Module == module)) { var setup = lockoutSetting.FirstOrDefault(e => e.EnableLoginFailedLockout && e.EnableRetryOnMobileApp && e.Module == module); if (setup != null) { var failedCached = _security.LogingFailedChecker.FirstOrDefault(r => r.Userid == usergent); if (isSuccessful) { if (failedCached != null) { _security.LogingFailedChecker.Remove(failedCached); await _security.SaveChangesAsync(); return(response); } } if (!isSuccessful) { var loginFailed = _security.LogingFailedChecker.Find(usergent); if (loginFailed == null) { loginFailed = new LogingFailedChecker(); loginFailed.Counter = 1; loginFailed.QuestionTimeCount = 1; loginFailed.RetryTime = DateTime.UtcNow.Add(setup.RetryTimeInMinutes); loginFailed.Userid = usergent; _security.LogingFailedChecker.Add(loginFailed); await _security.SaveChangesAsync(); return(response); } else { if (loginFailed.QuestionTimeCount >= setup.NumberOfFailedAttemptsBeforeSecurityQuestions && !setup.ShouldRetryAfterLockoutEnabled && setup.Module != (int)Modules.CENTRAL) { response.Status.Message.FriendlyMessage = "Please proceed to answer security question"; response.IsSecurityQuestion = true; response.Status.IsSuccessful = false; return(response); } loginFailed.Counter = loginFailed.Counter + 1; loginFailed.QuestionTimeCount = loginFailed.QuestionTimeCount + 1; _security.Entry(loginFailed).CurrentValues.SetValues(loginFailed); await _security.SaveChangesAsync(); if (loginFailed.Counter >= setup.NumberOfFailedLoginBeforeLockout) { var timeRemain = (loginFailed.RetryTime - DateTime.UtcNow).Minutes + 1; if (DateTime.UtcNow < loginFailed.RetryTime) { string TimeVariable = string.Empty; TimeVariable = $"{timeRemain} minutes"; if (timeRemain == 1) { TimeVariable = $"{(loginFailed.RetryTime - DateTime.UtcNow).Seconds} seconds"; } response.Status.IsSuccessful = false; response.UnLockAt = loginFailed.RetryTime; response.Status.Message.FriendlyMessage = $"Please retry after {TimeVariable}"; return(response); } else { loginFailed.Counter = 0; loginFailed.QuestionTimeCount = loginFailed.QuestionTimeCount + 1; _security.Entry(loginFailed).CurrentValues.SetValues(loginFailed); await _security.SaveChangesAsync(); return(response); } } loginFailed.RetryTime = DateTime.UtcNow.Add(setup.RetryTimeInMinutes); loginFailed.Userid = usergent; loginFailed.QuestionTimeCount = loginFailed.QuestionTimeCount + 1; _security.Entry(loginFailed).CurrentValues.SetValues(loginFailed); await _security.SaveChangesAsync(); return(response); } } } } return(response); }
public async Task <AuthResponse> Handle(LoginCommand request, CancellationToken cancellationToken) { var response = new AuthResponse { Status = new APIResponseStatus { IsSuccessful = true, Message = new APIResponseMessage() } }; try { if (!await _measure.ReturnStatusAsync(request.UserName)) { response.Status.IsSuccessful = false; return(response); } var lockoutSetting = new List <ScrewIdentifierGrid>(); var cachedSetting = await _cacheService.GetCacheResponseAsync(CacheKeys.AuthSettings); if (!string.IsNullOrEmpty(cachedSetting)) { lockoutSetting = JsonConvert.DeserializeObject <List <ScrewIdentifierGrid> >(cachedSetting); } else { lockoutSetting = await _securityContext.ScrewIdentifierGrid.ToListAsync(); } await _cacheService.CatcheResponseAsync(CacheKeys.AuthSettings, lockoutSetting, TimeSpan.FromSeconds(86400)); if (!await IsPasswordCharactersValid(request.Password)) { response.Status.IsSuccessful = false; response.Status.Message.FriendlyMessage = "Invalid Password"; return(response); } if (!await UserExist(request)) { response.Status.IsSuccessful = false; response.Status.Message.FriendlyMessage = "User does not exist"; return(response); } if (!await IsValidPassword(request)) { response.Status.IsSuccessful = false; response.Status.Message.FriendlyMessage = "User/Password Combination is wrong"; return(response); } var user = await _userManager.FindByNameAsync(request.UserName); var otp = await OTPOptionsAsync(user.Id); if (otp.Status.IsSuccessful) { otp.Status.Message.MessageId = user.Email; return(otp); } var result = await _service.LoginAsync(user); var measure = Measures.CollectAsMuchAsPossible(user, result, _detectionService); var res = await _measure.GetMeasuresAsync(measure); await ReplaceDeviceAsync(user.Id, measure.Token); var session = _securityContext.SessionChecker.Find(user.Id); if (session != null) { session.LastRefreshed = DateTime.UtcNow.Add(lockoutSetting.FirstOrDefault(v => v.Module == (int)Modules.CENTRAL).InActiveSessionTimeout); session.Userid = user.Id; session.Module = (int)Modules.CENTRAL; _securityContext.Entry(session).CurrentValues.SetValues(session); await _securityContext.SaveChangesAsync(); } response.Token = result.Token; response.RefreshToken = result.RefreshToken; return(response); } catch (Exception ex) { response.Status.Message.FriendlyMessage = ex?.Message ?? ex?.InnerException?.Message; response.Status.Message.TechnicalMessage = ex.ToString(); return(response); } }