Exemplo n.º 1
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            int threadID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["ThreadID"]);

            _thread = ThreadGuiHelper.GetThread(threadID);
            if (_thread == null)
            {
                // not found, return to default page
                Response.Redirect("default.aspx", true);
            }

            // Check access credentials
            bool userHasAccess             = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AccessForum);
            bool userMayDoThreadManagement = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.ForumSpecificThreadManagement) ||
                                             SessionAdapter.HasSystemActionRight(ActionRights.SystemWideThreadManagement);

            if (!userHasAccess || !userMayDoThreadManagement)
            {
                // doesn't have access to this forum or may not alter the thread's properties. redirect
                Response.Redirect("default.aspx");
            }

            if (!Page.IsPostBack)
            {
                chkIsClosed.Checked = _thread.IsClosed;
                chkIsSticky.Checked = _thread.IsSticky;
                tbxSubject.Value    = _thread.Subject;
            }
        }
Exemplo n.º 2
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            // If the user doesn't have any access rights to management stuff, the user should
            // be redirected to the default of the global system.
            if (!SessionAdapter.HasSystemActionRights())
            {
                // doesn't have system rights. redirect.
                Response.Redirect("../Default.aspx", true);
            }

            // Check if the user has the right systemright
            if (!SessionAdapter.HasSystemActionRight(ActionRights.SecurityManagement))
            {
                // no, redirect to admin default page, since the user HAS access to the admin menu.
                Response.Redirect("Default.aspx", true);
            }

            _roleID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["RoleID"]);

            if (!Page.IsPostBack)
            {
                // get the role and show the description
                RoleEntity role = SecurityGuiHelper.GetRole(_roleID);

                if (!role.IsNew)
                {
                    lblRoleDescription.Text = role.RoleDescription;
                }
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Resets the password for the user related to the password token specified to the newPassword specified
        /// It'll then remove the password reset token entity specified
        /// </summary>
        /// <param name="newPassword">the new password specified</param>
        /// <param name="passwordResetToken">the reset token. Will be removed in this method if password reset is successful</param>
        /// <returns>true if successful, false otherwise</returns>
        public static async Task <bool> ResetPasswordAsync(string newPassword, PasswordResetTokenEntity passwordResetToken)
        {
            if (string.IsNullOrWhiteSpace(newPassword) || passwordResetToken == null)
            {
                return(false);
            }

            using (var adapter = new DataAccessAdapter())
            {
                var q    = new QueryFactory().User.Where(UserFields.UserID.Equal(passwordResetToken.UserID));
                var user = await adapter.FetchFirstAsync(q).ConfigureAwait(false);

                if (user == null)
                {
                    return(false);
                }

                user.Password = HnDGeneralUtils.HashPassword(newPassword, performPreMD5Hashing: true);
                var uow = new UnitOfWork2();
                uow.AddForSave(user);
                uow.AddForDelete(passwordResetToken);
                var toReturn = await uow.CommitAsync(adapter);

                return(toReturn == 2);
            }
        }
Exemplo n.º 4
0
        protected void btnSet_Click(object sender, EventArgs e)
        {
            if (!_userMayManageSupportQueueContents)
            {
                return;
            }

            // move this thread to a support queue.
            // check the selected ID to see if it is the same as the current Queue. If so, ignore, otherwise set the queue.
            int selectedQueueID = HnDGeneralUtils.TryConvertToInt(cbxSupportQueues.SelectedValue);

            SupportQueueEntity containingQueue = SupportQueueGuiHelper.GetQueueOfThread(_thread.ThreadID);

            // now set the queue if:
            // a) the thread isn't in a queue and the selected queueID > 0 (so not None)
            // b) the thread is in a queue and the selected queueuID isn't the id of the queue containing the thread
            if (((containingQueue == null) && (selectedQueueID != -1)) || ((containingQueue != null) && (containingQueue.QueueID != selectedQueueID)))
            {
                // Set the queue. if the new queue is -1, remove from queue.
                if (selectedQueueID > 0)
                {
                    SupportQueueManager.AddThreadToQueue(_thread.ThreadID, selectedQueueID, SessionAdapter.GetUserID(), null);
                }
                else
                {
                    SupportQueueManager.RemoveThreadFromQueue(_thread.ThreadID, null);
                }
            }

            // done redirect to this page to refresh.
            Response.Redirect("Messages.aspx?ThreadID=" + _thread.ThreadID + "&StartAtMessage=" + _startMessageNo);
        }
Exemplo n.º 5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            int attachmentID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["AttachmentID"]);

            MessageEntity relatedMessage = MessageGuiHelper.GetMessageWithAttachmentLogic(attachmentID);

            if (relatedMessage == null)
            {
                // not found
                Response.Redirect("default.aspx", true);
            }

            // thread has been loaded into the related message object as well. This is needed for the forum access right check
            if (!SessionAdapter.CanPerformForumActionRight(relatedMessage.Thread.ForumID, ActionRights.AccessForum))
            {
                // user can't access this forum
                Response.Redirect("default.aspx", true);
            }

            // Check if the thread is sticky, or that the user can see normal threads started
            // by others. If not, the user isn't allowed to view the thread the message is in, and therefore is denied access.
            if ((relatedMessage.Thread.StartedByUserID != SessionAdapter.GetUserID()) &&
                !SessionAdapter.CanPerformForumActionRight(relatedMessage.Thread.ForumID, ActionRights.ViewNormalThreadsStartedByOthers) &&
                !relatedMessage.Thread.IsSticky)
            {
                // user can't view the thread the message is in, because:
                // - the thread isn't sticky
                // AND
                // - the thread isn't posted by the calling user and the user doesn't have the right to view normal threads started by others
                Response.Redirect("default.aspx", true);
            }

            AttachmentEntity toStream = MessageGuiHelper.GetAttachment(attachmentID);

            if (toStream == null)
            {
                // not found
                Response.Redirect("default.aspx", true);
            }

            if (!toStream.Approved && !SessionAdapter.CanPerformForumActionRight(relatedMessage.Thread.ForumID, ActionRights.ApproveAttachment))
            {
                // the attachment hasn't been approved yet, and the caller isn't entitled to approve attachments, so deny.
                // approval of attachments requires to be able to load the attachment without the attachment being approved
                Response.Redirect("default.aspx", true);
            }

            // all set, load stream the attachment data to the browser
            // create header
            Response.ClearHeaders();
            Response.ClearContent();
            Response.AddHeader("Content-Type", "application/unknown");
            Response.AddHeader("Content-length", toStream.Filecontents.Length.ToString());
            Response.AddHeader("Content-Disposition", "attachment; filename=" + toStream.Filename.Replace(" ", "_"));
            Response.AddHeader("Content-Transfer-Encoding", "Binary");
            // stream the data
            Response.BinaryWrite(toStream.Filecontents);
            Response.Flush();
            Response.End();
        }
Exemplo n.º 6
0
        public async Task <ActionResult> Edit([Bind(nameof(MessageData.MessageText))]
                                              MessageData messageData, string submitButton, int id = 0)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToAction("Index", "Home"));
            }

            var(userMayEditMessages, message) = await PerformEditMessageSecurityChecksAsync(id);

            if (!userMayEditMessages)
            {
                return(RedirectToAction("Index", "Home"));
            }

            if (submitButton == "Post")
            {
                // parse message text to html
                var messageAsHtml = HnDGeneralUtils.TransformMarkdownToHtml(messageData.MessageText, ApplicationAdapter.GetEmojiFilenamesPerName(),
                                                                            ApplicationAdapter.GetSmileyMappings());
                await MessageManager.UpdateEditedMessageAsync(this.HttpContext.Session.GetUserID(), message.MessageID, messageData.MessageText, messageAsHtml,
                                                              this.Request.Host.Host, string.Empty);

                if (this.HttpContext.Session.CheckIfNeedsAuditing(AuditActions.AuditAlteredMessage))
                {
                    await SecurityManager.AuditAlteredMessageAsync(this.HttpContext.Session.GetUserID(), message.MessageID);
                }
            }

            return(await CalculateRedirectToMessageAsync(message.ThreadID, message.MessageID));
        }
Exemplo n.º 7
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            // If the user doesn't have any access rights to management stuff, the user should
            // be redirected to the default of the global system.
            if (!SessionAdapter.HasSystemActionRights())
            {
                // doesn't have system rights. redirect.
                Response.Redirect("../Default.aspx", true);
            }

            // Check if the user has the right systemright
            if (!SessionAdapter.HasSystemActionRight(ActionRights.SecurityManagement))
            {
                // no, redirect to admin default page, since the user HAS access to the admin menu.
                Response.Redirect("Default.aspx", true);
            }

            _roleID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["RoleID"]);

            if (!Page.IsPostBack)
            {
                // Get Role
                RoleEntity role = SecurityGuiHelper.GetRole(_roleID);
                _roleDescription = role.RoleDescription;

                // bind the users listbox to an entitycollection with all users.
                UserCollection users = UserGuiHelper.GetAllUsersNotInRole(_roleID);

                lbxUsers.DataSource     = users;
                lbxUsers.DataTextField  = "NickName";
                lbxUsers.DataValueField = "UserID";
                lbxUsers.DataBind();
            }
        }
Exemplo n.º 8
0
        private static void ConvertForumWelcomeTexts()
        {
            Console.WriteLine("Converting forum welcome texts. Republishing header texts as well.");
            var qf = new QueryFactory();

            using (var adapter = new DataAccessAdapter())
            {
                var forums = adapter.FetchQuery(qf.Forum);
                foreach (ForumEntity f in forums)
                {
                    string parserLog;
                    string messageAsXml;
                    bool   errorsOccurred;
                    string convertedText = TextParser.TransformUBBMessageStringToHTML(f.NewThreadWelcomeText, _parserData, out parserLog, out errorsOccurred, out messageAsXml);
                    if (errorsOccurred)
                    {
                        Console.WriteLine("\nERRORS: {0}", parserLog);
                        Console.WriteLine("ForumID: {0}\nForum welcome text:\n{1}--------------\n", f.ForumID, f.NewThreadWelcomeText);
                        f.NewThreadWelcomeText       = string.Empty;
                        f.NewThreadWelcomeTextAsHTML = string.Empty;
                    }
                    else
                    {
                        // html decode, so any &lt; etc. are converted back to the regular characters.
                        f.NewThreadWelcomeText       = HttpUtility.HtmlDecode(convertedText);
                        f.NewThreadWelcomeTextAsHTML = HnDGeneralUtils.TransformMarkdownToHtml(f.NewThreadWelcomeText, new Dictionary <string, string>(),
                                                                                               new Dictionary <string, string>());
                    }
                }
                Console.Write("\tPersisting forums...");
                adapter.SaveEntityCollection(forums);
                Console.WriteLine("DONE!");
            }
            Console.WriteLine("DONE");
        }
Exemplo n.º 9
0
        /// <summary>
        /// Registers a new user, using the properties of this class.
        /// </summary>
        /// <param name="nickName">Name of the nick.</param>
        /// <param name="dateOfBirth">The date of birth.</param>
        /// <param name="emailAddress">The email address.</param>
        /// <param name="emailAddressIsPublic">flag to signal if the emailaddress is visible for everyone or not</param>
        /// <param name="iconURL">The icon URL.</param>
        /// <param name="ipNumber">The ip number.</param>
        /// <param name="location">The location.</param>
        /// <param name="occupation">The occupation.</param>
        /// <param name="signature">The signature.</param>
        /// <param name="website">The website.</param>
        /// <param name="emailTemplatePath">The email template path.</param>
        /// <param name="emailData">The email data.</param>
        /// <param name="autoSubscribeThreads">Default value when user creates new threads.</param>
        /// <param name="defaultMessagesPerPage">Messages per page to display</param>
        /// <returns>
        /// UserID of new user or 0 if registration failed.
        /// </returns>
        public static int RegisterNewUser(string nickName, DateTime?dateOfBirth, string emailAddress, bool emailAddressIsPublic, string iconURL,
                                          string ipNumber, string location, string occupation, string signature, string website, string emailTemplatePath, Dictionary <string, string> emailData, ParserData parserData,
                                          bool autoSubscribeThreads, short defaultMessagesPerPage)
        {
            UserEntity newUser = new UserEntity();

            // initialize objects
            newUser.AmountOfPostings     = 0;
            newUser.DateOfBirth          = dateOfBirth;
            newUser.EmailAddress         = emailAddress;
            newUser.EmailAddressIsPublic = emailAddressIsPublic;
            newUser.IPNumber             = ipNumber;
            newUser.IconURL    = iconURL;
            newUser.IsBanned   = false;
            newUser.JoinDate   = DateTime.Now;
            newUser.Location   = location;
            newUser.NickName   = nickName;
            newUser.Occupation = occupation;
            newUser.Signature  = signature;
            newUser.Website    = website;
            string password = HnDGeneralUtils.GenerateRandomPassword();

            newUser.Password = HnDGeneralUtils.CreateMD5HashedBase64String(password);

            //Preferences
            newUser.AutoSubscribeToThread          = autoSubscribeThreads;
            newUser.DefaultNumberOfMessagesPerPage = defaultMessagesPerPage;

            if (!string.IsNullOrEmpty(signature))
            {
                newUser.SignatureAsHTML = TextParser.TransformSignatureUBBStringToHTML(signature, parserData);
            }
            else
            {
                newUser.SignatureAsHTML = "";
            }
            //Fetch the SystemDataEntity to use the "DefaultUserTitleNewUser" as the user title & the "DefaultRoleNewUser"
            // as the roleID of the newly created RoleUserEntity.
            SystemDataEntity systemData = SystemGuiHelper.GetSystemSettings();

            newUser.UserTitleID = systemData.DefaultUserTitleNewUser;

            RoleUserEntity roleUser = new RoleUserEntity();

            roleUser.RoleID = systemData.DefaultRoleNewUser;
            roleUser.User   = newUser;

            // first encode fields which could lead to cross-site-scripting attacks
            EncodeUserTextFields(newUser);

            // now save the new user entity and the new RoleUser entity recursively in one go. This will create a transaction for us
            // under the hood so we don't have to do that ourselves.
            if (newUser.Save(true))
            {
                // all ok, Email the password
                bool result = HnDGeneralUtils.EmailPassword(password, emailAddress, emailTemplatePath, emailData);
            }

            return(newUser.UserID);
        }
Exemplo n.º 10
0
        public async Task <ActionResult> Register(NewProfileData data)
        {
            if (!ModelState.IsValid)
            {
                return(View(data));
            }

            data.Sanitize();
            data.StripProtocolsFromUrls();

            var nickNameExists = await UserGuiHelper.CheckIfNickNameExistAsync(data.NickName);

            if (nickNameExists)
            {
                ModelState.AddModelError("NickName", "NickName already exists");
                return(View(data));
            }

            var result = await UserManager.RegisterNewUserAsync(data.NickName, data.DateOfBirth, data.EmailAddress, data.EmailAddressIsPublic, data.IconURL,
                                                                HnDGeneralUtils.GetRemoteIPAddressAsIP4String(this.HttpContext.Connection.RemoteIpAddress), data.Location,
                                                                data.Occupation, data.Signature, data.Website,
                                                                ApplicationAdapter.GetEmailData(this.Request.Host.Host, EmailTemplate.RegistrationReply),
                                                                data.AutoSubscribeToThread, data.DefaultNumberOfMessagesPerPage);

            if (result > 0)
            {
                this.HttpContext.Session.UpdateUserSettings(data);
                return(RedirectToAction("Login", "Account"));
            }

            return(View(data));
        }
Exemplo n.º 11
0
        private void btnSave_ServerClick(object sender, System.EventArgs e)
        {
            if (Page.IsValid)
            {
                int?supportQueueID         = null;
                int selectedSupportQueueID = Convert.ToInt32(cbxSupportQueues.SelectedItem.Value);
                if (selectedSupportQueueID > 0)
                {
                    supportQueueID = selectedSupportQueueID;
                }

                string newThreadWelcomeText       = null;
                string newThreadWelcomeTextAsHTML = null;
                if (tbxNewThreadWelcomeText.Text.Trim().Length > 0)
                {
                    // has specified welcome text, convert to HTML
                    newThreadWelcomeText = tbxNewThreadWelcomeText.Text.Trim();
                    string parserLog, textAsXML;
                    bool   errorsOccured;
                    newThreadWelcomeTextAsHTML = TextParser.TransformUBBMessageStringToHTML(newThreadWelcomeText, ApplicationAdapter.GetParserData(),
                                                                                            out parserLog, out errorsOccured, out textAsXML);
                }

                // store the data as a new forum.
                int forumID = ForumManager.CreateNewForum(HnDGeneralUtils.TryConvertToInt(cbxSections.SelectedItem.Value), tbxForumName.Value,
                                                          tbxForumDescription.Text, chkHasRSSFeed.Checked, supportQueueID, HnDGeneralUtils.TryConvertToInt(cbxThreadListInterval.SelectedValue),
                                                          HnDGeneralUtils.TryConvertToShort(tbxOrderNo.Text), HnDGeneralUtils.TryConvertToInt(tbxMaxAttachmentSize.Text),
                                                          HnDGeneralUtils.TryConvertToShort(tbxMaxNoOfAttachmentsPerMessage.Text), newThreadWelcomeText, newThreadWelcomeTextAsHTML);

                // done for now, redirect to self
                Response.Redirect("AddForum.aspx", true);
            }
        }
Exemplo n.º 12
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            int threadID       = HnDGeneralUtils.TryConvertToInt(Request.QueryString["ThreadID"]);
            int messageID      = HnDGeneralUtils.TryConvertToInt(Request.QueryString["MessageID"]);
            int startAtMessage = ThreadGuiHelper.GetStartAtMessageForGivenMessageAndThread(threadID, messageID, SessionAdapter.GetUserDefaultNumberOfMessagesPerPage());

            Response.Redirect("Messages.aspx?ThreadID=" + threadID + "&StartAtMessage=" + startAtMessage + "&#" + messageID, true);
        }
Exemplo n.º 13
0
 private void FillMemoInformation(ThreadData container)
 {
     if (container.UserMayEditMemo && (container.Thread.Memo.Length > 0))
     {
         // convert memo contents to HTML so it's displayed above the thread.
         container.MemoAsHTML = HnDGeneralUtils.TransformMarkdownToHtml(container.Thread.Memo, ApplicationAdapter.GetEmojiFilenamesPerName(),
                                                                        ApplicationAdapter.GetSmileyMappings());
     }
 }
Exemplo n.º 14
0
        protected void btnUpdate_Click(object sender, System.EventArgs e)
        {
            if (Page.IsValid)
            {
                GetViewState();

                // user has filled in the right values, update the user's data.
                string   nickName     = string.Empty;
                DateTime?dateOfBirth  = null;
                string   emailAddress = string.Empty;
                string   iconURL      = string.Empty;
                string   ipNumber     = string.Empty;
                string   location     = string.Empty;
                string   occupation   = string.Empty;
                string   password     = string.Empty;
                string   signature    = string.Empty;
                string   website      = string.Empty;

                if (tbxPassword1.Value.Length > 0)
                {
                    password = tbxPassword1.Value;
                }

                emailAddress = tbxEmailAddress.Value;
                iconURL      = tbxIconURL.Value;

                if (tbxDateOfBirth.Value.Length > 0)
                {
                    try
                    {
                        dateOfBirth = System.DateTime.Parse(tbxDateOfBirth.Value, CultureInfo.InvariantCulture.DateTimeFormat);
                    }
                    catch (FormatException)
                    {
                        // format exception, date invalid, ignore, will resolve to default.
                    }
                }

                location   = tbxLocation.Value;
                occupation = tbxOccupation.Value;
                signature  = tbxSignature.Value;
                website    = tbxWebsite.Value;

                bool result = UserManager.UpdateUserProfile(_selectedUserID, dateOfBirth, emailAddress, (_emailAddressIsVisible.Value == "true"), iconURL, location, occupation, password,
                                                            signature, website, HnDGeneralUtils.TryConvertToInt(cmbUserTitle.SelectedValue), ApplicationAdapter.GetParserData()
                                                            , (_autoSubscribeToThread.Value == "true"), HnDGeneralUtils.TryConvertToShort(_defaultNumberOfMessagesPerPage.Value));

                if (result)
                {
                    // all ok
                    phModifyResult.Visible    = true;
                    phFindUserArea.Visible    = false;
                    phProfileEditArea.Visible = false;
                }
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Page_Load(object sender, System.EventArgs e)
        {
            int threadID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["ThreadID"]);

            _thread = ThreadGuiHelper.GetThread(threadID);
            if (_thread == null)
            {
                // not found, return to start page
                Response.Redirect("default.aspx");
            }

            // Check credentials
            bool userHasAccess = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AccessForum);

            if (!userHasAccess)
            {
                // doesn't have access to this forum. redirect
                Response.Redirect("default.aspx");
            }

            // show user IP addresses if the user has system admin rights, security admin rights or user admin rights.
            _showIPAddresses = (SessionAdapter.HasSystemActionRight(ActionRights.SystemManagement) ||
                                SessionAdapter.HasSystemActionRight(ActionRights.SecurityManagement) ||
                                SessionAdapter.HasSystemActionRight(ActionRights.UserManagement));
            // Get the forum entity related to the thread. Use BL class. We could have used Lazy loading, though for the sake of separation, we'll
            // call into the BL class.
            ForumEntity forum = CacheManager.GetForum(_thread.ForumID);

            if (forum == null)
            {
                // not found, orphaned thread, return to default page.
                Response.Redirect("default.aspx");
            }

            // check if the user can view this thread. If not, don't continue.
            if ((_thread.StartedByUserID != SessionAdapter.GetUserID()) &&
                !SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.ViewNormalThreadsStartedByOthers) &&
                !_thread.IsSticky)
            {
                // can't view this thread, it isn't visible to the user
                Response.Redirect("default.aspx", true);
            }

            lblForumName_Header.Text = forum.ForumName;

            if (!Page.IsPostBack)
            {
                bool threadStartedByCurrentUser = (_thread.StartedByUserID == SessionAdapter.GetUserID());
                // Get messages and bind it to the repeater control. Use the startmessage to get only the message visible on the current page.
                MessagesInThreadTypedList messages = ThreadGuiHelper.GetAllMessagesInThreadAsTypedList(threadID, 0, 0);
                rptMessages.DataSource = messages;
                rptMessages.DataBind();
            }
        }
Exemplo n.º 16
0
        protected void btnYes_Click(object sender, EventArgs e)
        {
            bool result = UserManager.DeleteUser(HnDGeneralUtils.TryConvertToInt(lblUserID.Text));

            phDeleteResult.Visible = result;
            phUserInfo.Visible     = !result;
            if (result)
            {
                ApplicationAdapter.AddUserToListToBeLoggedOutByForce(lblNickname.Text);
            }
        }
Exemplo n.º 17
0
        private void btnStart_Click(object sender, System.EventArgs e)
        {
            // start the indexation. Grab the selected properties for the indexer.

            int amountToReparse = HnDGeneralUtils.TryConvertToInt(tbxAmountToReparse.Text.Trim());

            DateTime startDate       = cldStartDate.SelectedDate;
            int      amountProcessed = MessageManager.ReParseMessages(amountToReparse, startDate, chkRegenerateHTML.Checked, ApplicationAdapter.GetParserData());

            pnlReparseResults.Visible = true;
            lblReparseResults.Text    = "Number of messages re-parsed: " + amountProcessed;
        }
Exemplo n.º 18
0
        public async Task <ActionResult> Add([Bind(nameof(NewThreadData.MessageText), nameof(NewThreadData.ThreadSubject), nameof(NewThreadData.IsSticky),
                                                   nameof(NewThreadData.Subscribe))]
                                             NewThreadData newThreadData, string submitButton, int forumId = 0)
        {
            if (submitButton != "Post")
            {
                // apparently canceled
                if (forumId <= 0)
                {
                    return(RedirectToAction("Index", "Home"));
                }

                return(RedirectToAction("Index", "Forum", new { forumId = forumId }));
            }

            if (!ModelState.IsValid)
            {
                return(RedirectToAction("Index", "Home"));
            }

            var(userMayAddThread, forum, userMayAddStickThread) = await PerformAddThreadSecurityChecksAsync(forumId);

            if (!userMayAddThread)
            {
                return(RedirectToAction("Index", "Home"));
            }

            int newThreadId = 0;

            if (submitButton == "Post")
            {
                // allowed, proceed
                // parse message text to html
                var messageAsHtml = HnDGeneralUtils.TransformMarkdownToHtml(newThreadData.MessageText, ApplicationAdapter.GetEmojiFilenamesPerName(),
                                                                            ApplicationAdapter.GetSmileyMappings());
                var(newThreadIdFromCall, newMessageId) = await ForumManager.CreateNewThreadInForumAsync(forumId, this.HttpContext.Session.GetUserID(),
                                                                                                        newThreadData.ThreadSubject, newThreadData.MessageText,
                                                                                                        messageAsHtml, userMayAddStickThread&& newThreadData.IsSticky,
                                                                                                        this.Request.Host.Host, forum.DefaultSupportQueueID,
                                                                                                        newThreadData.Subscribe);

                newThreadId = newThreadIdFromCall;
                ApplicationAdapter.InvalidateCachedNumberOfThreadsInSupportQueues();
                if (this.HttpContext.Session.CheckIfNeedsAuditing(AuditActions.AuditNewThread))
                {
                    await SecurityManager.AuditNewThreadAsync(this.HttpContext.Session.GetUserID(), newThreadId);
                }

                _cache.Remove(CacheManager.ProduceCacheKey(CacheKeys.SingleForum, forumId));
            }

            return(Redirect(this.Url.Action("Index", "Thread", new { threadId = newThreadId, pageNo = 1 })));
        }
Exemplo n.º 19
0
        /// <summary>
        /// Registers a new user, using the properties of this class.
        /// </summary>
        /// <param name="nickName">Name of the nick.</param>
        /// <param name="dateOfBirth">The date of birth.</param>
        /// <param name="emailAddress">The email address.</param>
        /// <param name="emailAddressIsPublic">flag to signal if the emailaddress is visible for everyone or not</param>
        /// <param name="iconUrl">The icon URL.</param>
        /// <param name="ipNumber">The ip number.</param>
        /// <param name="location">The location.</param>
        /// <param name="occupation">The occupation.</param>
        /// <param name="signature">The signature.</param>
        /// <param name="website">The website.</param>
        /// <param name="emailData">The email data.</param>
        /// <param name="autoSubscribeThreads">Default value when user creates new threads.</param>
        /// <param name="defaultMessagesPerPage">Messages per page to display</param>
        /// <returns>
        /// UserID of new user or 0 if registration failed.
        /// </returns>
        public static async Task <int> RegisterNewUserAsync(string nickName, DateTime?dateOfBirth, string emailAddress, bool emailAddressIsPublic, string iconUrl,
                                                            string ipNumber, string location, string occupation, string signature, string website,
                                                            Dictionary <string, string> emailData, bool autoSubscribeThreads, short defaultMessagesPerPage)
        {
            var newUser = new UserEntity
            {
                AmountOfPostings     = 0,
                DateOfBirth          = dateOfBirth,
                EmailAddress         = emailAddress,
                EmailAddressIsPublic = emailAddressIsPublic,
                IPNumber             = ipNumber,
                IconURL    = iconUrl,
                IsBanned   = false,
                JoinDate   = DateTime.Now,
                Location   = location,
                NickName   = nickName,
                Occupation = occupation,
                Signature  = signature,
                Website    = website
            };

            var password = HnDGeneralUtils.GenerateRandomPassword();

            newUser.Password = HnDGeneralUtils.HashPassword(password, performPreMD5Hashing: true);

            //Preferences
            newUser.AutoSubscribeToThread          = autoSubscribeThreads;
            newUser.DefaultNumberOfMessagesPerPage = defaultMessagesPerPage;

            //Fetch the SystemDataEntity to use the "DefaultUserTitleNewUser" as the user title & the "DefaultRoleNewUser" as the roleID of the newly
            //created RoleUserEntity.
            var systemData = await SystemGuiHelper.GetSystemSettingsAsync();

            newUser.UserTitleID = systemData.DefaultUserTitleNewUser;
            newUser.RoleUser.Add(new RoleUserEntity {
                RoleID = systemData.DefaultRoleNewUser
            });

            // first encode fields which could lead to cross-site-scripting attacks
            EncodeUserTextFields(newUser);

            // now save the new user entity and the new RoleUser entity recursively in one go.
            using (var adapter = new DataAccessAdapter())
            {
                if (await adapter.SaveEntityAsync(newUser).ConfigureAwait(false))
                {
                    // all ok, Email the password
                    await HnDGeneralUtils.EmailPassword(password, emailAddress, emailData);
                }
            }

            return(newUser.UserID);
        }
Exemplo n.º 20
0
        protected void btnYes_Click(object sender, EventArgs e)
        {
            bool newBanFlagValue = false;
            bool result          = UserManager.ToggleBanFlagValue(HnDGeneralUtils.TryConvertToInt(lblUserID.Text), out newBanFlagValue);

            phToggleResult.Visible = result;
            phUserInfo.Visible     = !result;
            if (newBanFlagValue)
            {
                // add the user to be logged out by force.
                ApplicationAdapter.AddUserToListToBeLoggedOutByForce(lblNickname.Text);
            }
        }
        private void Page_Load(object sender, System.EventArgs e)
        {
            // If the user doesn't have any access rights to management stuff, the user should
            // be redirected to the default of the global system.
            if (!SessionAdapter.HasSystemActionRights())
            {
                // doesn't have system rights. redirect.
                Response.Redirect("../Default.aspx", true);
            }

            // Check if the user has the right systemright
            if (!SessionAdapter.HasSystemActionRight(ActionRights.SecurityManagement))
            {
                // no, redirect to admin default page, since the user HAS access to the admin menu.
                Response.Redirect("Default.aspx", true);
            }

            _roleID = 0;

            if (!Page.IsPostBack)
            {
                // Get all roles
                RoleCollection roles = SecurityGuiHelper.GetAllRoles();

                cbxRoles.DataSource     = roles;
                cbxRoles.DataTextField  = "RoleDescription";
                cbxRoles.DataValueField = "RoleID";
                cbxRoles.DataBind();

                if (cbxRoles.Items.Count > 0)
                {
                    cbxRoles.Items[0].Selected = true;
                    _roleID = HnDGeneralUtils.TryConvertToInt(cbxRoles.SelectedItem.Value);
                }

                // get the audit actions
                AuditActionCollection auditActions = SecurityGuiHelper.GetAllAuditActions();

                cblAuditActions.DataSource     = auditActions;
                cblAuditActions.DataTextField  = "AuditActionDescription";
                cblAuditActions.DataValueField = "AuditActionID";
                cblAuditActions.DataBind();

                // Reflect action rights for current selected forum for this role
                ReflectCurrentAuditActions();
            }
            else
            {
                _roleID = HnDGeneralUtils.TryConvertToInt(cbxRoles.SelectedItem.Value);
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Page_Load(object sender, System.EventArgs e)
        {
            int currentPage = HnDGeneralUtils.TryConvertToInt(Request["Page"]);

            if (currentPage == 0)
            {
                currentPage = 1;
            }

            if (!Page.IsPostBack)
            {
                plPageListTop.CurrentPage    = currentPage;
                plPageListBottom.CurrentPage = currentPage;

                DataTable results = SessionAdapter.GetSearchResults();
                if (results == null)
                {
                    // no results, redirect to search page
                    Response.Redirect("Search.aspx");
                }

                short pageSize = CacheManager.GetSystemData().PageSizeSearchResults;
                if (pageSize <= 0)
                {
                    pageSize = 50;
                }

                int amountPages = (results.Rows.Count / pageSize);
                if ((amountPages * pageSize) < results.Rows.Count)
                {
                    amountPages++;
                }
                plPageListBottom.AmountPages = amountPages;
                plPageListTop.AmountPages    = amountPages;

                // get the page of the resultset to bind. We page in-memory, so we have to execute the search query just once.
                DataTable toBind = results.Clone();
                for (int i = 0;
                     (i < pageSize) && ((((currentPage - 1) * pageSize) + i) < results.Rows.Count);
                     i++)
                {
                    toBind.ImportRow(results.Rows[((currentPage - 1) * pageSize) + i]);
                }

                rptResults.DataSource = toBind;
                rptResults.DataBind();

                lblAmountThreads.Text = results.Rows.Count.ToString();
                lblSearchTerms.Text   = HttpUtility.HtmlEncode(SessionAdapter.GetSearchTerms());
            }
        }
Exemplo n.º 23
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            int threadID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["ThreadID"]);

            _thread = ThreadGuiHelper.GetThread(threadID);
            if (_thread == null)
            {
                // not found, return to default page
                Response.Redirect("default.aspx", true);
            }

            // Check credentials
            bool userHasAccess = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AccessForum);

            if (!userHasAccess)
            {
                // doesn't have access to this forum. redirect
                Response.Redirect("default.aspx");
            }

            bool userMayDeleteThread = SessionAdapter.HasSystemActionRight(ActionRights.SystemWideThreadManagement);

            if (!userMayDeleteThread)
            {
                // doesn't have the right to delete a thread. redirect
                Response.Redirect("Messages.aspx?ThreadID=" + threadID, true);
            }

            // check if the user can view this thread. If not, don't continue.
            if ((_thread.StartedByUserID != SessionAdapter.GetUserID()) &&
                !SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.ViewNormalThreadsStartedByOthers) &&
                !_thread.IsSticky)
            {
                // can't view this thread, it isn't visible to the user
                Response.Redirect("default.aspx", true);
            }

            if (!Page.IsPostBack)
            {
                // fill the page's content
                ForumEntity forum = CacheManager.GetForum(_thread.ForumID);
                if (forum == null)
                {
                    // Orphaned thread
                    Response.Redirect("default.aspx", true);
                }
                lblForumName.Text     = forum.ForumName;
                lblThreadSubject.Text = HttpUtility.HtmlEncode(_thread.Subject);
            }
        }
Exemplo n.º 24
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            int forumID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["ForumID"]);

            _forum = CacheManager.GetForum(forumID);
            if (_forum == null)
            {
                // not found
                Response.Redirect("default.aspx", true);
            }

            bool userHasAccess = SessionAdapter.CanPerformForumActionRight(forumID, ActionRights.AccessForum);

            if (!userHasAccess)
            {
                // doesn't have access to this forum. redirect
                Response.Redirect("default.aspx", true);
            }

            _userCanCreateNormalThreads = SessionAdapter.CanPerformForumActionRight(forumID, ActionRights.AddNormalThread);
            _userCanCreateStickyThreads = SessionAdapter.CanPerformForumActionRight(forumID, ActionRights.AddStickyThread);

            if (!(_userCanCreateNormalThreads || _userCanCreateStickyThreads))
            {
                // doesn't have the right to add new threads to this forum. redirect
                Response.Redirect("default.aspx", true);
            }

            meMessageEditor.ShowAddAttachment = ((_forum.MaxNoOfAttachmentsPerMessage > 0) &&
                                                 SessionAdapter.CanPerformForumActionRight(forumID, ActionRights.AddAttachment));

            if (!String.IsNullOrEmpty(_forum.NewThreadWelcomeTextAsHTML))
            {
                phWelcomeText.Visible = true;
                litWelcomeText.Text   = _forum.NewThreadWelcomeTextAsHTML;
            }

            if (!Page.IsPostBack)
            {
                // fill the page's content
                lnkThreads.Text                  = HttpUtility.HtmlEncode(_forum.ForumName);
                lnkThreads.NavigateUrl          += "?ForumID=" + forumID;
                meMessageEditor.ForumName        = _forum.ForumName;
                meMessageEditor.ForumDescription = HttpUtility.HtmlEncode(_forum.ForumDescription);
                meMessageEditor.CanBeSticky      = _userCanCreateStickyThreads;
                meMessageEditor.CanBeNormal      = _userCanCreateNormalThreads;
                meMessageEditor.IsThreadStart    = true;
                lblSectionName.Text              = CacheManager.GetSectionName(_forum.SectionID);
            }
        }
Exemplo n.º 25
0
        private void btnSave_ServerClick(object sender, System.EventArgs e)
        {
            // store the new settings in the database, refresh Application Object's cache when succeeded.
            int ID = (int)ViewState["ID"];

            short activeThreadsThreshold = HnDGeneralUtils.TryConvertToShort(tbxActiveThreadsThreshold.Text);

            if (activeThreadsThreshold <= 0)
            {
                activeThreadsThreshold = 48;
            }

            short pageSizeSearchResults = HnDGeneralUtils.TryConvertToShort(tbxPageSizeInSearchResults.Text);

            if (pageSizeSearchResults <= 0)
            {
                pageSizeSearchResults = 50;
            }

            short minNumberOfThreadsToFetch = HnDGeneralUtils.TryConvertToShort(tbxMinNumberOfThreadsToFetch.Text);

            if (minNumberOfThreadsToFetch <= 0)
            {
                minNumberOfThreadsToFetch = 25;
            }

            short minNumberOfNonStickyVisibleThreads = HnDGeneralUtils.TryConvertToShort(tbxMinNumberOfNonStickyVisibleThreads.Text);

            if (minNumberOfNonStickyVisibleThreads <= 0)
            {
                minNumberOfNonStickyVisibleThreads = 5;
            }

            bool result = SystemManager.StoreNewSystemSettings(ID,
                                                               Convert.ToInt32(cbxDefaultRoleNewUsers.SelectedItem.Value),
                                                               Convert.ToInt32(cbxAnonymousUserRole.SelectedItem.Value),
                                                               Convert.ToInt32(cbxDefaultUserTitleNewUsers.SelectedItem.Value), activeThreadsThreshold, pageSizeSearchResults,
                                                               minNumberOfThreadsToFetch, minNumberOfNonStickyVisibleThreads, chkSendReplyNotifications.Checked);

            if (result)
            {
                // invalidate cache
                CacheManager.InvalidateCachedItem(CacheKeys.SystemData);
            }

            // ignore result for now
            Response.Redirect("Default.aspx", true);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Initializes the system, by running a stored procedure passing in the new admin password.
        /// </summary>
        /// <param name="newAdminPassword"></param>
        /// <param name="emailAddress"></param>
        /// <returns></returns>
        public static async Task Initialize(string newAdminPassword, string emailAddress)
        {
            if (string.IsNullOrWhiteSpace(newAdminPassword))
            {
                return;
            }

            var passwordHashed = HnDGeneralUtils.HashPassword(newAdminPassword, performPreMD5Hashing: true);

            using (var adapter = new DataAccessAdapter())
            {
                await ActionProcedures.InstallAsync(emailAddress, passwordHashed, adapter, CancellationToken.None);

                CacheController.PurgeResultsets(CacheKeys.AnonymousUserQueryResultset);
            }
        }
Exemplo n.º 27
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            // If the user doesn't have any access rights to management stuff, the user should
            // be redirected to the default of the global system.
            if (!SessionAdapter.HasSystemActionRights())
            {
                // doesn't have system rights. redirect.
                Response.Redirect("../Default.aspx", true);
            }

            // Check if the user has the right systemright
            if (!SessionAdapter.HasSystemActionRight(ActionRights.SystemManagement))
            {
                // no, redirect to admin default page, since the user HAS access to the admin menu.
                Response.Redirect("Default.aspx", true);
            }

            _sectionID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["SectionID"]);

            if (!Page.IsPostBack)
            {
                // Get the section directly from the DB, instead from the in-memory cache
                SectionEntity section = SectionGuiHelper.GetSection(_sectionID);

                // Show results in the labels
                if (section != null)
                {
                    // Section found
                    // Get the forums in the section
                    ForumCollection forums = ForumGuiHelper.GetAllForumsInSection(_sectionID);
                    if (forums.Count > 0)
                    {
                        // section has forums. User is not able to delete the section. Show error message plus
                        // disable delete button
                        lblRuleError.Visible = true;
                        btnDelete.Disabled   = true;
                    }
                    lblSectionName.Text        = section.SectionName;
                    lblSectionDescription.Text = section.SectionDescription;
                }
                else
                {
                    // the section doesn't exist anymore
                    Response.Redirect("ModifyDeleteSection.aspx", true);
                }
            }
        }
Exemplo n.º 28
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            // If the user doesn't have any access rights to management stuff, the user should
            // be redirected to the default of the global system.
            if (!SessionAdapter.HasSystemActionRights())
            {
                // doesn't have system rights. redirect.
                Response.Redirect("../Default.aspx", true);
            }

            // Check if the user has the right systemright
            if (!SessionAdapter.HasSystemActionRight(ActionRights.SecurityManagement))
            {
                // no, redirect to admin default page, since the user HAS access to the admin menu.
                Response.Redirect("Default.aspx", true);
            }

            _roleID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["RoleID"]);

            if (!Page.IsPostBack)
            {
                // get the role and show the description
                RoleEntity role = SecurityGuiHelper.GetRole(_roleID);
                if (role != null)
                {
                    tbxRoleDescription.Text = role.RoleDescription;
                }

                // get the system rights
                ActionRightCollection systemActionRights = SecurityGuiHelper.GetAllSystemActionRights();

                cblSystemRights.DataSource     = systemActionRights;
                cblSystemRights.DataTextField  = "ActionRightDescription";
                cblSystemRights.DataValueField = "ActionRightID";
                cblSystemRights.DataBind();

                // get the action rights set for this role
                RoleSystemActionRightCollection systemActionRightRoleCombinations = SecurityGuiHelper.GetSystemActionRightRolesForRole(_roleID);

                // check the checkboxes in the cblSystemRights list if the value matches a row in the datatable
                foreach (RoleSystemActionRightEntity currentEntity in systemActionRightRoleCombinations)
                {
                    cblSystemRights.Items.FindByValue(currentEntity.ActionRightID.ToString()).Selected = true;
                }
            }
        }
Exemplo n.º 29
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            // If the user doesn't have any access rights to management stuff, the user should
            // be redirected to the default of the global system.
            if (!SessionAdapter.HasSystemActionRights())
            {
                // doesn't have system rights. redirect.
                Response.Redirect("../Default.aspx", true);
            }

            // Check if the user has the right systemright;
            if (!SessionAdapter.HasSystemActionRight(ActionRights.SystemManagement))
            {
                // no, redirect to admin default page, since the user HAS access to the admin menu.
                Response.Redirect("Default.aspx", true);
            }

            _forumID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["ForumID"]);

            if (!Page.IsPostBack)
            {
                // Get the forum
                try
                {
                    ForumEntity forum = ForumGuiHelper.GetForum(_forumID);

                    // Show results in the labels
                    if (forum != null)
                    {
                        // the forum exists
                        lblForumName.Text        = forum.ForumName;
                        lblForumDescription.Text = forum.ForumDescription;
                    }
                    else
                    {
                        // the forum doesn't exist anymore
                        Response.Redirect("ModifyDeleteForum.aspx", true);
                    }
                }
                catch (Exception ex)
                {
                    // Bubble
                    throw ex;
                }
            }
        }
Exemplo n.º 30
0
        public async Task <ActionResult> Add([Bind(nameof(MessageData.MessageText), nameof(MessageData.Subscribe))]
                                             MessageData messageData, string submitButton,
                                             int threadId = 0)
        {
            if (submitButton != "Post")
            {
                return(threadId <= 0 ? RedirectToAction("Index", "Home") : RedirectToAction("Index", "Thread", new { threadId = threadId }));
            }

            if (!ModelState.IsValid)
            {
                return(RedirectToAction("Index", "Home"));
            }

            var(userMayAddMessages, thread) = await PerformAddMessageSecurityChecksAsync(threadId);

            if (!userMayAddMessages)
            {
                return(RedirectToAction("Index", "Home"));
            }

            int newMessageId = 0;

            if (submitButton == "Post")
            {
                // allowed, proceed
                // parse message text to html
                var messageAsHtml = HnDGeneralUtils.TransformMarkdownToHtml(messageData.MessageText, ApplicationAdapter.GetEmojiFilenamesPerName(),
                                                                            ApplicationAdapter.GetSmileyMappings());
                var systemData = await _cache.GetSystemDataAsync();

                var remoteIPAddress = HnDGeneralUtils.GetRemoteIPAddressAsIP4String(this.HttpContext.Connection.RemoteIpAddress);
                newMessageId = await ThreadManager.CreateNewMessageInThreadAsync(threadId, this.HttpContext.Session.GetUserID(), messageData.MessageText, messageAsHtml,
                                                                                 remoteIPAddress, messageData.Subscribe,
                                                                                 ApplicationAdapter.GetEmailData(this.Request.Host.Host, EmailTemplate.ThreadUpdatedNotification),
                                                                                 systemData.SendReplyNotifications);

                ApplicationAdapter.InvalidateCachedNumberOfThreadsInSupportQueues();
                if (this.HttpContext.Session.CheckIfNeedsAuditing(AuditActions.AuditNewMessage))
                {
                    await SecurityManager.AuditNewMessageAsync(this.HttpContext.Session.GetUserID(), newMessageId);
                }
            }

            return(await CalculateRedirectToMessageAsync(thread.ThreadID, newMessageId));
        }