/// <summary> /// Sends a password reminder to the specified user /// </summary> /// <param name="email">Email address of user requesting password</param> /// <exception cref="InvalidUserException">Thrown if email address is empty, or no user with email address exists</exception> public static void ResetPasswordAndSend(string email) { if (StringUtils.IsBlank(email)) { throw new InvalidUserException("Email address is required", User.Empty); } User user = User.GetByEmail(email); if (user.IsNull) { throw new InvalidUserException("Your account could not be found", user); } user.SetPassword(PasswordGenerator.GeneratePassword()); user.PasswordExpiryDate = DateTime.Now.AddMinutes(-1); User.Update(user); if (PasswordResetRequested != null) { PasswordResetRequested(null, new UserEventArgs(user)); } AuditLogManager.LogUserAction(user, AuditUserAction.PasswordReminder, "Requested a password reminder"); }
private static void SaveHomepage(User user, Homepage homepage, IList <BinaryFile> imageList, bool publish) { ErrorList errors = ValidateHomepage(homepage, imageList); if (errors.Count > 0) { throw new InvalidHomepageException(errors, homepage); } homepage.IsPublished = publish; Homepage.Update(homepage); if (homepage.CategoriesLoaded) { HomepageCategory.DeleteHomepageCategories(homepage.HomepageId.GetValueOrDefault()); foreach (HomepageCategory hc in homepage.HomepageCategoryList) { hc.HomepageId = homepage.HomepageId.GetValueOrDefault(); HomepageCategory.Update(hc); } } SaveHomepageImages(homepage, imageList); if (publish) { AuditLogManager.LogUserAction(user, AuditUserAction.PublishHomepage, string.Format("Published Homepage: {0}", homepage.HomepageId)); } else { AuditLogManager.LogUserAction(user, AuditUserAction.PreviewHomepage, string.Format("Preview Homepage created: {0}", homepage.HomepageId)); } }
/// <summary> /// Changes an employee from PendingAdminApproval to PendingEmailConfirmation. /// Sends them an email with their updated status too. /// </summary> /// <param name="user">The processed user</param> /// <param name="adminUser">The admin user performing the action</param> /// <param name="approved">True if user is approved, false if rejected</param> /// <param name="notes">Admin notes attached to this approval or denial</param> /// <exception cref="SystemException"></exception> public static void ProcessNonEmployee(User user, User adminUser, bool approved, string notes) { // Ensure unapproved users have notes if (!approved && notes.Length == 0) { throw new SystemException("Please specify the reason why the user is rejected in the notes"); } // Update the user user.UserStatus = (approved) ? UserStatus.PendingEmailConfirmation : UserStatus.Rejected; user.Notes = notes; // Rejected users should be flagged as deleted if (!approved) { user.IsDeleted = true; } SaveUser(user); // Fire notifications if (NonEmployeeProcessed != null) { NonEmployeeProcessed(null, new UserEventArgs(user)); } // Update audit log string auditNotes = string.Format("Account processed by {0} and {1}", adminUser.FullName, ((approved) ? "approved" : "rejected")); AuditLogManager.LogUserAction(user, AuditUserAction.AuthoriseUser, auditNotes); }
/// <summary> /// Creates a new Category /// </summary> /// <param name="parentCategoryId">The id of the parent category, 0 belongs to root</param> /// <param name="brandId">The brand ID</param> /// <param name="name">New name</param> /// <param name="externalRef">External Reference</param> /// <param name="message">Message to display when selected</param> /// <param name="synonyms">Synonyms for the search functionality</param> /// <param name="user">The user creating the category</param> public static int CreateCategory(int?parentCategoryId, int brandId, string name, string externalRef, string message, string synonyms, User user) { Category category = Category.New(); category.ParentCategoryId = parentCategoryId; category.BrandId = brandId; category.Name = name; category.ExternalRef = externalRef; category.Message = message; category.Synonyms = ProcessSynonyms(synonyms); category.OwnerUserId = user.UserId.GetValueOrDefault(); ErrorList errors = Validate(category); if (errors.Count > 0) { throw new CategoryException(errors); } int subCategoriesCount = Category.Get(parentCategoryId.GetValueOrDefault()).SubCategories.Count; category.CategoryOrder = subCategoriesCount + 1; Category.Update(category); CacheManager.InvalidateCache("Category", CacheType.All); AuditLogManager.LogUserAction(user, AuditUserAction.AddCategory, string.Format("Created category {0}, ID: {1}", category.Name, category.CategoryId)); return(category.CategoryId.GetValueOrDefault()); }
/// <summary> /// Reorders the actual tree /// </summary> /// <param name="categoryId"> The category to change the order</param> /// <param name="parentId"> The parent category</param> /// <param name="order"> The new order</param> /// <param name="user">The user reordering the categories</param> public static void Reorder(int categoryId, int parentId, int order, User user) { Category category = Category.Get(categoryId); Category parentCategory = Category.Get(parentId); List <Category> subCategories = parentCategory.SubCategories; // Reorder top level categories foreach (Category subCategory in subCategories) { if ((subCategory.CategoryOrder >= order) && (subCategory.CategoryId != categoryId)) { subCategory.CategoryOrder += 1; Category.Update(subCategory); } } // Update category order category.ParentCategoryId = parentId; category.CategoryOrder = order; Category.Update(category); CacheManager.InvalidateCache("Category", CacheType.All); AuditLogManager.LogUserAction(user, AuditUserAction.ModifyCategory, string.Format("Reordered category {0}, ID: {1}", category.Name, category.CategoryId)); }
public void RemoveAssetFromLightbox(int lightboxId, int assetId, string additionalNotes) { Lightbox lb = GetLightboxById(lightboxId); if (EntitySecurityManager.CanManageLightbox(User, lb)) { if (LightboxContainsAsset(lb, assetId)) { foreach (LightboxAsset lba in lb.GetLightboxAssetList()) { if (lba.AssetId == assetId) { LightboxAsset.Delete(lba.LightboxAssetId); AuditLogManager.LogAssetAction(assetId, User, AuditAssetAction.RemovedFromLightbox); string notes = string.Format("Removed AssetId: {0} from LightboxId: {1}", assetId, lightboxId); if (!StringUtils.IsBlank(additionalNotes)) { notes += string.Format(". {0}", additionalNotes); } AuditLogManager.LogUserAction(User, AuditUserAction.RemoveFromLightbox, notes); } } } } else { m_Logger.DebugFormat("User: {0} (UserId: {1}) tried to remove AssetId: {2} from LightboxId: {3} but couldn't due to insufficient permissions to manage ths lightbox", User.FullName, User.UserId, assetId, lightboxId); } }
/// <summary> /// Adds a copy of the lightbox asset to the lightbox, if it does not contain the asset /// </summary> public void AddAssetToLightbox(Lightbox lightbox, LightboxAsset lightboxAsset) { if (!lightbox.IsNull && !lightboxAsset.IsNull) { if (EntitySecurityManager.CanManageLightbox(User, lightbox)) { if (!LightboxContainsAsset(lightbox, lightboxAsset.AssetId)) { LightboxAsset lba = LightboxAsset.New(); lba.LightboxId = lightbox.LightboxId.GetValueOrDefault(); lba.AssetId = lightboxAsset.AssetId; lba.Notes = lightboxAsset.Notes; lba.CreateDate = DateTime.Now; LightboxAsset.Update(lba); AuditLogManager.LogAssetAction(lightboxAsset.AssetId, User, AuditAssetAction.AddedToLightbox); AuditLogManager.LogUserAction(User, AuditUserAction.AddToLightbox, string.Format("Added AssetId: {0} to LightboxId: {1}", lightboxAsset.AssetId, lightbox.LightboxId.GetValueOrDefault())); } } else { m_Logger.DebugFormat("User: {0} (UserId: {1}) tried to add AssetId: {2} to LightboxId: {3} but couldn't due to insufficient permissions to manage ths lightbox", User.FullName, User.UserId, lightboxAsset.AssetId, lightbox.LightboxId.GetValueOrDefault()); } } }
/// <summary> /// Delete asset and update audit log /// </summary> /// <param name="user">The user deleting the asset</param> /// <param name="assetId">The ID of the asset to be deleted</param> public static void DeleteAsset(User user, int assetId) { m_Logger.DebugFormat("DeleteAsset: {0}", assetId); Asset asset = Asset.Get(assetId); if (asset.IsNull) { return; } asset.IsDeleted = true; Asset.Update(asset); m_Logger.Debug(" -Flagged asset as deleted"); // Update the audit log AuditLogManager.LogAssetAction(asset, user, AuditAssetAction.DeleteAsset); AuditLogManager.LogUserAction(user, AuditUserAction.DeleteAsset, string.Format("Deleted Asset with AssetId: {0}", asset.AssetId)); m_Logger.Debug(" -Updated audit log"); // Delete asset files DeleteAssetFiles(asset, asset.AssetFilePath.Path); // Delete asset bitmaps folder AssetBitmapGroupManager.DeleteAssetBitmapsFolder(asset); // Delete all asset categories AssetCategory.DeleteAllByAssetId(assetId); }
public static void ReplaceAssetFile(Asset asset, BinaryFile file, bool notify, User uploadUser) { m_Logger.DebugFormat("ReplaceAssetFile() - AssetId: {0}", asset.AssetId); // Will save the asset file, increment version, etc AssetFileManager.SaveAssetFile(asset, file, notify); if (asset.AssetPublishStatus == AssetPublishStatus.PendingApproval) { // The asset is still in a workflow, which we need to cancel and re-submit // Get the most recent workflow and perform relevant actions on it if (asset.AssetWorkflowList.Count > 0) { // Get the most recent workflow AssetWorkflow assetWorkflow = asset.AssetWorkflowList[0]; // Cancel it WorkflowManager.CancelWorkflow(assetWorkflow); m_Logger.DebugFormat("Cancelled AssetWorkflow - AssetWorkflowId: {0}", assetWorkflow.AssetWorkflowId); // Resubmit it WorkflowManager.SubmitAssetToWorkflow(asset, uploadUser); m_Logger.DebugFormat("Resubmitted asset to workflow. AssetId: {0}", asset.AssetId); } } AuditLogManager.LogAssetAction(asset, uploadUser, AuditAssetAction.ReplacedAssetFile); AuditLogManager.LogUserAction(uploadUser, AuditUserAction.ReplacedAssetFile, string.Format("Replaced asset file of AssetId: {0}", asset.AssetId)); }
/// <summary> /// Updates a Category /// </summary> /// <param name="categoryId"> The id of the category to be updated</param> /// <param name="categoryName"> New name</param> /// <param name="user">User making the change</param> public static void RenameCategory(int categoryId, string categoryName, User user) { Category category = Category.Get(categoryId); string oldname = category.Name; category.Name = categoryName; UpdateCategory(category); AuditLogManager.LogUserAction(user, AuditUserAction.ModifyCategory, string.Format("Renamed {0} to {1}, ID: {2}", oldname, categoryName, category.CategoryId)); }
public static void ReactivateUser(User user) { user.AccountExpiryDate = DateTime.Now.AddDays(AccountExpiryDays); User.Update(user); string notes = string.Format("Account reactivated, expiry date updated to: {0}", user.AccountExpiryDate.GetValueOrDefault().ToString("dd MMMM yyyy HH:mm")); AuditLogManager.LogUserAction(user, AuditUserAction.ReactivateAccount, notes); }
public void RemoveCartItemFromCart(Cart cart) { Cart.Delete(cart.CartId); AuditLogManager.LogAssetAction(cart.AssetId, User, AuditAssetAction.RemovedFromCart); AuditLogManager.LogUserAction(User, AuditUserAction.RemoveFromCart, string.Format("Removed AssetId: {0} from cart", cart.AssetId)); m_CartItems = null; }
/// <summary> /// Updates a Category /// </summary> /// <param name="categoryId"> The id of the category to be updated</param> /// <param name="categoryName">New name</param> /// <param name="externalRef">External Reference</param> /// <param name="message">Message to display when selected</param> /// <param name="synonyms">Synonyms for the search functionality</param> /// <param name="user">The user updating the category</param> public static void UpdateCategory(int categoryId, string categoryName, string externalRef, string message, string synonyms, User user) { Category category = Category.Get(categoryId); category.Name = categoryName; category.ExternalRef = externalRef; category.Message = message; category.Synonyms = ProcessSynonyms(synonyms); UpdateCategory(category); AuditLogManager.LogUserAction(user, AuditUserAction.ModifyCategory, string.Format("Modified category {0}, ID: {1}", category.Name, category.CategoryId)); }
/// <summary> /// Updates the last login date, account expiry date, and adds an user login audit entry /// </summary> public static void UpdateLastLoginAuditInfo(User user) { // Update the user user.LastLoginDate = DateTime.Now; user.AccountExpiryDate = DateTime.Now.AddDays(UserManager.AccountExpiryDays); User.Update(user); // Update the audit log string message = string.Format("Login successful. Account expiry date updated to {0}.", user.AccountExpiryDate.GetValueOrDefault().ToString("dd MMM yyyy HH:mm")); AuditLogManager.LogUserAction(user, AuditUserAction.UserLogin, message); }
public static void Update(int id, string text, string externalRef, string synonyms, User user) { Metadata o = Metadata.Get(id); o.Name = text; o.ExternalRef = externalRef; o.Synonyms = synonyms; Validate(o); Metadata.Update(o); CacheManager.InvalidateCache("Metadata", CacheType.All); AuditLogManager.LogUserAction(user, AuditUserAction.ModifyMetadata, "Updated metadata with ID: " + id); }
/// <summary> /// Changes the user status from pending email confirmation to approved /// </summary> public static void ConfirmEmailAddress(User user) { if (!user.IsNull) { if (user.UserStatusId == Convert.ToInt32((UserStatus.PendingEmailConfirmation))) { user.UserStatusId = Convert.ToInt32(UserStatus.Approved); SaveUser(user); AuditLogManager.LogUserAction(user, AuditUserAction.ConfirmEmailAddress, string.Format("Confirmed email address: {0}", user.Email)); } } }
/// <summary> /// Remove the cart item for the specified asset from the user's cart /// </summary> public void RemoveAssetFromCart(int assetId) { foreach (Cart cart in CartList) { if (cart.AssetId == assetId) { Cart.Delete(cart.CartId); AuditLogManager.LogAssetAction(assetId, User, AuditAssetAction.RemovedFromCart); AuditLogManager.LogUserAction(User, AuditUserAction.RemoveFromCart, string.Format("Removed AssetId: {0} from cart", assetId)); } } m_CartItems = null; }
public void RemoveLightbox(int lightboxId) { // Ensure that we have more than one lightbox if (UserLightboxes.Count == 1) { throw new InvalidLightboxException("cannot remove only lightbox"); } // Get the lightbox Lightbox lb = GetLightboxById(lightboxId); // Default lightboxes cannot be removed if (lb.IsDefault) { throw new InvalidLightboxException("cannot remove default lightbox"); } if (lb.IsLinked) { //remove linked lightbox LightboxLinked lightboxLinked = LightboxLinked.GetLightboxLinked(User.UserId.GetValueOrDefault(-1), lightboxId); if (!lightboxLinked.IsNull) { LightboxLinked.Delete(lightboxLinked.LightboxLinkedId); } // Update audit log AuditLogManager.LogUserAction(User, AuditUserAction.RemoveLightbox, string.Format("Removed linked lightbox: {0} (LightboxLinkedId: {1})", lb.Name, lightboxLinked.LightboxLinkedId)); } else { // Non-superadmins can only remove their own lightboxes if (User.UserRole != UserRole.SuperAdministrator && lb.UserId != User.UserId.GetValueOrDefault()) { throw new InvalidLightboxException("cannot remove lightbox not created by you"); } // Delete it Lightbox.Delete(lb.LightboxId); // Update audit log AuditLogManager.LogUserAction(User, AuditUserAction.RemoveLightbox, string.Format("Removed lightbox: {0} (LightboxId: {1})", lb.Name, lb.LightboxId)); } // Fire event OnLightboxListChanged(); }
/// <summary> /// Empties the specified user's cart /// </summary> /// <param name="log">Boolean value specifying whether the asset and user logs should be updated</param> public void EmptyCart(bool log) { foreach (Cart cartItem in CartList) { Cart.Delete(cartItem.CartId); if (log) { AuditLogManager.LogAssetAction(cartItem.AssetId, User, AuditAssetAction.RemovedFromCart, "User emptied cart"); AuditLogManager.LogUserAction(User, AuditUserAction.EmptyCart, string.Format("User emptied cart. Removed AssetId: {0} from cart", cartItem.AssetId)); } } m_CartItems = null; }
/// <summary> /// Deletes a user (marks them as deleted) /// </summary> /// <param name="adminUser">The admin user performing the delete operation</param> /// <param name="userId">The user to be marked as deleted</param> public static void DeleteUser(User adminUser, int userId) { User user = User.Get(userId); if (!user.IsNull) { // Change email address and append user id onto it // This is in case another user tries to register // with it or this user tries to re-register. user.Email = user.UserId + "_" + user.Email; user.IsDeleted = true; User.Update(user); AuditLogManager.LogUserAction(adminUser, AuditUserAction.DeleteUser, string.Format("Deleted user: {0}, with UserId: {1}", user.FullName, user.UserId)); } }
public static void ChangePassword(User user, string existingPassword, string newPassword, string newPasswordConfirmation) { // First make sure that the existing password the user has entered is valid if (!user.CheckPassword(existingPassword)) { throw new ChangePasswordException("Old password is incorrect"); } // Ensure that they entered a new password if (StringUtils.IsBlank(newPassword)) { throw new ChangePasswordException("New password cannot be blank"); } // Ensure that the new password and confirm new password match if (newPassword.Trim() != newPasswordConfirmation.Trim()) { throw new ChangePasswordException("New password does not match confirmed password"); } // Ensure that the user has not used the new password recently if (PasswordHistory.IsRecentPassword(user, newPassword)) { throw new ChangePasswordException("New password has been used recently and cannot be used again"); } // Validate the new password, ensuring it meets all password criteria ErrorList e = PasswordGenerator.ValidatePassword(newPassword); if (e.Count > 0) { throw new ChangePasswordException(e[0].ToString()); } // Everything has password. Set the new password and update the user's // password expiry date. Then save the user back to the database. user.SetPassword(newPassword); user.PasswordExpiryDate = DateTime.Now.AddDays(PasswordExpiryDays); User.Update(user); // Update the user's password history (this is so that we can stop the same // password from being used again in future). PasswordHistory.UpdateUserPasswordHistory(user); // Update the audit log AuditLogManager.LogUserAction(user, AuditUserAction.ChangePassword, "Changed password"); }
/// <summary> /// Used for users created by an admin from the admin area /// </summary> /// <param name="user">The user being created</param> /// <param name="creator">The admin user creating the user</param> /// <param name="notify">Boolean specifying whether welcome email should be sent</param> public static void Create(User user, User creator, bool notify) { // First run standard validations ErrorList errorList = ValidateUser(user); if (!notify && string.IsNullOrEmpty(user.UnencryptedPassword)) { errorList.Add("Password must be specified when welcome email is not being sent"); } // Quit if any validation errors occurred if (errorList.Count > 0) { throw new InvalidUserException(errorList, user); } // Bypass the standard admin approval as this user is created by an admin // Just pre-approve this account. user.UserStatus = UserStatus.Approved; // Set account expiry date user.AccountExpiryDate = DateTime.Now.AddDays(AccountExpiryDays); // Expire password immediately so that user must change it on first login user.PasswordExpiryDate = DateTime.Now.AddDays(-1); // Save user to database SaveUser(user); //generate a new user api token user.RegenerateUserAPIToken(); // Update the audit log for both the admin and new user AuditLogManager.LogUserAction(creator, AuditUserAction.AddUser, string.Format("Created user: {0}, with UserId: {1}", user.FullName, user.UserId)); AuditLogManager.LogUserAction(user, AuditUserAction.RegisteredByAdmin, string.Format("Created by admin: {0}", creator.FullName)); // Fire events if (notify) { if (UserCreatedByAdmin != null) { UserCreatedByAdmin(null, new UserEventArgs(user)); } } }
/// <summary> /// Deletes a Category only if it doesn't have children /// </summary> /// <param name="categoryId"> The id of the category to be deleted</param> /// <param name="user">User doing the delete</param> public static void DeleteCategory(int categoryId, User user) { Category category = Category.Get(categoryId); if (category.IsRootCategory) { throw new CategoryException(string.Format("The category named '{0}' cannot be deleted because it is the root category", category.Name)) { ErrorCode = "root-category" } } ; if (category.SubCategories.Count > 0) { throw new CategoryException(string.Format("The category named '{0}' cannot be deleted because it contains sub-categories", category.Name)) { ErrorCode = "has-subcategories" } } ; int count = GetFullAssetCount(categoryId); if (count > 0) { // This should be caught client-side, so update the asset count and invalidate cache // In case the external category count updater has not updated it yet. category.FullAssetCount = count; Category.Update(category); CacheManager.InvalidateCache("Category", CacheType.All); throw new CategoryException(string.Format("The category named '{0}' cannot be deleted because it has {1} assets assigned to it", category.Name, count)) { ErrorCode = "has-assets" }; } Category.Delete(categoryId); CacheManager.InvalidateCache("Category", CacheType.All); AuditLogManager.LogUserAction(user, AuditUserAction.DeleteCategory, string.Format("Deleted category: {0}, ID: {1}", category.Name, category.CategoryId)); }
/// <summary> /// Adds the asset with the specified ID to the user's cart. /// </summary> public void AddAssetToCart(int assetId) { if (CartContainsAsset(assetId)) { return; } Cart cart = Cart.New(); cart.UserId = User.UserId.GetValueOrDefault(); cart.AssetId = assetId; cart.DateAdded = DateTime.Now; Cart.Update(cart); AuditLogManager.LogAssetAction(assetId, User, AuditAssetAction.AddedToCart); AuditLogManager.LogUserAction(User, AuditUserAction.AddToCart, string.Format("Added AssetId: {0} to cart", assetId)); m_CartItems = null; }
public Lightbox CreateLightbox(string name, bool isDefault) { Lightbox lb = Lightbox.New(); lb.UserId = User.UserId.GetValueOrDefault(); lb.Name = name; lb.IsDefault = false; lb.CreateDate = DateTime.Now; SaveLightbox(lb); if (isDefault) { SetDefaultLightbox(lb.LightboxId.GetValueOrDefault()); } AuditLogManager.LogUserAction(User, AuditUserAction.AddLightbox, string.Format("Created lightbox: {0} (LightboxId: {1})", lb.Name, lb.LightboxId)); return(lb); }
public static Metadata Add(string text, int?parentId, int brandId, int groupNumber, string externalRef, string synonyms, User user) { Metadata o = Metadata.New(); o.Name = text; o.ParentMetadataId = parentId; o.BrandId = brandId; o.GroupNumber = groupNumber; o.ExternalRef = externalRef; o.Synonyms = synonyms; if (o.ParentMetadataId.GetValueOrDefault() <= 0) { o.ParentMetadataId = null; } var sibglings = MetadataCache.Instance .GetList(brandId, groupNumber) .Where(m => ( //either we are adding to the top parent level parentId == 0 && !m.ParentMetadataId.HasValue) || //or we need all siblings with the same parent m.ParentMetadataId == parentId ) .ToList(); o.MetadataOrder = sibglings.Count == 0 ? 1 : sibglings.OrderBy(s => s.MetadataOrder).Last().MetadataOrder + 1; Validate(o); o = Metadata.Update(o); CacheManager.InvalidateCache("Metadata", CacheType.All); if (!user.IsNull) { AuditLogManager.LogUserAction(user, AuditUserAction.AddMetadata, string.Format("Added Metadata with ID: {0}. Name: {1}", o.MetadataId, o.Name)); } return(o); }
public static void Move(int metadataId, int parentId, User user, int order) { var metadata = Metadata.Get(metadataId); IList <Metadata> subMetas; if (parentId > 0) { var parentMetadata = Metadata.Get(parentId); subMetas = parentMetadata.Children; } else {//we are at root level - i.e. all metas are with parent=NULL //so get all siblings by brandId and group number subMetas = (from m in MetadataCache.Instance.GetList(metadata.BrandId.GetValueOrDefault(), metadata.GroupNumber) where !m.ParentMetadataId.HasValue select m).ToList(); } // Reorder top level categories foreach (var meta in subMetas) { if ((meta.MetadataOrder >= order) && (meta.MetadataId != metadataId)) { meta.MetadataOrder += 1; Metadata.Update(meta); } } metadata.ParentMetadataId = parentId; metadata.MetadataOrder = order; if (metadata.ParentMetadataId.GetValueOrDefault() <= 0) { metadata.ParentMetadataId = null; } Metadata.Update(metadata); CacheManager.InvalidateCache("Metadata", CacheType.All); AuditLogManager.LogUserAction(user, AuditUserAction.ModifyMetadata, "Moved metadata with ID: " + metadataId); }
public static void EnsureUserHasDefaultLightbox(User user) { if (user.IsNew || user.IsNull) { return; } LightboxFinder finder = new LightboxFinder { UserId = user.UserId.GetValueOrDefault(), IsDefault = true }; int count = Lightbox.GetCount(finder); if (count == 0) { Lightbox lb = Lightbox.New(); lb.UserId = user.UserId.GetValueOrDefault(); lb.Name = "My Assets"; lb.IsDefault = true; lb.CreateDate = DateTime.Now; Lightbox.Update(lb); AuditLogManager.LogUserAction(user, AuditUserAction.AddLightbox, "System created default lightbox as there were no other ligthboxes"); } }
/// <summary> /// Verify the user credentials and the account, and if if valid, returns the user /// </summary> /// <param name="email">Email Address</param> /// <param name="password">Password</param> /// <exception cref="LoginException">Thrown if email or password is missing, account is not found, or password is invalid</exception> /// <exception cref="LoginSecurityException">Thrown if the account is pending admin approval, inactive, suspended, or the IP address is unknown and home access is not enabled</exception> /// <exception cref="UserPendingEmailConfirmationException">Thrown if the account is pending email confirmation</exception> /// <exception cref="AccountExpiredException">Thrown if the account is expired</exception> /// <exception cref="PasswordExpiredException">Thrown if the password is expired</exception> public static User Login(string email, string password) { // Remove space around posted values email = email.Trim(); password = password.Trim(); // Ensure email and password exists if (email.Length == 0 || password.Length == 0) { throw new LoginException("Please enter email and password", User.Empty); } // Get user matching email User user = User.GetByEmail(email); // Ensure user was found if (user.IsNull) { throw new LoginException("User account not found", user); } // Get any info about bad logins BadLoginInfo badLoginInfo = user.GetBadLoginInfo(m_BadLoginLockoutMinutes); // Check that the account isn't locked based on the bad login info if (AccountIsLocked(badLoginInfo)) { throw new LoginException("User account is locked. Please try again in " + m_BadLoginLockoutMinutes + " minutes.", user); } // Get the IP address as we'll need it later string ipAddress = BusinessHelper.GetCurrentIpAddress(); // Ensure password is correct if (!user.CheckPassword(password)) { // Update log m_Logger.DebugFormat("Login failed for {0}, UserId: {1} Invalid password.", user.FullName, user.UserId); AuditLogManager.LogUserAction(user, AuditUserAction.UserLogin, "Login Failed. Invalid Password."); // Update bad login info badLoginInfo.BadLoginCount++; badLoginInfo.LastBadLoginDate = DateTime.Now; // Check to see if this failed login has locked the account if (AccountIsLocked(badLoginInfo)) { throw new LoginException("Too many bad login attempts. Please try again in " + m_BadLoginLockoutMinutes + " minutes.", user); } // Otherwise, bad login but account isn't locked throw new LoginException("Invalid Password", user); } // Ensure user is not pending admin approval if (user.UserStatus == UserStatus.PendingAdminApproval) { m_Logger.DebugFormat("Login failed for {0}, UserId: {1} Account is pending admin approval.", user.FullName, user.UserId); AuditLogManager.LogUserAction(user, AuditUserAction.UserLogin, "Login Failed. Account pending admin approval."); throw new LoginSecurityException(user, "This account is awaiting approval", ipAddress); } // Ensure user is not pending email confirmation if (user.UserStatus == UserStatus.PendingEmailConfirmation) { m_Logger.DebugFormat("Login failed for {0}, UserId: {1} Account is pending email confirmation.", user.FullName, user.UserId); AuditLogManager.LogUserAction(user, AuditUserAction.UserLogin, "Login Failed. Account pending email confirmation."); throw new UserPendingEmailConfirmationException("This account is pending email confirmation", user); } // Ensure user is not rejected if (user.UserStatus == UserStatus.Rejected) { m_Logger.DebugFormat("Login failed for {0}, UserId: {1} Account is rejected.", user.FullName, user.UserId); AuditLogManager.LogUserAction(user, AuditUserAction.UserLogin, "Login Failed. Account status is rejected."); throw new LoginSecurityException(user, "This account is inactive", ipAddress); } // Ensure user is not suspended if (user.IsSuspended) { m_Logger.DebugFormat("Login failed for {0}, UserId: {1} Account is suspended.", user.FullName, user.UserId); AuditLogManager.LogUserAction(user, AuditUserAction.UserLogin, "Login Failed. Account is suspended."); throw new LoginSecurityException(user, "This account has been suspended", ipAddress); } // Ensure user can login from unapproved ip address if they are logging in from an unapproved ip address if (Settings.IpAddressRestrictionEnabled && !UserSecurityManager.IsApprovedIpAddress(ipAddress) && !user.IsAllowedExternalAccess) { m_Logger.DebugFormat("Login failed for {0}, UserId: {1} The IP address '{2}' is unapproved and account does not have external access enabled.", user.FullName, user.UserId, ipAddress); AuditLogManager.LogUserAction(user, AuditUserAction.UserLogin, string.Format("Login Failed. The IP address '{0}' is unapproved and user account does not have home access rights.", ipAddress)); throw new LoginSecurityException(user, "Unable to log in. Unknown IP Address.", ipAddress); } // Ensure the user account has not expired if (user.GetAccountExpiryDate() < DateTime.Now) { m_Logger.DebugFormat("Login succeeded for {0}, UserId: {1} but account is expired", user.FullName, user.UserId); AuditLogManager.LogUserAction(user, AuditUserAction.UserLogin, "Login succeeded, but account has expired."); throw new AccountExpiredException("This account has expired.", user); } // Ensure the password has not expired if (user.GetPasswordExpiryDate() < DateTime.Now) { m_Logger.DebugFormat("Login succeeded for {0}, UserId: {1} but password is expired", user.FullName, user.UserId); AuditLogManager.LogUserAction(user, AuditUserAction.UserLogin, "Login succeeded, but password has expired"); throw new PasswordExpiredException("This account's password has expired", user); } //create new session api token if (!UserManager.APISessionIsValid(user)) { UserManager.RenewSessionAPIToken(user); } // Update login date, audit login, etc UpdateLastLoginAuditInfo(user); return(user); }
/// <summary> /// Logs the user out (records an audit log event) /// </summary> public static void Logout(User user) { m_Logger.DebugFormat("User: {0}, UserId: {1} logged out successfully", user.FullName, user.UserId); AuditLogManager.LogUserAction(user, AuditUserAction.Logout, "Logged out manually"); }