Exemplo n.º 1
0
        public static void AuthenticateUser(ForumRespository db, int UserID)
        {
            string SessionID = Guid.NewGuid().ToString();

            HttpCookie SessionCookie = new HttpCookie("MvcForum", SessionID);
            SessionCookie.HttpOnly = true;
            SessionCookie.Expires = DateTime.Now.AddYears(50);
            HttpContext.Current.Response.Cookies.Add(SessionCookie);
            var SessionStore = new Forum_Session() { UserID = UserID, SessionGUID = SessionID };
            db.AddSessionToDB(SessionStore);
            db.Save();
        }
Exemplo n.º 2
0
        public ActionResult DeletePost(int id, int page, string confirmbutton)
        {
            using (ForumRespository db = new ForumRespository())
            {
                Forum_Post ToDelete = db.GetPostByID(id);

                var model = new MasterViewModel();
                model.AddNavigation(ToDelete.Forum_Thread);
                model.AddNavigation("Delete Post");

                if (ToDelete == null)
                    return NotFoundView("Post");
                if (ToDelete.Forum_Thread.Forum_Posts[0] == ToDelete)
                    return RedirectToAction("ViewThread", new { id = ToDelete.ThreadID });

                if (ToDelete.Forum_Thread.Locked)
                    return AuthenticationHelper.AccessDeniedView(model);

                var Category = ToDelete.Forum_Thread.Forum_Category;

                var Deleter = GetCurrentUser(db);

                if (!db.CheckCategoryPermissions(Category, Deleter, P => (P.AllowDeleteOwnPost && ToDelete.PosterID == Deleter.UserID && ToDelete.PosterID != (int)BuildInUser.Guest) || P.AllowDeleteAllPosts))
                    return AuthenticationHelper.AccessDeniedView(model);

                if (IsHttpPost)
                {
                    if (!AntiForgeryTokenValid)
                    {
                        ModelState.AddModelError("AntiForgery", "The antiforgery token was invalid.");
                    }
                    else
                    {
                        int ThreadID = ToDelete.ThreadID;
                        db.DeletePost(ToDelete);
                        db.Save();
                        return RedirectToAction("ViewThread", new { id = ThreadID, page = page });
                    }
                }

                return View(model);
            }
        }
Exemplo n.º 3
0
 public static void AuthenticateRequest()
 {
     var Context = HttpContext.Current;
     var Cookie = Context.Request.Cookies["MvcForum"];
     if (Cookie != null)
     {
         using (ForumRespository db = new ForumRespository())
         {
             var Session = db.GetSession(Cookie.Value);
             if (Session != null)
             {
                 var ForumUser = Session.Forum_User;
                 bool Admin = db.UserInRole(ForumUser, BuildInRole.Administrator);
                 Context.User = new ForumPrinciple(ForumUser.Username, ForumUser.UserID, Admin, Session.SessionGUID);
                 return;
             }
         }
     }
     Context.User = new ForumPrinciple();
 }
Exemplo n.º 4
0
        public ActionResult LogOn(LogonViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    using (ForumRespository db = new ForumRespository())
                    {
                        Forum_User ForumUser = db.GetUser(model.UserName);

                        Authentication.AuthenticateUser(db, ForumUser.UserID);

                        return Redirect(Request.UrlReferrer.ToString());
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }
            model.AddNavigation("Log on");
            return View(model);
        }
Exemplo n.º 5
0
 public ActionResult Register(RegisterViewModel model)
 {
     if (ModelState.IsValid)
     {
         // Attempt to register the user
         MembershipCreateStatus createStatus;
         Membership.CreateUser(model.Reg_Username, model.Reg_Password, model.Reg_Email, null, null, true, null, out createStatus);
         if (createStatus == MembershipCreateStatus.Success)
         {
             using (ForumRespository db = new ForumRespository())
             {
                 Authentication.AuthenticateUser(db, db.GetUser(model.Reg_Username).UserID);
                 return Redirect("/");
             }
         }
         else
         {
             ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
         }
     }
     model.AddNavigation("Register");
     return View(model);
 }
Exemplo n.º 6
0
        public ActionResult Category(int id, string NewCategory, string UpdateCategory, string MoveCategory)
        {
            var model = new AdminCategoryModel();
            model.AddNavigation("Admin Panel", "Overview", "Admin", null);
            model.AddNavigation("Edit Category");
            using (ForumRespository db = new ForumRespository())
            {
                Forum_User CurrentUser = GetCurrentUser(db);

                if (!UserIdentity.IsAdmin)
                    return AuthenticationHelper.AccessDeniedView(model); // Administrating the forum requires the user to be an Admin.

                HandlePermissionsLinkUpdates();

                Forum_Category Root = db.GetCategoryByID((int)BuildInCategory.Root);

                Forum_Category CurrentCategory = id != 0 ? db.GetCategoryByID(id) : Root;

                if (CurrentCategory == null)
                    return NotFoundView("Category");

                bool IsRoot = Root == CurrentCategory;

                if (IsHttpPost && AntiForgeryTokenValid)
                {
                    if (!String.IsNullOrEmpty(NewCategory))
                    {
                        Forum_Category NewForumCategory = new Forum_Category();
                        NewForumCategory.ParentID = CurrentCategory.CategoryID;
                        NewForumCategory.Name = "Untitled Category";
                        NewForumCategory.InheritPermissions = true;
                        NewForumCategory.AllowPosts = false;
                        db.AddCategory(NewForumCategory);
                        db.Save();
                        return RedirectToAction("Category", new { id = NewForumCategory.CategoryID });
                    }
                    if (!String.IsNullOrEmpty(UpdateCategory) && CurrentCategory != Root)
                    {
                        var Form = Request.Form;
                        string NewName = Form["CurrentCategory.Name"];
                        bool InheritPermissions = !String.IsNullOrEmpty(Form["Inherit Permissions"]);
                        bool AllowPosts = !String.IsNullOrEmpty(Form["Allow Posts"]);
                        CurrentCategory.AllowPosts = AllowPosts;
                        CurrentCategory.InheritPermissions = InheritPermissions;
                        try
                        {
                            CurrentCategory.Priority = Convert.ToInt32(Form["CurrentCategory.Priority"]);
                        } catch { }
                        if (!String.IsNullOrWhiteSpace(NewName))
                            CurrentCategory.Name = NewName.Trim();

                        db.Save();
                    }
                    if (!String.IsNullOrEmpty(MoveCategory) && CurrentCategory != Root)
                    {
                        var Form = Request.Form;
                        int DestinationID = 0;
                        try
                        {
                            DestinationID = Convert.ToInt32(Form["MoveToDestination"]);
                        }
                        catch
                        {}

                        var Parent = db.GetCategoryByID(DestinationID);
                        if (Parent != null)
                        {
                            while (Parent != null)
                            {
                                if (Parent == CurrentCategory)
                                    break;
                                Parent = Parent.Category1;
                            }
                            if (Parent == null)
                            {
                                CurrentCategory.ParentID = DestinationID;
                                db.Save();
                            }
                        }
                    }
                }

                foreach (var Category in db.GetAllCategories())
                {
                    var Parent = Category;
                    while (Parent != null)
                    {
                        if (Parent == CurrentCategory) break;
                        Parent = Parent.Category1;
                    }
                    if (Parent != null) continue;
                    if (Category == CurrentCategory.Category1) continue;

                    model.MoveCategoryToOptions.Add(new AdminNamedID() { Name = Category.Name, ID = Category.CategoryID });
                }

                model.Root = RecursivelyFillCategoryTree(db, Root, model, CurrentCategory.CategoryID);

                model.UserGroups = db.GetAllRoles().Where(R => R.RoleID != (int)BuildInRole.Administrator).ToClassList(R => new AdminNamedID() { ID = R.RoleID, Name = R.Name });
                model.PermissionSets = db.GetAllPermissionSets().ToClassList(P => new AdminNamedID() { ID = P.PermissionID, Name = P.Name });
                model.Fixed = AdminPermissionLinkEditors.FixedSet.Categories;

                model.FixedNamedID = new AdminNamedID() { ID = model.CurrentCategory.id, Name = model.CurrentCategory.Name };
                model.PermissionLinkList = db.GetPermissionLinks(CurrentCategory).OrderBy(L => L.CategoryID).ToClassList(L => new AdminPermissionLink()
                {
                    Category = new AdminNamedID() { ID = L.CategoryID, Name = db.GetCategoryByID(L.CategoryID).Name },
                    UserGroup = new AdminNamedID() { ID = L.RoleID, Name = db.GetRole(L.RoleID).Name },
                    PermissionSet = new AdminNamedID() { ID = L.PermissionID, Name = db.GetPermissionSetByID(L.PermissionID).Name },
                });

                return View(model);
            }
        }
Exemplo n.º 7
0
        public ActionResult Overview(int page)
        {
            var model = new AdminOverviewModel();
            model.AddNavigation("Admin Panel");
            using (ForumRespository db = new ForumRespository())
            {
                Forum_User CurrentUser = GetCurrentUser(db);

                if (!UserIdentity.IsAdmin)
                    return AuthenticationHelper.AccessDeniedView(model); // Administrating the forum requires the user to be an Admin.

                model.page = page;

                var Users = db.GetAllUsers().OrderBy(U => U.Username);
                model.LastPage = (Users.Count() - 1) / UsersPerPage + 1;
                model.Users = Users.Skip((page - 1) * UsersPerPage).Take(UsersPerPage).ToClassList(U => new AdminNamedID() { ID = U.UserID, Name = U.Username });
                model.UserGroups = db.GetAllRoles().ToClassList(R => new AdminNamedID() { ID = R.RoleID, Name = R.Name });
                model.PermissionSets = db.GetAllPermissionSets().ToClassList(P => new AdminNamedID() { ID = P.PermissionID, Name = P.Name });
                model.RootCategory = RecursivelyFillCategoryTree(db, db.GetCategoryByID((int)BuildInCategory.Root));

                return View(model);
            }
        }
Exemplo n.º 8
0
        public ActionResult DeleteCategory(int id, int? MovePostsDestination, string MovePostOption, int? MoveChildrenDestination)
        {
            var model = new AdminDeleteCategoryViewModel();
            model.AddNavigation("Admin Panel", "Overview", "Admin", null);
            model.AddNavigation("Delete Category");
            using (ForumRespository db = new ForumRespository())
            {
                Forum_User CurrentUser = GetCurrentUser(db);

                if (!UserIdentity.IsAdmin)
                    return AuthenticationHelper.AccessDeniedView(model); // Administrating the forum requires the user to be an Admin.

                Forum_Category CurrentCategory = db.GetCategoryByID(id);

                if (CurrentCategory == null)
                    return NotFoundView("Category");

                if (CurrentCategory.CategoryID == (int)BuildInCategory.Root)
                    return RedirectToAction("Overview");

                if (IsHttpPost && AntiForgeryTokenValid)
                {
                    db.DeleteCategory(CurrentCategory);

                    if (CurrentCategory.AllowPosts)
                    {
                        bool DeletePosts = String.Equals(MovePostOption, "Delete", StringComparison.Ordinal);
                        if (!DeletePosts && MovePostsDestination == null)
                            return RedirectToAction("Overview");

                        if (!DeletePosts)
                        {
                            foreach (var Thread in CurrentCategory.Forum_Threads)
                            {
                                Thread.CategoryID = (int)MovePostsDestination;
                            }
                        }
                        else
                        {
                            db.DeleteThreads(CurrentCategory.Forum_Threads);
                        }
                    }

                    if (CurrentCategory.Forum_Categories.Count > 0)
                    {
                        var NewParent = db.GetCategoryByID((int)MoveChildrenDestination);

                        if (NewParent == null)
                            return RedirectToAction("Overview");

                        foreach (var Child in CurrentCategory.Forum_Categories)
                        {
                            Child.ParentID = NewParent.CategoryID;
                        }
                    }

                    db.Save();
                    return RedirectToAction("Category");
                }

                model.ThreadCount = CurrentCategory.Forum_Threads.Count;
                model.HasChildCategories = CurrentCategory.Forum_Categories.Count > 0;
                model.CategoryName = CurrentCategory.Name;

                foreach (var Category in db.GetAllCategories())
                {
                    if (Category.CategoryID != (int)BuildInCategory.Root & Category.CategoryID != CurrentCategory.CategoryID)
                        model.MovePostsToOptions.Add(new AdminNamedID() { Name = Category.Name, ID = Category.CategoryID });
                    var Parent = Category;
                    while (Parent != null)
                    {
                        if (Parent == CurrentCategory) break;
                        Parent = Parent.Category1;
                    }
                    if (Parent != null) continue;

                    model.MoveChildrenToOptions.Add(new AdminNamedID() { Name = Category.Name, ID = Category.CategoryID });
                }

                return View(model);
            }
        }
Exemplo n.º 9
0
 protected Forum_User GetCurrentUser(ForumRespository db)
 {
     return db.GetUser(User.Identity.Name);
 }
Exemplo n.º 10
0
        public ActionResult MyPosts(int Page)
        {
            using (ForumRespository db = new ForumRespository())
            {

                var Model = new MyPostsViewModel();
                Model.AddNavigation("My Posts");

                if (!Request.IsAuthenticated)
                    return AuthenticationHelper.AccessDeniedView(Model); // Regardless of permissions, requires an account by neccecity

                Forum_User CurrentUser = GetCurrentUser(db);

                var Threads = db.GetSortedThreads(CurrentUser);

                Model.PageCount = (Threads.Count() - 1) / THREADS_PER_PAGE + 1;
                Model.Page = Page;

                ThreadInfoModelFromThread(db, CurrentUser, Threads.Skip(THREADS_PER_PAGE * (Page - 1)).Take(THREADS_PER_PAGE), Model.ThreadInfoList);

                return View(Model);
            }
        }
Exemplo n.º 11
0
        AdminCategory RecursivelyFillCategoryTree(ForumRespository db, Forum_Category ToFill, AdminCategoryModel model = null, int ID = 0)
        {
            AdminCategory newCategory = new AdminCategory()
            {
                AllowPosts = ToFill.AllowPosts,
                id = ToFill.CategoryID,
                InheritPermissions = ToFill.InheritPermissions,
                Name = ToFill.Name,
                Priority = ToFill.Priority
            };

            if (newCategory.id == ID)
                model.CurrentCategory = newCategory;

            var SortedCategories = db.GetSortedCategories(ToFill.CategoryID);

            if (!ToFill.AllowPosts)
                SortedCategories = SortedCategories.OrderByDescending(C => C.AllowPosts);

            foreach (var Child in SortedCategories)
                newCategory.Children.Add(RecursivelyFillCategoryTree(db, Child, model, ID));

            return newCategory;
        }
Exemplo n.º 12
0
        public ActionResult UserGroup(int id, int page, string UsersAddButton, string UsersRemoveButton, string NewGroup, string UpdateGroup, string DeleteGroup)
        {
            var model = new AdminUserGroupModel(){page = page};
            model.AddNavigation("Admin Panel", "Overview", "Admin", null);
            model.AddNavigation("Edit User Groups");
            using (ForumRespository db = new ForumRespository())
            {
                Forum_User CurrentUser = GetCurrentUser(db);

                if (!UserIdentity.IsAdmin)
                    return AuthenticationHelper.AccessDeniedView(model); // Administrating the forum requires the user to be an Admin.

                HandlePermissionsLinkUpdates();

                Forum_Role CurrentRole;

                if (id != 0)
                    CurrentRole = db.GetRole(id);
                else
                    CurrentRole = db.GetAllRoles().First();

                if (CurrentRole == null)
                    return NotFoundView("User Group");

                model.id = CurrentRole.RoleID;
                model.CanBeDeleted = CurrentRole.CanBeDeleted;
                model.HasMembers = CurrentRole.RoleID != (int)BuildInRole.Everyone &&
                                   CurrentRole.RoleID != (int)BuildInRole.RegisteredUser;
                model.HasPermissions = CurrentRole.RoleID != (int)BuildInRole.Administrator;

                if (IsHttpPost && AntiForgeryTokenValid)
                {
                    if (!String.IsNullOrEmpty(UsersAddButton) && model.HasMembers)
                    {
                        int nID;
                        Forum_User ToAdd;
                        foreach (var ID in Request.Form.GetValues("Users"))
                        {
                            try
                            {
                                nID = Convert.ToInt32(ID);
                            }
                            catch
                            {
                                continue;
                            }
                            if (nID == (int)BuildInUser.Guest) continue;
                            ToAdd = db.GetUserByID(nID);
                            if (ToAdd == null) continue;
                            if (db.UserInRole(ToAdd, CurrentRole)) continue;
                            db.AddUserRoleLink(CurrentRole, ToAdd);
                        }
                        db.Save();
                    }
                    else if (!String.IsNullOrEmpty(UsersRemoveButton))
                    {
                        int nID;
                        var RemovedUsers = Request.Form.GetValues("Users");
                        if (RemovedUsers != null)
                        {
                            foreach (var ID in RemovedUsers)
                            {
                                try
                                {
                                    nID = Convert.ToInt32(ID);
                                }
                                catch
                                {
                                    continue;
                                }
                                if (CurrentRole.RoleID == (int)BuildInRole.Administrator && nID == CurrentUser.UserID) continue;
                                db.RemoveUserFromRole(db.GetUserByID(nID), CurrentRole);
                            }
                            db.Save();
                        }
                    }
                    else if (!String.IsNullOrEmpty(UpdateGroup) && model.HasPermissions)
                    {
                        if (model.CanBeDeleted)
                            CurrentRole.Name = Request.Form["Name"];
                        CurrentRole.AllowSearch = Request.Form["IsAllowedSearch"] != "false";
                        db.Save();
                    }
                    else if (!String.IsNullOrEmpty(NewGroup))
                    {
                        var NewRole = new Forum_Role();
                        NewRole.Name = "Unnamed";
                        NewRole.CanBeDeleted = true;
                        db.AddRole(NewRole);
                        db.Save();
                        return RedirectToAction("UserGroup", new { id = NewRole.RoleID });
                    }
                    else if (!String.IsNullOrEmpty(DeleteGroup) && model.CanBeDeleted && CurrentRole.Forum_UserRoleLinks.Count == 0)
                    {
                        db.DeleteRole(CurrentRole);
                        db.Save();
                        return RedirectToAction("UserGroup", new { id = 0 });
                    }
                }

                if (model.HasMembers)
                {
                    model.CurrentGroupUsers = db.GetUsersInRole(CurrentRole).ToClassList(U => new AdminNamedID(){ID = U.UserID, Name = U.Username});
                }

                model.UserGroups = db.GetAllRoles().ToClassList(R => new AdminNamedID() { ID = R.RoleID, Name = R.Name });
                model.Categories = db.GetAllCategories().ToClassList(C => new AdminNamedID() { ID = C.CategoryID, Name = C.Name });
                model.PermissionSets = db.GetAllPermissionSets().ToClassList(P => new AdminNamedID() { ID = P.PermissionID, Name = P.Name });
                model.Fixed = AdminPermissionLinkEditors.FixedSet.UserGroups;

                var Users = db.GetAllUsers().OrderBy(U => U.Username);
                model.LastPage = (Users.Count() - 1) / UsersPerPage + 1;

                model.AllUsers = Users.Skip((page - 1) * UsersPerPage).Take(UsersPerPage).ToClassList(U => new AdminNamedID() { ID = U.UserID, Name = U.Username });

                if (model.HasPermissions)
                {
                    model.FixedNamedID = new AdminNamedID() { ID = CurrentRole.RoleID, Name = CurrentRole.Name};
                    model.PermissionLinkList = db.GetPermissionLinks().Where(L => L.RoleID == id).OrderBy(L => L.CategoryID).ToClassList(L => new AdminPermissionLink()
                    {
                        Category = new AdminNamedID() { ID = L.CategoryID, Name = db.GetCategoryByID(L.CategoryID).Name },
                        PermissionSet = new AdminNamedID() { ID = L.PermissionID, Name = db.GetPermissionSetByID(L.PermissionID).Name },
                        UserGroup = model.FixedNamedID
                    });
                }

                model.Name = CurrentRole.Name;

                model.IsAllowedSearch = CurrentRole.AllowSearch;

                return View(model);
            }
        }
Exemplo n.º 13
0
        public ActionResult ViewThread(ThreadViewModel model)
        {
            using (ForumRespository db = new ForumRespository())
            {
                Forum_Thread Thread = db.GetThreadByID(model.Id);

                if (Thread == null)
                {
                    return NotFoundView("Thread");
                }

                if (model.Page < 1) return RedirectToAction("ViewThread", new { id = model.Id, page = 1}); // page less than 0 for existing thread equals redirect to valid page.

                model.AddNavigation(Thread);

                Forum_User ThreadViewUser = GetCurrentUser(db);

                if (!db.CheckCategoryPermissions(Thread.Forum_Category, ThreadViewUser, P => P.AllowView))
                    return AuthenticationHelper.AccessDeniedView(model);

                model.AllowEditThread = db.CheckCategoryPermissions(Thread.Forum_Category, ThreadViewUser, P => (P.AllowDeleteOwnThread && Thread.Forum_Posts[0].PosterID == ThreadViewUser.UserID && Thread.Forum_Posts[0].PosterID != (int)BuildInUser.Guest) || P.AllowDeleteAllThread || P.AllowMoveThread || P.AllowLockThread);
                model.Locked = Thread.Locked;
                model.ThreadTitle = Thread.Title;

                int UserID = 0;
                Forum_User U = GetCurrentUser(db);
                if (U != null)
                {
                    UserID = U.UserID;
                    db.SetLastPost(Thread, U, Math.Min(model.Page * POSTS_PER_PAGE, Thread.Posts));
                    db.Save();
                }

                model.LastPage = (Thread.Posts - 1) / POSTS_PER_PAGE + 1;
                if (model.Page > model.LastPage) return RedirectToAction("ViewThread", new { id = model.Id, page = model.LastPage }); // page greater than what exists equals redirect to last page.
                IEnumerable<Forum_Post> Posts = Thread.Forum_Posts.Skip((model.Page - 1)* POSTS_PER_PAGE).Take(POSTS_PER_PAGE);

                int PostNumber = 0;

                foreach (Forum_Post Post in Posts)
                {
                    PostViewModel PostModel = new PostViewModel();
                    PostModel.Locked = model.Locked;
                    PostModel.PostNumber = ++PostNumber;
                    PostModel.ThreadID = model.Id;
                    PostModel.PostText = PostParser.Parse(Post.PostText);
                    PostModel.PostTime = Post.TimeStamp;
                    PostModel.Poster = new UserViewModel();
                    PostModel.PostID = Post.PostID;
                    PostModel.Poster.Name = Post.Forum_User.Username;
                    PostModel.Poster.UserID = Post.PosterID;
                    PostModel.AllowDelete = (PostNumber > 1 || model.Page > 1) && db.CheckCategoryPermissions(Thread.Forum_Category, ThreadViewUser,
                        P => (P.AllowDeleteOwnPost && Post.PosterID == ThreadViewUser.UserID && Post.PosterID != (int)BuildInUser.Guest) || P.AllowDeleteAllPosts);
                    PostModel.AllowEdit = db.CheckCategoryPermissions(Thread.Forum_Category, ThreadViewUser, P => (P.AllowEditOwnPost && Post.PosterID == ThreadViewUser.UserID && Post.PosterID != (int)BuildInUser.Guest) || P.AllowEditAllPosts);
                    model.PostList.Add(PostModel);
                }
                return View(model);
            }
        }
Exemplo n.º 14
0
        public ActionResult ViewCategory(CategoryViewModel model)
        {
            using (ForumRespository db = new ForumRespository())
            {
                Forum_User CurrentUser = GetCurrentUser(db);
                Forum_Category Category =  db.GetCategoryByID(model.id);

                if (Category == null)
                    return NotFoundView("Category");

                if (model.id != (int)BuildInCategory.Root)
                {
                    model.AddNavigation(Category);
                    model.Name = Category.Name;
                }
                else
                {
                    model.IncludeIndex = false;
                    model.AddNavigation("Index");
                    model.Name = "Index";
                }

                if (!db.CheckCategoryPermissions(Category, CurrentUser, P => P.AllowView))
                    return AuthenticationHelper.AccessDeniedView(model);

                ViewCategory_RecursivelyFillSubcategories(db, CurrentUser, model.SubCategories, model.id, Category.AllowPosts ? 0 : 1);

                if (Category.AllowPosts)
                {
                    IQueryable<Forum_Thread> SortedThreads = db.GetSortedThreads(Category.CategoryID);
                    model.PageCount = (SortedThreads.Count() - 1) / THREADS_PER_PAGE + 1;

                    model.AllowPosts = true;
                    ThreadInfoModelFromThread(db, CurrentUser, SortedThreads.Skip(THREADS_PER_PAGE * (model.page - 1)).Take(THREADS_PER_PAGE), model.Threads);
                }

                return View(model);
            }
        }
Exemplo n.º 15
0
        public ActionResult Search(string Search)
        {
            using (ForumRespository db = new ForumRespository())
            {
                Forum_User CurrentUser = GetCurrentUser(db);

                var Model = new SearchResultsViewModel() { SearchString = Search };

                Model.AddNavigation("Search Results");

                if (!db.CheckRolePermissions(CurrentUser, R => R.AllowSearch))
                    return AuthenticationHelper.AccessDeniedView(Model);

                var Posts = db.GetMatchingPosts(Search);
                var Threads = db.GetMatchingThreads(Search);

                Model.ResultCount = Posts.Count() + Threads.Count();

                // Temp
                int I = 0;
                ThreadInfoModelFromThread(db, CurrentUser, Threads.Take(THREADS_PER_PAGE), Model.ThreadInfoList);
                foreach (var Post in Posts.Take(POSTS_PER_PAGE))
                {
                    Model.PostInfoList.Add(new PostWithThread()
                    {
                        ThreadName = Post.Forum_Thread.Title,
                        Post = new PostViewModel()
                            {
                                Locked = true,
                                PostID = Post.PostID,
                                PostNumber = ++I,
                                PostText = PostParser.Parse(Post.PostText),
                                PostTime = Post.TimeStamp,
                                ThreadID = Post.ThreadID,
                                Poster = new UserViewModel()
                                {
                                    Name = Post.Forum_User.Username,
                                    UserID = Post.Forum_User.UserID
                                }
                            }
                    });
                }

                return View("SearchResults", Model);
            }
        }
Exemplo n.º 16
0
        public ActionResult Reply(WritePostViewModel model, string button, int QuoteId = 0)
        {
            using (ForumRespository db = new ForumRespository())
            {
                Forum_Thread RepliedToThread = db.GetThreadByID(model.id);
                if (RepliedToThread == null) return NotFoundView("Thread");

                model.AddNavigation(RepliedToThread);
                model.AddNavigation("Reply to thread");

                Forum_User Replier = GetCurrentUser(db);

                if (!db.CheckCategoryPermissions(RepliedToThread.Forum_Category, Replier, P => P.AllowReply))
                    return AuthenticationHelper.AccessDeniedView(model);

                if (RepliedToThread.Locked)
                    return AuthenticationHelper.AccessDeniedView(model);

                if (IsHttpPost)
                {
                    if (String.Equals(button, "preview", StringComparison.InvariantCultureIgnoreCase))
                    {
                        model.ShowPost = true;
                        model.PostHtml = PostParser.Parse(model.PostText);
                        ModelState.Clear();
                    } else if (!AntiForgeryTokenValid)
                    {
                        ModelState.AddModelError("AntiForgery", "The antiforgery token was invalid.");
                    }
                    else if (ModelState.IsValid)
                    {
                        Forum_Post ReplyPost = new Forum_Post();
                        ReplyPost.TimeStamp = DateTime.Now;
                        ReplyPost.PosterID = Replier.UserID;
                        ReplyPost.PostText = model.PostText;
                        RepliedToThread.Forum_Posts.Add(ReplyPost);
                        RepliedToThread.LastPostTime = ReplyPost.TimeStamp;
                        RepliedToThread.Posts = RepliedToThread.Forum_Posts.Count;
                        // Save to database
                        db.Save();

                        int PostIndex = RepliedToThread.Forum_Posts.IndexOf(ReplyPost);
                        int NewPostPage = PostIndex / POSTS_PER_PAGE + 1;
                        int NewPostNumber = PostIndex % POSTS_PER_PAGE + 1;

                        return RedirectToAction("ViewThread", new { id = RepliedToThread.ThreadID, page = NewPostPage }).AddFragment(String.Format("Post_{0}", NewPostNumber));
                    }
                }
                else
                {
                    ModelState.Clear();
                    Forum_Post QuotedPost = db.GetPostByID(QuoteId);
                    if (QuotedPost != null)
                    {
                        model.PostText = String.Format("[quote={0}]{1}[/quote]", QuotedPost.Forum_User.Username, QuotedPost.PostText);
                    }
                }

                model.ThreadID = model.id;
                model.Title = "Reply to Thread";
                return View("WritePost", model);
            }
        }
Exemplo n.º 17
0
        public ActionResult RecentPosts()
        {
            using (ForumRespository db = new ForumRespository())
            {
                var Model = new RecentPostsViewModel();

                Model.AddNavigation("Recent Posts");

                Forum_User CurrentUser = GetCurrentUser(db);

                List<int> VisibleCategoryIDList = new List<int>();

                var Categories = db.GetAllCategories();

                foreach (var Category in Categories)
                {
                    if (db.CheckCategoryPermissions(Category, CurrentUser, P => P.AllowView))
                        VisibleCategoryIDList.Add(Category.CategoryID);
                }

                var Threads = db.GetSortedThreads().Where(T => VisibleCategoryIDList.Contains(T.CategoryID));

                ThreadInfoModelFromThread(db, CurrentUser, Threads.Take(THREADS_PER_PAGE), Model.ThreadInfoList);

                return View(Model);
            }
        }
Exemplo n.º 18
0
        public ActionResult NewThread(WritePostViewModel model, string button)
        {
            using (ForumRespository db = new ForumRespository())
            {
                Forum_Category Category = db.GetCategoryByID(model.id);
                if (Category == null) return NotFoundView("Category");

                model.AddNavigation(Category);
                model.AddNavigation("New thread");

                Forum_User Poster = GetCurrentUser(db);

                if (!db.CheckCategoryPermissions(Category, Poster, P => P.AllowNewThread))
                    return AuthenticationHelper.AccessDeniedView(model);

                if (String.Equals(button, "preview", StringComparison.InvariantCultureIgnoreCase))
                {
                    model.ShowPost = true;
                    model.PostHtml = PostParser.Parse(model.PostText);
                    ModelState.Clear();
                }
                else
                if (IsHttpPost)
                {
                    if (!AntiForgeryTokenValid)
                    {
                        ModelState.AddModelError("AntiForgery", "The antiforgery token was invalid.");
                    }
                    if (String.IsNullOrEmpty(model.ThreadTitle))
                    {
                        ModelState.AddModelError("ThreadTitle", "A thread title is required.");
                    }
                    if (ModelState.IsValid)
                    {
                        Forum_Thread NewThread = new Forum_Thread();
                        NewThread.Title = model.ThreadTitle;

                        NewThread.PosterID = Poster.UserID;

                        Forum_Post InitialPost = new Forum_Post();
                        InitialPost.TimeStamp = DateTime.Now;
                        InitialPost.PosterID = NewThread.PosterID;
                        InitialPost.PostText = model.PostText;
                        NewThread.Forum_Posts.Add(InitialPost);
                        NewThread.Posts = 1;
                        NewThread.LastPostTime = InitialPost.TimeStamp;
                        NewThread.CategoryID = model.id;
                        // Save and add thread to database
                        db.AddThread(NewThread);
                        db.SetLastPost(NewThread, Poster, 1);
                        db.Save();
                        return RedirectToAction("ViewCategory", new { id = model.id });
                    }
                }
                else
                {
                    ModelState.Clear();
                }
                model.EditTitle = true;
                model.Title = "Post new Thread";
                return View("WritePost", model);
            }
        }
Exemplo n.º 19
0
        public ActionResult PermissionSet(int id, string UpdatePermissions, string DeletePermissions, string NewPermissions)
        {
            var model = new AdminPermissionSetModel();
            model.AddNavigation("Admin Panel", "Overview", "Admin", null);
            model.AddNavigation("Edit Permission Set");
            using (ForumRespository db = new ForumRespository())
            {
                Forum_User CurrentUser = GetCurrentUser(db);

                if (!UserIdentity.IsAdmin)
                    return AuthenticationHelper.AccessDeniedView(model); // Administrating the forum requires the user to be an Admin.

                HandlePermissionsLinkUpdates();

                Forum_Permission CurrentPermissionSet;

                if (id == 0)
                    CurrentPermissionSet = db.GetAllPermissionSets().First();
                else
                    CurrentPermissionSet = db.GetPermissionSetByID(id);

                if (CurrentPermissionSet == null)
                    return NotFoundView("Permission Set");

                if (IsHttpPost && AntiForgeryTokenValid)
                {
                    if (!String.IsNullOrEmpty(UpdatePermissions))
                    {
                        UpdateModel(CurrentPermissionSet, "PermissionSet");
                        db.Save();
                    } else if (!String.IsNullOrEmpty(DeletePermissions) && CurrentPermissionSet.Forum_PermissionsLinks.Count == 0 && db.GetAllPermissionSets().Count() > 1)
                    {
                        db.DeletePermission(CurrentPermissionSet);
                        db.Save();
                        return RedirectToAction("PermissionSet", new { id = 0 });
                    }
                    else if (!String.IsNullOrEmpty(NewPermissions))
                    {
                        var NewPermissionSet = new Forum_Permission();
                        NewPermissionSet.Name = "Unnamed";
                        db.AddPermission(NewPermissionSet);
                        db.Save();
                        return RedirectToAction("PermissionSet", new { id = NewPermissionSet.PermissionID });
                    }
                }

                model.PermissionSet = CurrentPermissionSet;

                model.UserGroups = db.GetAllRoles().Where(R => R.RoleID != (int)BuildInRole.Administrator).ToClassList(R => new AdminNamedID() { ID = R.RoleID, Name = R.Name });
                model.Categories = db.GetAllCategories().ToClassList(C => new AdminNamedID() { ID = C.CategoryID, Name = C.Name });
                model.PermissionSets = db.GetAllPermissionSets().ToClassList(P => new AdminNamedID() { ID = P.PermissionID, Name = P.Name });
                model.Fixed = AdminPermissionLinkEditors.FixedSet.PermissionSets;

                model.FixedNamedID = new AdminNamedID() { ID = CurrentPermissionSet.PermissionID, Name = CurrentPermissionSet.Name };
                model.PermissionLinkList = db.GetPermissionLinks().Where(L => L.PermissionID == CurrentPermissionSet.PermissionID).OrderBy(L => L.CategoryID).ToClassList(L => new AdminPermissionLink()
                {
                    Category = new AdminNamedID() { ID = L.CategoryID, Name = db.GetCategoryByID(L.CategoryID).Name },
                    UserGroup = new AdminNamedID() { ID = L.RoleID, Name = db.GetRole(L.RoleID).Name },
                    PermissionSet = model.FixedNamedID
                });

                return View(model);
            }
        }
Exemplo n.º 20
0
        public new ActionResult User(AdminUpdateUser model)
        {
            model.AddNavigation("Admin Panel", "Overview", "Admin", null);
            model.AddNavigation("Update User");
            using (ForumRespository db = new ForumRespository())
            {
                Forum_User CurrentUser = GetCurrentUser(db);

                if (!UserIdentity.IsAdmin)
                    return AuthenticationHelper.AccessDeniedView(model); // Administrating the forum requires the user to be an Admin.

                Forum_User UpdateUser = db.GetUserByID(model.id);

                if (UpdateUser == null)
                    return NotFoundView("User");

                model.OldEmail = UpdateUser.Email;
                model.OldUserName = UpdateUser.Username;

                if (IsHttpPost && ModelState.IsValid)
                {
                    if (!AntiForgeryTokenValid)
                    {
                        ModelState.AddModelError("AntiForgery", "The antiforgery token was invalid.");
                    }
                    else
                    {
                        if (!String.IsNullOrEmpty(model.Reg_Username))
                            UpdateUser.Username = model.Reg_Username;

                        if (!String.IsNullOrEmpty(model.Reg_Email))
                            UpdateUser.Email = model.Reg_Email;

                        if (!String.IsNullOrEmpty(model.Reg_Password))
                        {
                            var NewPassword = ((ForumMembershipProvider)Membership.Provider).CalculateSaltedPasswordHash(model.Reg_Password, UpdateUser.Salt);
                            UpdateUser.PasswordHash = NewPassword;
                        }

                        db.Save();

                        return RedirectToAction("Overview");
                    }
                }

                return View(model);
            }
        }
Exemplo n.º 21
0
 public static void LogOff()
 {
     if (!Identity.IsAuthenticated) return;
     using (ForumRespository db = new ForumRespository())
     {
         db.RemoveUserSession(Identity.SessionID);
         db.Save();
     }
 }
Exemplo n.º 22
0
        void HandlePermissionsLinkUpdates()
        {
            if (!IsHttpPost) return;
            if (!AntiForgeryTokenValid) return;
            var Form = HttpContext.Request.Form;
            string Button = Form["permissionslinkbutton"];
            if (String.IsNullOrWhiteSpace(Button)) return;

            int CategoryID, PermissionsID, RoleID;

            try {
                CategoryID = Convert.ToInt32(Form["Category"]);
                PermissionsID = Convert.ToInt32(Form["PermissionSet"]);
                RoleID = Convert.ToInt32(Form["UserGroup"]);
            } catch (FormatException)
            {
                ModelState.AddModelError("InvalidData", "Numbers are invalid");
                return;
            } catch (OverflowException)
            {
                ModelState.AddModelError("InvalidData", "Numbers are too big");
                return;
            }

            using (ForumRespository db = new ForumRespository())
            {
                var PermissionsLink = db.GetPermissionLinks().SingleOrDefault(L => L.CategoryID == CategoryID && L.PermissionID == PermissionsID && L.RoleID == RoleID);

                if (Button == "Add")
                {
                    if (PermissionsLink != null)
                    {
                        ModelState.AddModelError("AddLinkError", "Permission link already exists");
                        return;
                    }

                    db.AddPermissionsLink(new Forum_PermissionsLink() { CategoryID = CategoryID, PermissionID = PermissionsID, RoleID = RoleID });

                    try
                    {
                        db.Save();
                    }
                    catch
                    {
                        ModelState.AddModelError("AddLinkError", "Unable to add new permissions link");
                    }
                }
                else if (Button == "Delete")
                {
                    if (PermissionsLink == null)
                    {
                        ModelState.AddModelError("DeleteLinkError", "Permission link doesn't exists");
                        return;
                    }

                    db.DeletePermissionsLink(PermissionsLink);
                    try
                    {
                        db.Save();
                    }
                    catch
                    {
                        ModelState.AddModelError("DeleteLinkError", "Unable to delete permissions link");
                    }
                }
            }
        }
Exemplo n.º 23
0
        public ActionResult Edit(WritePostViewModel model, string button)
        {
            using (ForumRespository db = new ForumRespository())
            {
                Forum_Post Post = db.GetPostByID(model.id);
                if (Post == null) return NotFoundView("Post");

                var Editor = GetCurrentUser(db);

                if (!db.CheckCategoryPermissions(Post.Forum_Thread.Forum_Category, Editor, P => (P.AllowEditOwnPost && Post.PosterID == Editor.UserID && Post.PosterID != (int)BuildInUser.Guest) || P.AllowEditAllPosts))
                    return AuthenticationHelper.AccessDeniedView(model);

                if (Post.Forum_Thread.Locked)
                    return AuthenticationHelper.AccessDeniedView(model);

                if (IsHttpPost)
                {
                    if (String.Equals(button, "preview", StringComparison.InvariantCultureIgnoreCase))
                    {
                        model.ShowPost = true;
                        model.PostHtml = PostParser.Parse(model.PostText);
                        ModelState.Clear();
                    }
                    else
                    {
                        if (!AntiForgeryTokenValid)
                        {
                            ModelState.AddModelError("AntiForgery", "The antiforgery token was invalid.");
                        }
                        else if (ModelState.IsValid)
                        {
                            Post.TimeStamp = DateTime.Now;
                            Post.PostText = model.PostText;
                            Post.Forum_Thread.LastPostTime = Post.TimeStamp;
                            if (Post == Post.Forum_Thread.Forum_Posts[0] && !String.IsNullOrEmpty(Post.Forum_Thread.Title))
                            {
                                Post.Forum_Thread.Title = model.ThreadTitle;
                            }
                            // Save to database
                            db.Save();

                            int PostIndex = Post.Forum_Thread.Forum_Posts.IndexOf(Post);
                            int EditedPostPage = PostIndex / POSTS_PER_PAGE + 1;
                            int EditedPostNumber = PostIndex % POSTS_PER_PAGE + 1;

                            return RedirectToAction("ViewThread", new { id = Post.ThreadID, page = EditedPostPage }).AddFragment(String.Format("Post_{0}", EditedPostNumber));
                        }
                    }
                }
                else
                {
                    model.PostText = Post.PostText;
                    ModelState.Clear();
                }
                if (Post == Post.Forum_Thread.Forum_Posts[0])
                    model.EditTitle = true;

                model.ThreadID = Post.ThreadID;
                model.Title = "Edit Post";
                model.ThreadTitle = Post.Forum_Thread.Title;
                model.AddNavigation(Post.Forum_Thread);
                model.AddNavigation("Edit Post");
                return View("WritePost", model);
            }
        }
Exemplo n.º 24
0
        void ThreadInfoModelFromThread(ForumRespository db, Forum_User User, IEnumerable<Forum_Thread> Threads, ICollection<ThreadInfoViewModel> InfoCollection)
        {
            foreach (var Thread in Threads)
            {
                ThreadInfoViewModel NewThreadInfo = new ThreadInfoViewModel()
                {
                    ThreadTitle = Thread.Title,
                    ThreadID = Thread.ThreadID,
                    PostCount = Thread.Posts
                };

                InfoCollection.Add(NewThreadInfo);

                if (User == null)
                    NewThreadInfo.LastViewedPost = Thread.Posts;
                else
                    NewThreadInfo.LastViewedPost = db.GetLastPost(Thread, User);

                NewThreadInfo.Locked = Thread.Locked;

                NewThreadInfo.PageCount = (Thread.Posts - 1) / POSTS_PER_PAGE + 1;
                NewThreadInfo.LastViewedPostPage = NewThreadInfo.LastViewedPost / POSTS_PER_PAGE + 1;
                NewThreadInfo.LastViewedPostID = NewThreadInfo.LastViewedPost % POSTS_PER_PAGE + 1;

                Forum_Post LastPost = Thread.Forum_Posts.Last();
                NewThreadInfo.LastPoster = new UserViewModel();
                NewThreadInfo.LastPoster.Name = LastPost.Forum_User.Username;
                NewThreadInfo.LastPoster.UserID = LastPost.Forum_User.UserID;
                NewThreadInfo.LastPostTime = LastPost.TimeStamp;
            }
        }
Exemplo n.º 25
0
        public ActionResult EditThread(int id, int? MoveTo, string Lock, string Delete)
        {
            using (ForumRespository db = new ForumRespository())
            {
                Forum_Thread EditedThread = db.GetThreadByID(id);
                if (EditedThread == null)
                    return NotFoundView("Post");

                var model = new EditThreadViewModel();
                var Category = EditedThread.Forum_Category;

                model.AddNavigation(EditedThread);
                model.AddNavigation("Edit Thread");

                var Editor = GetCurrentUser(db);

                model.AllowDelete = db.CheckCategoryPermissions(Category, Editor, P => (P.AllowDeleteOwnThread && EditedThread.Forum_Posts[0].PosterID == Editor.UserID && EditedThread.PosterID != (int)BuildInUser.Guest) || P.AllowDeleteAllThread);
                model.AllowMove = db.CheckCategoryPermissions(Category, Editor, P => P.AllowMoveThread);
                model.AllowLock = db.CheckCategoryPermissions(Category, Editor, P => P.AllowLockThread);

                if (!model.AllowDelete && !model.AllowLock && !model.AllowMove)
                    return AuthenticationHelper.AccessDeniedView(model);

                model.id = id;
                model.ThreadName = EditedThread.Title;
                model.CategoryID = Category.CategoryID;
                model.CategoryName = Category.Name;

                model.IsLocked = EditedThread.Locked;

                foreach (var MoveToCategory in db.GetAllCategories())
                {
                    if (MoveToCategory == Category) continue; // Cannot move the where the thread is already
                    if (!MoveToCategory.AllowPosts) continue; // Cannot move to a category that does not allow posts
                    if (!db.CheckCategoryPermissions(MoveToCategory, Editor, P => P.AllowNewThread)) continue; // Cannot move to a category where you are not allowed to create new threads.
                    model.ValidMoveDestinations.Add(new AdminNamedID() { ID = MoveToCategory.CategoryID, Name = MoveToCategory.Name});
                }

                if (IsHttpPost)
                {
                    if (!AntiForgeryTokenValid)
                    {
                        ModelState.AddModelError("AntiForgery", "The antiforgery token was invalid.");
                    }
                    else
                    {
                        if (model.AllowDelete && !String.IsNullOrEmpty(Delete))
                        {
                            db.DeleteThread(EditedThread);
                            db.Save();
                            return RedirectToAction("ViewCategory", new { id = model.CategoryID });
                        }
                        if (model.AllowMove)
                        {
                            var Destination = db.GetCategoryByID((int)MoveTo);
                            if (Destination != null && model.ValidMoveDestinations.Exists(D => D.ID == Destination.CategoryID))
                            {
                                EditedThread.Forum_Category = Destination;
                            }
                        }
                        if (model.AllowLock)
                            EditedThread.Locked = !String.IsNullOrEmpty(Lock);
                        db.Save();
                        return RedirectToAction("ViewThread", new { id = model.id });
                    }
                }
                return View(model);
            }
        }
Exemplo n.º 26
0
 public JsonResult UserNameAvailable(string Reg_Username)
 {
     using (var db = new ForumRespository())
     {
         return Json(!db.UserExists(Reg_Username), JsonRequestBehavior.AllowGet);
     }
 }
Exemplo n.º 27
0
        /// <summary>
        /// Fills the list with subcategories found in the database, and fills the subcategories with their subcategories, until MaxRecursion
        /// level is reached, or all are accounted for. 
        /// </summary>
        /// <param name="db">The repository. Since read-only, any will do, but don't create one needlessly</param>
        /// <param name="ModelList">The list to fill</param>
        /// <param name="id">The id of the category, or null if primary categories are to be found</param>
        /// <param name="MaxRecursionLevel">0 means no recursion, only fill the current list.</param>
        private void ViewCategory_RecursivelyFillSubcategories(ForumRespository db, Forum_User CategoryReader, List<SubCategoryModel> ModelList, int id, int MaxRecursionLevel)
        {
            if (MaxRecursionLevel < 0) return;
            foreach (var SubCategory in db.GetSortedCategories(id))
            {
                if (!SubCategory.InheritPermissions && !db.CheckCategoryPermissions(SubCategory, CategoryReader, P => P.AllowView))
                    continue;
                SubCategoryModel SubModel = new SubCategoryModel() {
                    id = SubCategory.CategoryID,
                    Name = SubCategory.Name,
                    AllowPosts = SubCategory.AllowPosts
                };

                ModelList.Add(SubModel);
                if (!SubCategory.AllowPosts)
                {
                    ViewCategory_RecursivelyFillSubcategories(db, CategoryReader, SubModel.SubCategories, SubModel.id, MaxRecursionLevel - 1);
                }
                else
                {
                    IQueryable<Forum_Thread> Threads = db.GetSortedThreads(SubCategory.CategoryID);
                    SubModel.ThreadCount = Threads.Count();
                    if (SubModel.ThreadCount > 0)
                    {
                        SubModel.PostCount = Threads.Sum(T => T.Posts);
                        SubModel.LastPostTime = Threads.First().LastPostTime;
                    }
                }
            }
        }