private static void EndJob(string taskName, UserActivityRepository <UserActivity> activityRepository) { var userActivity = CreateAuditRecord( string.Format("{0} completed {1:r}", taskName, DateTime.Now), BatchUser); activityRepository.Add(userActivity); }
private static void StartJob(string taskName, string how, UserActivityRepository <UserActivity> activityRepository) { var userActivity = CreateAuditRecord( string.Format("{0} invoked {1:r} {2}", taskName, DateTime.Now, how), how); activityRepository.Add(userActivity); }
public static bool DoJob(string taskName, string how) { var activityRepository = new UserActivityRepository <UserActivity>(); var patService = new PatService(); var control = patService.GetControlFile(); StartJob(taskName, how, activityRepository); // Get rid of any unused samples SampleCleanup(patService); // Refresh the Compliance indicators for PAM UpdateComplianceIndicators(patService, how, control); // Get outcomes from Staton's spreadsheet BatchUpdateReviewOutcomes(patService, how, control); HealthCheck(patService, control.LastBatchRun, how); EndJob(taskName, activityRepository); control.LastBatchRun = DateTime.Now; control.UpdatedBy = BatchUser; patService.UpdateControl(control); return(true); }
public async Task <IHttpActionResult> Logout() { string currentUserId = User.Identity.GetUserId(); await UserManager.UpdateSecurityStampAsync(currentUserId); //audit var _userActivityRepository = new UserActivityRepository(); var userActivity = new UserActivity() { ActionId = UserActionIds.Logout, ActionType = ActionTypes.NonAdmin, UserName = UserManager.FindById(currentUserId).Email }; try { await _userActivityRepository.AddAsync(userActivity); } catch { //TODO - send email here } return(Ok()); }
static ComplianceIndicators() { ciRepository = new ComplianceIndicatorRepository(); projectRepository = new ProjectRepository(); projectContractRepository = new ProjectContractRepository(); reviewRepository = new ReviewRepository(); uploadRepository = new UploadRepository(); activityRepository = new UserActivityRepository <UserActivity>(); }
/// <summary> /// Default constructor for injecting dependent services /// </summary> /// <param name="employerService"> /// The Employer service this controller should use /// </param> /// <param name="organizationService"> /// The organization service this controller should use /// </param> /// <summary> /// Default constructor for injecting dependent services /// </summary> /// <param name="identityService"> public AccountController(IEmployerService employerService, IOrganizationService organizationService, IIdentityService identityService) { _employerService = employerService; _organizationService = organizationService; _identityService = identityService; _userActivityRepository = new UserActivityRepository(); }
public void TestUserActivityStringOverflow() { var _activityRepository = new UserActivityRepository <UserActivity>(); var userActivity = new UserActivity { UserId = "1234567890-the rest is superflus", Activity = "123456789012345678901234567890123456789012345678901234567890-superfluous", CreatedBy = "UnitTest" }; _activityRepository.Add(userActivity); Assert.IsTrue(true); }
public void AuditActivity(string activity, string userId) { if (string.IsNullOrEmpty(activity)) { return; } var userActivity = new UserActivity { Activity = activity, UserId = userId ?? "not passed" }; var activityRepository = new UserActivityRepository <UserActivity>(); activityRepository.Add(userActivity); }
protected override async Task ExecuteAsync(CancellationToken cancellationToken) { using (var scope = scopeFactory.CreateScope()) { try { var dbContext = scope.ServiceProvider.GetRequiredService <ApplicationDbContext>(); string connString = dbContext.Database.GetDbConnection().ConnectionString; var userRepo = new UserActivityRepository(connString); var errorRepo = new ErrorRepository(connString); var errorLogger = new ErrorLoggerService(errorRepo); var userActivityLogger = new UserActivityLogService( userRepo, errorLogger); while (!cancellationToken.IsCancellationRequested) { if (await this._errorLogItems.QueueIsEmpty(cancellationToken) && await this._userActivityLogItems.QueueIsEmpty(cancellationToken)) { await Task.Delay(TimeSpan.FromSeconds(10), cancellationToken); } else { if (await this._userActivityLogItems.QueueIsEmpty(cancellationToken) == false) { var item = await this._userActivityLogItems.DequeueAsync(cancellationToken); await userActivityLogger.LogThisActivity((UserActivityLogItem)item); } if (await this._errorLogItems.QueueIsEmpty(cancellationToken) == false) { var item = await this._errorLogItems.DequeueAsync(cancellationToken); errorLogger.LogError((ErrorLogItem)item); } } } } catch (Exception e) { StopAsync(cancellationToken); } } }
public UnitOfWork(DataContext context) { _context = context; Account = new AccountRepository(_context); AccountHistory = new AccountHistoryRepository(_context); AccountType = new AccountTypeRepository(_context); Business = new BusinessRepository(_context); Client = new ClientRepository(_context); Group = new GroupRepository(_context); Relationship = new RelationshipRepository(_context); Role = new RoleRepository(_context); Transaction = new TransactionRepository(_context); TransactionType = new TransactionTypeRepository(_context); User = new UserRepository(_context); UserHistory = new UserHistoryRepository(_context); UserActivity = new UserActivityRepository(_context); Menu = new MenuRepository(_context); }
/// <summary> /// /// </summary> /// <param name="context"></param> /// <returns></returns> public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { LogEventInfo eventInfo = new LogEventInfo(); try { var userManager = context.OwinContext.GetUserManager <ApplicationUserManager>(); var roleManager = context.OwinContext.Get <ApplicationRoleManager>(); eventInfo.Properties["CorrelationId"] = Guid.NewGuid().ToString(); eventInfo.LoggerName = "LoginAttempts"; eventInfo.Properties["IsServiceSideLog"] = 1; // Ensure User Email is not case sensitive var userName = context.UserName.TrimAndToLowerCase(); // Handle LINQ to Entities TrimAndToLowerCase() method cannot be translated into a store expression byr using ToLower() and Trim() directly var user = await userManager.Users.Include("Roles.Role").Include("Organizations").FirstOrDefaultAsync(x => x.UserName.ToLower().Trim() == userName && x.Deleted != true && x.Disabled != true); if (user != null) { eventInfo.Properties["UserId"] = user.Id; eventInfo.Properties["UserName"] = user.UserName; var passwordExpired = false; var passwordExpirationDays = AppSettings.Get <int>("PasswordExpirationDays"); if (passwordExpirationDays > 0) { passwordExpired = user.LastPasswordChangedDate.AddDays(passwordExpirationDays) < DateTime.Now; } var validCredentials = await userManager.FindAsync(context.UserName, context.Password); if (await userManager.IsLockedOutAsync(user.Id)) { // account locked // use invalid user name or password message to avoid disclosing that a valid username was input var message = string.Format(App_GlobalResources.LocalizedText.LoginFailureMessageAccountLockedOut, AppSettings.Get <int>("DefaultAccountLockoutTimeSpan")); context.SetError("locked_out", message); // Get locked out email template var accountLockedOutEmailTemplatePath = System.Web.Hosting.HostingEnvironment.MapPath(@"~/App_Data/AccountLockedOutEmailTemplate.txt"); var accountLockedOutEmailTemplateString = File.ReadAllText(accountLockedOutEmailTemplatePath); //Send Account Lock Out Email await userManager.SendEmailAsync(user.Id, AppSettings.Get <string>("AccountLockedoutEmailSubject"), accountLockedOutEmailTemplateString); throw new UnauthorizedAccessException(string.Format("{0}: {1}", App_GlobalResources.LocalizedText.LoginFailureMessage, message)); } if (!user.EmailConfirmed) { // email not confirmed // use invalid user name or password message to avoid disclosing that a valid username was input context.SetError("invalid_grant", App_GlobalResources.LocalizedText.LoginFailureMessageEmailNotConfirmed); var message = string.Format("{0}: {1}", App_GlobalResources.LocalizedText.LoginFailureMessage, App_GlobalResources.LocalizedText.LoginFailureMessageEmailNotConfirmed); eventInfo.Message = message; throw new UnauthorizedAccessException(message); } if (validCredentials == null) { // invalid credentials // increment failed login count int loginAttempted = 0; if (await userManager.GetLockoutEnabledAsync(user.Id)) { loginAttempted = await userManager.GetAccessFailedCountAsync(user.Id); await userManager.AccessFailedAsync(user.Id); } context.SetError("invalid_grant", App_GlobalResources.LocalizedText.InvalidUserNameorPassword); throw new UnauthorizedAccessException(string.Format("{0}: {1} Login Attempted: {2}", App_GlobalResources.LocalizedText.LoginFailureMessage, App_GlobalResources.LocalizedText.InvalidUserNameorPassword, loginAttempted + 1)); } if (passwordExpired) { // password expired context.SetError("invalid_grant", App_GlobalResources.LocalizedText.LoginFailureMessagePasswordExpired); var message = string.Format("{0}: {1}", App_GlobalResources.LocalizedText.LoginFailureMessage, App_GlobalResources.LocalizedText.LoginFailureMessagePasswordExpired); eventInfo.Message = message; throw new UnauthorizedAccessException(message); } var data = await context.Request.ReadFormAsync(); var code = data.Get("code"); // Send authentication code if code is empty if (await userManager.GetTwoFactorEnabledAsync(user.Id) && string.IsNullOrEmpty(code)) { await userManager.UpdateSecurityStampAsync(user.Id); var token = await userManager.GenerateTwoFactorTokenAsync(user.Id, "EmailCode"); await userManager.NotifyTwoFactorTokenAsync(user.Id, "EmailCode", token); context.SetError("need_code", App_GlobalResources.LocalizedText.MissingUser2FACode); var message = string.Format("{0}: {1}", "Send 2FA Code", App_GlobalResources.LocalizedText.MissingUser2FACode); eventInfo.Level = LogLevel.Info; eventInfo.Message = message; return; } // Verify authentication code if (await userManager.GetTwoFactorEnabledAsync(user.Id) && !await userManager.VerifyTwoFactorTokenAsync(user.Id, "EmailCode", code)) { context.SetError("invalid_code", App_GlobalResources.LocalizedText.LoginFailureEmailCodeIncorrect); var message = string.Format("{0}: {1}", App_GlobalResources.LocalizedText.LoginFailureMessage, App_GlobalResources.LocalizedText.LoginFailureEmailCodeIncorrect); eventInfo.Message = message; throw new UnauthorizedAccessException(App_GlobalResources.LocalizedText.LoginFailureEmailCodeIncorrect); } else { // successful login ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, roleManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, roleManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = CreateProperties(user.Email); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); context.Validated(ticket); context.Request.Context.Authentication.SignIn(cookiesIdentity); // reset failed attempts count await userManager.ResetAccessFailedCountAsync(user.Id); // logging of successful attempts eventInfo.Level = LogLevel.Info; eventInfo.Message = App_GlobalResources.LocalizedText.LoginSuccessMessage; //audit var _userActivityRepository = new UserActivityRepository(); var userActivity = new UserActivity() { ActionId = UserActionIds.Login, ActionType = ActionTypes.NonAdmin, UserName = user.Email }; try { await _userActivityRepository.AddAsync(userActivity); } catch { //TODO - send email here } } } else { // invalid username context.SetError("invalid_grant", App_GlobalResources.LocalizedText.InvalidUserNameorPassword); throw new UnauthorizedAccessException(App_GlobalResources.LocalizedText.InvalidUserNameorPassword); } } catch (Exception ex) { // logging of unsuccessful attempts eventInfo.Message = ex.Message; eventInfo.Exception = ex; eventInfo.Level = LogLevel.Error; } finally { // Write log to database _logger.Log(eventInfo); } }
public UserActivityManager() { session1 = new Session1Entities(); userActivityRepository = new UserActivityRepository(); }