Пример #1
0
        /// <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());
                }
            }
        }
Пример #2
0
        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);
            }
        }
Пример #3
0
        /// <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);
        }
Пример #4
0
        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));
        }
Пример #5
0
        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);
        }
Пример #6
0
        /// <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));
        }
Пример #7
0
        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;
        }
Пример #8
0
        /// <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));
        }
Пример #9
0
        /// <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);
        }
Пример #10
0
        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);
        }
Пример #11
0
        /// <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));
                }
            }
        }
Пример #12
0
        /// <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;
        }
Пример #13
0
        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();
        }
Пример #14
0
        /// <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;
        }
Пример #15
0
        /// <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));
            }
        }
Пример #16
0
        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");
        }
Пример #17
0
        /// <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));
                }
            }
        }
Пример #18
0
        /// <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));
        }
Пример #19
0
        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);
        }
Пример #20
0
        /// <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;
        }
Пример #21
0
        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);
        }
Пример #22
0
        /// <summary>
        /// Delegates an asset to another user
        /// </summary>
        /// <param name="asset">The asset to be delegated</param>
        /// <param name="newContactEmail">The email address of the user to which the asset should be delegated. This must be an upload user or above.</param>
        /// <exception cref="InvalidAssetDelegationException">Thrown if the specified email address does not belong to a valid user, or if belongs to a user without upload permissions</exception>
        private static void DelegateAsset(Asset asset, string newContactEmail)
        {
            if (StringUtils.IsBlank(newContactEmail))
            {
                throw new InvalidAssetDelegationException("System Error: Contact Email is blank", asset, User.Empty);
            }

            // First get the user we are delegating to
            User user = User.GetByEmail(newContactEmail);

            // Ensure we have a valid user
            if (user.IsNull)
            {
                throw new InvalidAssetDelegationException("Email address does not belong to a valid user", asset, user);
            }

            // Ensure the user is at least an upload user
            if (user.UserRoleId < Convert.ToInt32(UserRole.UploadUser))
            {
                throw new InvalidAssetDelegationException("Email address does not belong to a user with upload permissions", asset, user);
            }

            // Otherwise, user is valid, so re-assign the asset
            asset.UploadedByUserId = user.UserId.GetValueOrDefault();
            asset.ContactEmail     = user.Email;

            // Save it
            Asset.Update(asset);

            // Log it
            AuditLogManager.LogAssetAction(asset, user, AuditAssetAction.SavedAsset, "Asset was delegated to this user");
            m_Logger.DebugFormat("Asset with AssetId: {0} delegated to user: {1}", asset.AssetId, user.FullName);

            // Fire email notification
            if (AssetDelegated != null)
            {
                AssetDelegatedEventArgs e = new AssetDelegatedEventArgs(asset, user);
                AssetDelegated(null, e);
            }
        }
Пример #23
0
        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);
        }
Пример #24
0
        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");
            }
        }
Пример #25
0
        /// <summary>
        /// Creates an order from the user's cart.
        /// </summary>
        public static Order CreateOrderFromCart(User user)
        {
            // Create new cart manager for easy access to cart
            CartManager cm = new CartManager(user);

            // Ensure that the cart contains orderable items
            ValidateCart(cm.CartList, user);

            // Create the order
            Order order = Order.New();

            order.UserId    = user.UserId.GetValueOrDefault();
            order.OrderDate = DateTime.Now;

            // Ensure there's no order items
            Debug.Assert(order.OrderItemList.Count == 0);

            // Now add the cart items to it
            foreach (Cart cartItem in cm.CartList)
            {
                Asset asset = cartItem.Asset;

                // Get the asset status for the cart item
                AssetStatus assetStatus = AssetManager.GetAssetStatusForUser(asset, user);

                // Only add assets that are actually available
                // (Ignore withdrawn and expired assets)
                if (assetStatus == AssetStatus.Available)
                {
                    // Set the order item status based on whether the item is restricted or not
                    bool isRestricted = EntitySecurityManager.IsAssetRestricted(user, asset);

                    // Create new order item
                    OrderItem orderItem = OrderItem.New();

                    // Order items that are for restricted assets are set to awaiting approval
                    // and need to be approved by the user who uploaded them by default
                    // (though this can change, and be reassigned to the BU admin or superadmin,
                    // as per the workflow and scheduled scripts)
                    if (isRestricted)
                    {
                        orderItem.OrderItemStatus  = OrderItemStatus.AwaitingApproval;
                        orderItem.AssignedToUserId = asset.UploadedByUser.GetOrderItemApproverUserId();
                    }
                    else
                    {
                        orderItem.OrderItemStatus  = OrderItemStatus.Preapproved;
                        orderItem.AssignedToUserId = null;
                    }

                    orderItem.AssetId        = cartItem.AssetId;
                    orderItem.Notes          = cartItem.Notes;
                    orderItem.RequiredByDate = cartItem.RequiredByDate;
                    orderItem.CreateDate     = DateTime.Now;
                    order.OrderItemList.Add(orderItem);
                }
            }

            // Save the order
            SaveOrder(order);

            // Log which assets were ordered
            foreach (OrderItem orderItem in order.OrderItemList)
            {
                AuditLogManager.LogAssetAction(orderItem.AssetId, user, AuditAssetAction.Ordered, string.Format("OrderId: {0}", orderItem.OrderId));
            }

            // Log order against user
            AuditLogManager.LogUserAction(user, AuditUserAction.OrderAssets, string.Format("Placed order, with OrderId: {0} containing {1} assets", order.OrderId, order.OrderItemList.Count));

            // Remove the items from the cart
            cm.EmptyCart(false);

            // Complete the order if all items have been processed
            if (AllOrderItemsProcessed(order))
            {
                // Nothing in the order required approval, so automatically complete it
                CompleteOrder(order);
            }
            else
            {
                // Fire event
                if (OrderCreated != null)
                {
                    OrderCreated(null, new OrderEventArgs(order));
                }
            }

            return(order);
        }
Пример #26
0
        private void SendLightboxToUser(Lightbox lightbox, User user, string recipient, string subject, string message, DateTime?expiryDate, bool?downloadLinks, bool?linked, bool?editable)
        {
            m_Logger.Debug("SendLightboxToUser - start");

            int?createdLightboxId = null;
            int?linkedLightboxId  = null;

            if (!user.IsNull)
            {
                //check to see if should link the lightbox or
                //make a new copy of it
                if (linked.GetValueOrDefault(false))
                {
                    // create new linked lightbox
                    LightboxLinked linkedLightbox = LightboxLinked.New();
                    linkedLightbox.UserId     = user.UserId.GetValueOrDefault();
                    linkedLightbox.LightboxId = lightbox.LightboxId.GetValueOrDefault();
                    linkedLightbox.IsEditable = editable;
                    linkedLightbox.ExpiryDate = expiryDate;
                    LightboxLinked.Update(linkedLightbox);

                    linkedLightboxId = linkedLightbox.LightboxLinkedId;
                }
                else
                {
                    // copying lightbox
                    string lightboxName    = lightbox.Name;
                    string newLightboxName = GetLightboxNameForSending(lightboxName);

                    Lightbox createdLightbox = DuplicateLightbox(lightbox.LightboxId.GetValueOrDefault(), newLightboxName, user.UserId.GetValueOrDefault());
                    createdLightboxId = createdLightbox.LightboxId.GetValueOrDefault();
                }
            }

            LightboxSent lbs = LightboxSent.New();

            lbs.LightboxId        = lightbox.LightboxId.GetValueOrDefault();
            lbs.CreatedLightboxId = createdLightboxId;
            lbs.SenderId          = User.UserId.GetValueOrDefault();
            lbs.RecipientEmail    = recipient;
            lbs.Subject           = subject;
            lbs.Message           = message;
            lbs.DateSent          = DateTime.Now;
            lbs.ExpiryDate        = expiryDate;
            lbs.DownloadLinks     = downloadLinks;
            lbs.LightboxLinkedId  = linkedLightboxId;


            if (lbs.RecipientEmail.Length > 150)
            {
                throw new SystemException("Recipient email cannot exceed 150 characters");
            }

            if (lbs.Subject.Length > 150)
            {
                throw new SystemException("Subject cannot exceed 150 characters");
            }

            if (lbs.Message.Length > 500)
            {
                throw new SystemException("Message cannot exceed 500 characters");
            }
            LightboxSent.Update(lbs);

            if (LightboxSentToUser != null)
            {
                LightboxSentToUser(this, new LightboxSentEventArgs(lbs));
            }

            AuditLogManager.LogUserAction(User, AuditUserAction.SendLightbox, string.Format("Sent LightboxId: {0} to: {1}", lightbox.LightboxId, recipient));

            m_Logger.Debug("SendLightboxToUser - end");
        }
Пример #27
0
        /// <summary>
        /// Used for public registrations
        /// </summary>
        public static void Register(User user)
        {
            // Initialise the approved company to a null instance
            Company company = Company.Empty;

            // Get the IP Address
            string ipAddress = BusinessHelper.GetCurrentIpAddress();

            // Only check for an approved company if email is not blank.
            if (!StringUtils.IsBlank(user.Email))
            {
                company = UserSecurityManager.GetCompanyByDomain(user.Email);
            }

            //Process depends on the value defined in the AppSettings key "RegisterUserRequiresKnownEmailFormat".
            switch (RegistrationEmailFormat)
            {
            case RegistrationEmailFormatType.Empty:
            {
                if (user.IsEmployee && !company.IsNull)
                {
                    user.UserStatus = UserStatus.PendingEmailConfirmation;
                }
                else
                {
                    user.UserStatus = UserStatus.PendingAdminApproval;
                }

                break;
            }

            case RegistrationEmailFormatType.InternalUsers:
            {
                if (user.IsEmployee)
                {
                    if (company.IsNull)
                    {
                        throw new RegistrationSecurityException(user, "Your email address is not recognised as being from a company authorised to use this website. Please contact the system administrator for further information.", ipAddress);
                    }

                    user.UserStatus = UserStatus.PendingEmailConfirmation;
                }
                else
                {
                    user.UserStatus = UserStatus.PendingAdminApproval;
                }

                break;
            }

            case RegistrationEmailFormatType.AllUsers:
            {
                if (company.IsNull)
                {
                    throw new RegistrationSecurityException(user, "Your email address is not recognised as being from a company authorised to use this website. Please contact the system administrator for further information.", ipAddress);
                }

                user.UserStatus = UserStatus.PendingEmailConfirmation;

                break;
            }
            }

            // Check if user is employee or belongs to an internal company
            // (If a user belongs to an internal company, then they are effectively an employee)
            bool isEmployeeOrInternal = (user.IsEmployee || company.IsInternal);

            // They are an employee or their email belongs to an internal company, but their ip address isn't approved so quit
            if (Settings.IpAddressRestrictionEnabled && isEmployeeOrInternal && !UserSecurityManager.IsApprovedIpAddress(ipAddress))
            {
                throw new RegistrationSecurityException(user, "Your IP address is not recognised as being from a company authorised to use this website. Please contact the system administrator for further information.", ipAddress);
            }

            // Everything passed, update some standard user settings
            user.IsAccountNonExpiring  = false;
            user.IsPasswordNonExpiring = false;
            user.UserRole     = UserRole.Normal;
            user.RegisterDate = DateTime.Now;

            // Set up default user rules and expiry dates
            user.IsAllowedExternalAccess = !user.IsEmployee;
            user.EnableFilePathIngestion = false;
            user.AccountExpiryDate       = DateTime.Now.AddDays(AccountExpiryDays);
            user.PasswordExpiryDate      = DateTime.Now.AddDays(PasswordExpiryDays);

            // Validate standard business objecr requirements
            ErrorList errors = ValidateUser(user);

            // Throw an error if the user fields are not all valid
            if (errors.Count > 0)
            {
                throw new InvalidUserException(errors, user);
            }

            // Save the user
            User u = SaveUser(user);

            FireUserCreateEvent(user);

            AuditLogManager.LogUserAction(u, AuditUserAction.Register, string.Format("Registration successful. Registered from IP Address: {0}.  Account status is: {1}", ipAddress, u.UserStatus));
        }
Пример #28
0
 private void LogUploadedAsset(Asset asset, string notes)
 {
     AuditLogManager.LogAssetAction(asset, UploadedBy, AuditAssetAction.UploadedAsset, notes);
     AuditLogManager.LogUserAction(UploadedBy, AuditUserAction.UploadAsset, string.Format("Uploaded {0} asset - AssetId: {1}. {2}", asset.AssetType.Name, asset.AssetId, notes));
 }
Пример #29
0
 /// <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");
 }
Пример #30
0
        /// <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);
        }