Ejemplo n.º 1
0
        public ActionResult TeacherUploader(HttpPostedFileBase postedFile, string id, bool refresh = false)
        {
            TeacherUploadViewModel tuvm = new TeacherUploadViewModel();

            tuvm.Id    = id;
            tuvm.Files = new List <FileDocument>();
            var currentUser = UserUtils.GetCurrentUser(HttpContext);

            try
            {
                int intId;
                if (int.TryParse(id.Substring(1), out intId))
                {
                    FileDocument file = new FileDocument();
                    file.MemberId  = currentUser.Id;
                    file.TimeStamp = DateTime.Now;
                    switch (id[0])
                    {
                    case 'a':
                        Activity activity = db.Activities.Find(intId);
                        file.ActivityId   = activity.Id;
                        tuvm.ActivityName = activity.Name;
                        tuvm.Files        = activity.Files;
                        break;

                    case 'm':
                        Module module = db.Modules.Find(intId);
                        file.ModuleId   = module.Id;
                        tuvm.ModuleName = module.Name;
                        tuvm.Files      = module.Files;
                        break;

                    case 'c':
                        Course course = db.Courses.Find(intId);
                        file.CourseId   = course.Id;
                        tuvm.CourseName = course.Name;
                        tuvm.Files      = course.Files;
                        break;

                    default:
                        break;
                    }
                    if (!refresh)
                    {
                        if (postedFile != null)
                        {
                            file.Name = postedFile.FileName;

                            string path = Server.MapPath("~/Uploads/");
                            if (!Directory.Exists(path))
                            {
                                Directory.CreateDirectory(path);
                            }
                            db.Files.Add(file);
                            db.SaveChanges();
                            postedFile.SaveAs(path + file.Id.Encode().ToString());
                            TempData["alert"] = "success|Dokumentet är uppladdat!";
                        }
                        else
                        {
                            TempData["alert"] = "danger|Kunde inte lägga till dokument";
                        }
                    }
                }
            }
            catch (Exception)
            {
                TempData["alert"] = "danger|Allvarligt fel!";
            }
            return(PartialView("_TeacherUploader", tuvm));
        }
Ejemplo n.º 2
0
        public void TestPostDeltas()
        {
            //Assumptions:
            // Role 'Contributor' exists
            // Role 'Viewer' exists
            //Actions:
            // Create User1, User2 and User3
            // User1 is contributor, User2 is contributor on /A/B*
            // User3 is a viewer on A* (grant added)
            //Expected result:
            // User3 is viewer on /A*
            // User1 and user2 are contributors on /A/B*

            Plug p = Utils.BuildPlugForAdmin();

            string baseTreePath = PageUtils.BuildPageTree(p);

            string       userid1 = null;
            DreamMessage msg     = UserUtils.CreateRandomContributor(p, out userid1);

            string userid2 = null;

            msg = UserUtils.CreateRandomContributor(p, out userid2);

            string userid3 = null;

            msg = UserUtils.CreateRandomContributor(p, out userid3);

            XDoc securityDoc = new XDoc("security")
                               .Start("permissions.page")
                               .Elem("restriction", "Private")
                               .End()
                               .Start("grants")
                               .Start("grant")
                               .Start("permissions")
                               .Elem("role", "Contributor")
                               .End()
                               .Start("user").Attr("id", userid1).End()
                               .End()
                               .Start("grant")
                               .Start("permissions")
                               .Elem("role", "Contributor")
                               .End()
                               .Start("user").Attr("id", userid2).End()
                               .End()
                               .End();

            msg = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A/B"), "security").
                  WithQuery("cascade=absolute").Put(securityDoc);
            Assert.AreEqual(DreamStatus.Ok, msg.Status);

            securityDoc = new XDoc("security")
                          .Start("permissions.page")
                          .Elem("restriction", "Private")
                          .End()
                          .Start("grants.added")
                          .Start("grant")
                          .Start("permissions")
                          .Elem("role", "Viewer")
                          .End()
                          .Start("user").Attr("id", userid3).End()
                          .End()
                          .End();

            msg = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A"), "security").
                  WithQuery("cascade=delta").Post(securityDoc);
            Assert.AreEqual(DreamStatus.Ok, msg.Status);

            msg = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A"), "security").Get();
            Assert.AreEqual(msg.ToDocument()[string.Format("grants/grant[user/@id=\"{0}\"]/permissions/role", userid3)].Contents, "Viewer");

            msg = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A/B/C"), "security").Get();
            Assert.AreEqual(msg.ToDocument()["permissions.page/restriction"].Contents, "Private");
            Assert.AreEqual(msg.ToDocument()[string.Format("grants/grant[user/@id=\"{0}\"]/permissions/role", userid1)].Contents, "Contributor");
            Assert.AreEqual(msg.ToDocument()[string.Format("grants/grant[user/@id=\"{0}\"]/permissions/role", userid2)].Contents, "Contributor");
            Assert.AreEqual(msg.ToDocument()[string.Format("grants/grant[user/@id=\"{0}\"]/permissions/role", userid3)].Contents, "Viewer");
        }
Ejemplo n.º 3
0
        public void FailedPermissionChangeWhenPartOfMultipleGroups()
        {
            //Assumptions:
            //  Role 'Contributor' exist
            //Actions:
            //  Create user user1 with "Contributor" role
            //  Create group group1 with "Contributor" role
            //  Create group group2 with "Contributor" role
            //  Assing user1 with group1 and group2
            //  Create new page
            //  Set page restriction as private
            //  Set grant to page for user1, group1 and group2
            //  Login as user1
            //  Remove group2 from list of grants
            //Expected result:
            //  List of grants doesn't content group2

            Plug p = Utils.BuildPlugForAdmin();

            string       userid   = null;
            string       username = null;
            DreamMessage msg      = UserUtils.CreateRandomContributor(p, out userid, out username);

            string groupid1 = null;

            msg = UserUtils.CreateRandomGroup(p, new string[] { userid }, out groupid1);

            string groupid2 = null;

            msg = UserUtils.CreateRandomGroup(p, new string[] { userid }, out groupid2);

            string pageid = null;

            msg = PageUtils.CreateRandomPage(p, out pageid);

            XDoc securityDoc = new XDoc("security")
                               .Start("permissions.page")
                               .Elem("restriction", "Private")
                               .End()
                               .Start("grants")
                               .Start("grant")
                               .Start("permissions")
                               .Elem("role", "Contributor")
                               .End()
                               .Start("user").Attr("id", userid).End()
                               .End()
                               .Start("grant")
                               .Start("permissions")
                               .Elem("role", "Contributor")
                               .End()
                               .Start("group").Attr("id", groupid1).End()
                               .End()
                               .Start("grant")
                               .Start("permissions")
                               .Elem("role", "Contributor")
                               .End()
                               .Start("group").Attr("id", groupid2).End()
                               .End()
                               .End();

            msg = p.At("pages", pageid, "security").Put(securityDoc);
            Assert.IsTrue(msg.IsSuccessful, "Failed to set page to private");

            p = Utils.BuildPlugForUser(username);

            securityDoc = new XDoc("security")
                          .Start("permissions.page")
                          .Elem("restriction", "Private")
                          .End()
                          .Start("grants.removed")
                          .Start("grant")
                          .Start("permissions")
                          .Elem("role", "Contributor")
                          .End()
                          .Start("group").Attr("id", groupid2).End()
                          .End()
                          .End();

            msg = p.At("pages", pageid, "security").Post(securityDoc);
            Assert.IsTrue(msg.IsSuccessful, "Failed to set page to private");

            Assert.AreEqual(msg.ToDocument()["permissions.page/restriction"].Contents, "Private");
            Assert.AreEqual(msg.ToDocument()[string.Format("grants/grant[user/@id=\"{0}\"]/permissions/role", userid)].Contents, "Contributor");
            Assert.AreEqual(msg.ToDocument()[string.Format("grants/grant[group/@id=\"{0}\"]/permissions/role", groupid1)].Contents, "Contributor");
            Assert.IsTrue(msg.ToDocument()[string.Format("grants/grant[group/@id=\"{0}\"]/permissions/role", groupid2)].IsEmpty);
        }
Ejemplo n.º 4
0
        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            var userId = (int)providerUserKey;
            var user   = new UserEntity(userId);

            if (!user.IsNew && !user.LastLoginTime.HasValue)
            {
                if (username.Length >= MinUsernameLength && !username.Contains(" "))
                {
                    if (ValidateNewPassword(password))
                    {
                        var args = new ValidatePasswordEventArgs(username, password, true);
                        OnValidatingPassword(args);
                        if (!args.Cancel)
                        {
                            if (UserUtils.GetByUsername(username) == null)
                            {
                                Transaction transaction = new Transaction(IsolationLevel.ReadCommitted, "user initialization");

                                try
                                {
                                    transaction.Add(user);

                                    user.Username     = username;
                                    user.EmailAddress = email;
                                    SetPassword(user, password, transaction);

                                    user.Save();

                                    transaction.Commit();

                                    status = MembershipCreateStatus.Success;

                                    return(GetUser(username, true));
                                }
                                catch (Exception)
                                {
                                    transaction.Rollback();
                                    status = MembershipCreateStatus.ProviderError;
                                }
                                finally
                                {
                                    transaction.Dispose();
                                }
                            }
                            else
                            {
                                status = MembershipCreateStatus.DuplicateUserName;
                            }
                        }
                        else
                        {
                            status = MembershipCreateStatus.InvalidPassword;
                        }
                    }
                    else
                    {
                        status = MembershipCreateStatus.InvalidPassword;
                    }
                }
                else
                {
                    status = MembershipCreateStatus.InvalidUserName;
                }
            }
            else
            {
                status = MembershipCreateStatus.InvalidProviderUserKey;
            }

            return(null);
        }
Ejemplo n.º 5
0
        public void TestAbsoluteCascading()
        {
            //Assumptions:
            //role 'contributor' exists
            //Actions:
            // Create User1 and User2
            //User1 is contributor on /A/B/* with absolute cascading
            //User2 is contributor on /A* with absolute cascading
            //Expected result:
            // A/* including A/B does not have user1 as contributor

            Plug p = Utils.BuildPlugForAdmin();

            string baseTreePath = PageUtils.BuildPageTree(p);

            string       userid1 = null;
            DreamMessage msg     = UserUtils.CreateRandomContributor(p, out userid1);

            string userid2 = null;

            msg = UserUtils.CreateRandomContributor(p, out userid2);

            XDoc securityDoc = new XDoc("security")
                               .Start("permissions.page")
                               .Elem("restriction", "Private")
                               .End()
                               .Start("grants")
                               .Start("grant")
                               .Start("permissions")
                               .Elem("role", "Contributor")
                               .End()
                               .Start("user").Attr("id", userid1).End()
                               .End()
                               .End();

            msg = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A/B"), "security").
                  WithQuery("cascade=absolute").Put(securityDoc);
            Assert.AreEqual(DreamStatus.Ok, msg.Status);

            securityDoc = new XDoc("security")
                          .Start("permissions.page")
                          .Elem("restriction", "Private")
                          .End()
                          .Start("grants")
                          .Start("grant")
                          .Start("permissions")
                          .Elem("role", "Contributor")
                          .End()
                          .Start("user").Attr("id", userid2).End()
                          .End()
                          .End();

            msg = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A"), "security").
                  WithQuery("cascade=absolute").Put(securityDoc);
            Assert.AreEqual(DreamStatus.Ok, msg.Status);

            msg = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A/B"), "security").Get();
            Assert.AreEqual(msg.ToDocument()["permissions.page/restriction"].Contents, "Private");
            Assert.AreEqual(msg.ToDocument()["grants/grant[1]/user/@id"].Contents, userid2);
            Assert.IsTrue(msg.ToDocument()["grants/grant[2]"].IsEmpty);
        }
Ejemplo n.º 6
0
        public async Task <object> Seed()
        {
            await _context.Database.EnsureCreatedAsync();

            await _roleManager.CreateAsync(new IdentityRole("Admin"));

            await _roleManager.CreateAsync(new IdentityRole("Director"));

            await _roleManager.CreateAsync(new IdentityRole("Curator"));

            await _roleManager.CreateAsync(new IdentityRole("Teacher"));

            await _roleManager.CreateAsync(new IdentityRole("Student"));

            try
            {
                var college = _context.Colleges.Add(new College {
                    Name = "МРК"
                }).Entity;

                await UserUtils.CreateUser(_userManager, "*****@*****.**", "_Wsda1234", "Admin");

                var director = await UserUtils.CreateUser(_userManager, "*****@*****.**", "_Wsda1234", "Director");

                director.FirstName = "Сергей";
                director.LastName  = "Анкуда";

                var curator = await UserUtils.CreateUser(_userManager, "*****@*****.**", "_Wsda1234", "Curator");

                curator.FirstName = "Елена";
                curator.LastName  = "Клемято";

                var teacher = await UserUtils.CreateUser(_userManager, "*****@*****.**", "_Wsda1234", "Teacher");

                teacher.FirstName = "Марина";
                teacher.LastName  = "Бельчик";

                var student = await UserUtils.CreateUser(_userManager, "*****@*****.**", "_Wsda1234", "Student");

                student.FirstName = "Владислав";
                student.LastName  = "Добрицкий";

                var student1 = await UserUtils.CreateUser(_userManager, "*****@*****.**", "_Wsda1234", "Student");

                student1.FirstName = "Андросов";
                student1.LastName  = "Павел";

                var student2 = await UserUtils.CreateUser(_userManager, "*****@*****.**", "_Wsda1234", "Student");

                student2.FirstName = "Бубневич";
                student2.LastName  = "Илья";

                var student3 = await UserUtils.CreateUser(_userManager, "*****@*****.**", "_Wsda1234", "Student");

                student3.FirstName = "Голодок";
                student3.LastName  = "Андрей";

                var student4 = await UserUtils.CreateUser(_userManager, "*****@*****.**", "_Wsda1234", "Student");

                student4.FirstName = "Гуриш";
                student4.LastName  = "Елизавета";

                var student5 = await UserUtils.CreateUser(_userManager, "*****@*****.**", "_Wsda1234", "Student");

                student5.FirstName = "Зазаульничкий";
                student5.LastName  = "Дмитрий";


                var student7 = await UserUtils.CreateUser(_userManager, "*****@*****.**", "_Wsda1234", "Student");

                student7.FirstName = "Колышко";
                student7.LastName  = "Кирилл";

                var specialty = _context.Specialties.Add(new Specialty()
                {
                    College = college, Name = "ПОИТ"
                }).Entity;
                var group = _context.CollegeGroups.Add(new CollegeGroup()
                {
                    Number = "42491", Specialty = specialty
                }).Entity;
                var subGroup = _context.SubGroups.Add(new SubGroup()
                {
                    Name = "42491sub1", Group = group
                }).Entity;

                _context.Directors.Add(new Director()
                {
                    User = director, College = college
                });
                var s = _context.Students.Add(new Student()
                {
                    User = student, SubGroup = subGroup
                }).Entity;

                _context.Students.Add(new Student()
                {
                    User = student1, SubGroup = subGroup
                });
                _context.Students.Add(new Student()
                {
                    User = student2, SubGroup = subGroup
                });
                _context.Students.Add(new Student()
                {
                    User = student3, SubGroup = subGroup
                });
                _context.Students.Add(new Student()
                {
                    User = student4, SubGroup = subGroup
                });
                _context.Students.Add(new Student()
                {
                    User = student5, SubGroup = subGroup
                });
                _context.Students.Add(new Student()
                {
                    User = student7, SubGroup = subGroup
                });

                var t = _context.Teachers.Add(new Teacher()
                {
                    User = teacher, College = college
                }).Entity;
                _context.Teachers.Add(new Teacher()
                {
                    User = curator, College = college
                });

                var semester = _context.Semesters.Add(new Semester()
                {
                    Number    = 1,
                    StartDate = new DateTime(2017, 9, 1),
                    EndDate   = new DateTime(2017, 12, 24),
                    SubGroup  = subGroup
                }).Entity;
                var subject = _context.Subjects.Add(new Subject()
                {
                    Name = "КПиЯП", College = college
                }).Entity;
                var topic = _context.Topics.Add(new Topic()
                {
                    Name = "Делегаты", Subject = subject
                }).Entity;
                _context.Topics.Add(new Topic()
                {
                    Name = "Типы данных в C#", Subject = subject
                });
                _context.Topics.Add(new Topic()
                {
                    Name = "Работа с массивами C#", Subject = subject
                });
                _context.Topics.Add(new Topic()
                {
                    Name = "Основы ООП", Subject = subject
                });
                _context.Topics.Add(new Topic()
                {
                    Name = "Практическая работа №1", Subject = subject
                });

                await _context.SaveChangesAsync();

                await new TeacheSubjectInfoController(_context).CreateTsi(new TsiDto()
                {
                    Semester = new SemesterDTO()
                    {
                        ID = semester.ID
                    },
                    Subject = new SubjectDTO()
                    {
                        ID = subject.ID
                    },
                    Teacher = new TeacherDTO()
                    {
                        ID = t.ID
                    }
                });

                var lesson1 = await _context.Lessons.FirstOrDefaultAsync(l => l.Date == new DateTime(2017, 09, 05));

                var lesson2 = await _context.Lessons.FirstOrDefaultAsync(l => l.Date == new DateTime(2017, 09, 06));

                var lesson3 = await _context.Lessons.FirstOrDefaultAsync(l => l.Date == new DateTime(2017, 09, 20));

                var lesson4 = await _context.Lessons.FirstOrDefaultAsync(l => l.Date == new DateTime(2017, 09, 21));

                var lesson5 = await _context.Lessons.FirstOrDefaultAsync(l => l.Date == new DateTime(2017, 10, 05));

                var mark1 = _context.Marks.Add(new Mark()
                {
                    IsAbsent = false, IsCredited = false, Lesson = lesson1, Student = s, Value = 9
                }).Entity;
                var mark2 = _context.Marks.Add(new Mark()
                {
                    IsAbsent = false, IsCredited = false, Lesson = lesson2, Student = s, Value = 9
                }).Entity;
                var mark3 = _context.Marks.Add(new Mark()
                {
                    IsAbsent = false, IsCredited = false, Lesson = lesson3, Student = s, Value = 9
                }).Entity;
                var mark4 = _context.Marks.Add(new Mark()
                {
                    IsAbsent = false, IsCredited = false, Lesson = lesson4, Student = s, Value = 9
                }).Entity;
                var mark5 = _context.Marks.Add(new Mark()
                {
                    IsAbsent = false, IsCredited = false, Lesson = lesson5, Student = s, Value = 9
                }).Entity;
            }
            catch
            {
                return("Seeding Error");
            }

            await _context.SaveChangesAsync();

            return(Ok("Seeding Success"));
        }
        public static void Update()
        {
            if (!BlazeManager.GetForPlayer <bool>("Fly Enable"))
            {
                return;
            }
            if (BlazeManager.GetForPlayer <bool>("Fly Type"))
            {
                Player    player    = Player.Instance;
                Transform transform = Camera.main.transform;
                player.GetComponent <Collider>().enabled = false;
                float MultiSpeed = Input.GetKey(KeyCode.LeftShift) ? 2.5F : 1F;
                float calcTimes  = MultiSpeed * Time.deltaTime;
                // NoClipMode
                if (Input.GetKey(KeyCode.E))
                {
                    player.transform.position += new Vector3(0, 1f, 0) * fNoClipSpeed * calcTimes;
                }
                else if (Input.GetKey(KeyCode.Q))
                {
                    player.transform.position -= new Vector3(0, 1f, 0) * fNoClipSpeed * calcTimes;
                }

                Vector3 moveControl = Player.Instance.transform.position;
                if (Math.Abs(Input.GetAxis("Vertical")) > 0f)
                {
                    moveControl += calcTimes * fNoClipSpeed * transform.forward * Input.GetAxis("Vertical");
                }
                if (Math.Abs(Input.GetAxis("Horizontal")) > 0f)
                {
                    moveControl += calcTimes * fNoClipSpeed * transform.right * Input.GetAxis("Horizontal");
                }
                UserUtils.TeleportTo(moveControl);
            }
            else
            {
                Player player = Player.Instance;
                player.GetComponent <Collider>().enabled = true;
                if (Input.GetKey(KeyCode.Q))
                {
                    Physics.gravity = new Vector3(0, -9.5f, 0);
                    iCountBalance   = 10;
                }
                else if (Input.GetKey(KeyCode.E))
                {
                    Physics.gravity = new Vector3(0, 9.5f, 0);
                    iCountBalance   = 10;
                }
                else if (iCountBalance >= 0)
                {
                    CharacterController controller = player.GetComponent <CharacterController>();
                    if (controller.velocity[1] != 0.0f)
                    {
                        iCountBalance   = 10;
                        Physics.gravity = new Vector3(0, -controller.velocity[1] * 2.0f);
                    }
                    else
                    {
                        iCountBalance   = -1;
                        Physics.gravity = Vector3.zero;
                    }
                }
            }
        }
Ejemplo n.º 8
0
        public void AMAPRASelfMaxCreditTest()
        {
            //creating a random user with api calls
            UserInfo NewUser1 = UserUtils.CreateUser("AMA-SL");

            /// 1. Navigate to the login page
            LoginPage LP = Navigation.GoToLoginPageMainpro(browser);



            //create the dashboard page
            //Login to the Automation Test User, However another user should be selected in the case that
            //
            DashboardPage DP = LP.LoginAsUser(NewUser1.Username, "test");;

            //deal with the eula
            DP.EULAButton.Click();

            EnterACPDActivityPage EP = DP.ClickToAdvance(DP.EnterCPDActBtn);

            /// 3. create an activity that is a Certified Assessment, Other Activity                  MIKE: Added an end line above here
            EP.FillEnterACPDActivityForm("Self-Learning", "Certified", "American Medical Association (AMA) PRA Category 1");

            //if the popup appears, click the okay button and then
            //click on the popup button appears
            if (EP.AMAPopupSubmitBtn.Displayed)
            {
                EP.AMAPopupSubmitBtn.Click();
            }


            EP.LiveInPersonRdoBtn.Click();
            EP.ClickToAdvance(EP.LiveInPersonRdoBtn);


            /// 4. Click continue after all of the options have been selected
            EP.ContinueBtn.Click();
            Thread.Sleep(2000);            // MIKE: Add wait criteria for this click, then use ClickToAdvance and place the wait criteria in there, instead of sleeping. Can wait for an element to appear on the next instance of this page

            /// 5. Fill out the details
            EP.FillOutAMAActivityForm1(90);   // MIKE: See comments inside method

            //next go on and check to see that only 50 credits are applied to the Certification
            Browser.ExecuteScript("arguments[0].click();", EP.PopupSubmitBtn);
            Thread.Sleep(8000);      // MIKE: Add wait criteria. Can wait for an element to be NOT visible

            DP.DashboardTab.Click();
            Thread.Sleep(1000);  // MIKE: Add wait criteria



            double newCreditValue = DP.GetTotalCredits();

            //loop over until the credits update
            do
            {
                Thread.Sleep(5000);
                browser.Navigate().Refresh();
                newCreditValue = DP.GetTotalCredits();
            } while (newCreditValue == 0);

            //once the new credits appear, click on the link to open up the popup
            int x = 0;

            //now check to see if the applied credits
            DP.TotalCreditsLinkLnk.Click();
            Thread.Sleep(5000);

            String creditValue = DP.TotalCreditsValueLbl.Text;

            //just putting the wait criteria here incase a breakpoint is needed
            Thread.Sleep(5000);
            Assert.AreEqual(creditValue, "50");
        }
Ejemplo n.º 9
0
        public void EnterAnArticleTest()
        {
            //creating a random user with api calls
            UserInfo NewUser1 = UserUtils.CreateUser("Article");
            /// 1. Navigate to the login page and Log In
            LoginPage LP = Navigation.GoToLoginPageMainpro(browser);

            // Wrapper to login
            DashboardPage DP = LP.LoginAsUser(NewUser1.Username, "test");


            /// 2. Click on the Enter a CPD Activity Button
            DP.EULAButton.Click();



            /// 3. Fill out the Enter a CPD Activity 1st Page
            EnterACPDActivityPage EP = DP.ClickToAdvance(DP.EnterCPDActBtn);

            EP.FillEnterACPDActivityForm("Self-Learning", "Certified", "CFP Mainpro+ Articles");

            EP.ArticleDrpDn.Click();
            Thread.Sleep(1000);

            EP.AntibioticArticle.Click();
            Thread.Sleep(1000);



            EP.ContinueBtn.Click();
            Thread.Sleep(4000);
            /// 3. Fill out the Article Details for the article

            //scroll to the radio button
            ElemSet.ScrollToElement(browser, EP.ArticleDescriptionRdo);
            //EP.ArticleDescriptionRdo.Click();



            //Generate start and end dates for the article Page
            DateTime dt             = DateTime.Now.AddDays(-1);
            String   startDate      = dt.Month + "/" + dt.Day + "/" + dt.Year;
            String   completionDate = startDate;

            ElemSet.ScrollToElement(browser, EP.ActivityStartDateArticleTxt);
            EP.ActivityStartDateArticleTxt.SendKeys(startDate);
            EP.ActivityStartDateArticleTxt.SendKeys(Keys.Tab);
            ElemSet.ScrollToElement(browser, EP.ActivityCompletionDateArticleTxt);
            EP.ActivityCompletionDateArticleTxt.SendKeys(completionDate);
            EP.ActivityCompletionDateArticleTxt.SendKeys(Keys.Tab);

            ElemSet.ScrollToElement(browser, EP.SubmitButton);
            EP.SubmitButton.SendKeys(Keys.Tab);
            //perform the Selenium Click
            Browser.ExecuteScript("arguments[0].click();", EP.SubmitButton);

            //wait until the popup submit button appears
            Browser.WaitForElement(Bys.EnterACPDActivityPage.PopupSubmitBtn, ElementCriteria.IsVisible);



            Browser.ExecuteScript("arguments[0].click();", EP.PopupSubmitBtn);
            /// 4. return to the dashboard



            String TotalCreditsString = DP.CheckForCreditUpdate();

            /// 5. check to see that the Total credits are now equal to the 0.5 added by the article
            Assert.AreEqual(TotalCreditsString, "0.5");
        }
Ejemplo n.º 10
0
        public void CommentsForTreeOfPagesWithSecurity()
        {
            //Assumptions:
            //Actions:
            //  Create tree of pages
            //  Add comment to every page
            //  Set private restrictions for E page
            //  Try to get comments from user which doesn't have rights for E page
            //Expected result:
            //  All comments received except comments for E

            Plug p = Utils.BuildPlugForAdmin();

            string baseTreePath = PageUtils.BuildPageTree(p);

            string       commentForA   = Utils.GetSmallRandomText();
            DreamMessage postMsg       = DreamMessage.Ok(MimeType.TEXT_UTF8, commentForA);
            DreamMessage msg           = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A"), "comments").Post(postMsg);
            string       commentForAId = msg.ToDocument()["@id"].AsText;

            string commentForB = Utils.GetSmallRandomText();

            postMsg = DreamMessage.Ok(MimeType.TEXT_UTF8, commentForB);
            msg     = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A/B"), "comments").Post(postMsg);
            string commentForBId = msg.ToDocument()["@id"].AsText;

            string commentForC = Utils.GetSmallRandomText();

            postMsg = DreamMessage.Ok(MimeType.TEXT_UTF8, commentForC);
            msg     = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A/B/C"), "comments").Post(postMsg);
            string commentForCId = msg.ToDocument()["@id"].AsText;

            string commentForD = Utils.GetSmallRandomText();

            postMsg = DreamMessage.Ok(MimeType.TEXT_UTF8, commentForD);
            msg     = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A/B/D"), "comments").Post(postMsg);
            string commentForDId = msg.ToDocument()["@id"].AsText;

            string commentForE1 = Utils.GetSmallRandomText();

            postMsg = DreamMessage.Ok(MimeType.TEXT_UTF8, commentForE1);
            msg     = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A/E"), "comments").Post(postMsg);
            string commentForE1Id = msg.ToDocument()["@id"].AsText;

            string commentForE2 = Utils.GetSmallRandomText();

            postMsg = DreamMessage.Ok(MimeType.TEXT_UTF8, commentForE2);
            msg     = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A/E"), "comments").Post(postMsg);
            string commentForE2Id = msg.ToDocument()["@id"].AsText;

            XDoc securityDoc = new XDoc("security")
                               .Start("permissions.page")
                               .Elem("restriction", "Private")
                               .End();

            msg = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A/E"), "security").
                  WithQuery("cascade=none").Put(securityDoc);

            string userid   = null;
            string username = null;

            msg = UserUtils.CreateRandomContributor(p, out userid, out username);

            p = Utils.BuildPlugForUser(username);

            msg = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath), "comments").With("depth", "infinity").Get();
            Assert.IsTrue(msg.ToDocument()["@count"].AsInt == 4);
            Assert.AreEqual(msg.ToDocument()[string.Format("comment[@id='{0}']/content", commentForAId)].AsText, commentForA);
            Assert.AreEqual(msg.ToDocument()[string.Format("comment[@id='{0}']/content", commentForBId)].AsText, commentForB);
            Assert.AreEqual(msg.ToDocument()[string.Format("comment[@id='{0}']/content", commentForCId)].AsText, commentForC);
            Assert.AreEqual(msg.ToDocument()[string.Format("comment[@id='{0}']/content", commentForDId)].AsText, commentForD);
            Assert.IsTrue(msg.ToDocument()[string.Format("comment[@id='{0}']", commentForE1Id)].IsEmpty);
            Assert.IsTrue(msg.ToDocument()[string.Format("comment[@id='{0}']", commentForE2Id)].IsEmpty);
        }
Ejemplo n.º 11
0
        public void GetCommentsWithFilter()
        {
            Plug p = Utils.BuildPlugForAdmin();

            string       id   = null;
            string       path = null;
            DreamMessage msg  = PageUtils.CreateRandomPage(p, out id, out path);

            string       comment = Utils.GetSmallRandomText();
            DreamMessage postMsg = DreamMessage.Ok(MimeType.TEXT_UTF8, comment);

            msg = p.At("pages", id, "comments").Post(postMsg);
            Assert.AreEqual(DreamStatus.Ok, msg.Status);
            string commentId1 = msg.ToDocument()["@id"].AsText;

            Assert.IsFalse(string.IsNullOrEmpty(commentId1));
            Assert.AreEqual(comment, msg.ToDocument()["content"].AsText);

            comment = Utils.GetSmallRandomText();
            postMsg = DreamMessage.Ok(MimeType.TEXT_UTF8, comment);
            msg     = p.At("pages", id, "comments").Post(postMsg);
            Assert.AreEqual(DreamStatus.Ok, msg.Status);
            string commentId2 = msg.ToDocument()["@id"].AsText;

            Assert.IsFalse(string.IsNullOrEmpty(commentId2));
            Assert.AreEqual(comment, msg.ToDocument()["content"].AsText);

            string username = null;
            string userid   = null;

            msg = UserUtils.CreateRandomContributor(p, out userid, out username);

            p = Utils.BuildPlugForUser(username);

            comment = Utils.GetSmallRandomText();
            postMsg = DreamMessage.Ok(MimeType.TEXT_UTF8, comment);
            msg     = p.At("pages", id, "comments").Post(postMsg);
            Assert.AreEqual(DreamStatus.Ok, msg.Status);
            string commentId3 = msg.ToDocument()["@id"].AsText;

            Assert.IsFalse(string.IsNullOrEmpty(commentId3));
            Assert.AreEqual(comment, msg.ToDocument()["content"].AsText);

            msg = p.At("pages", "=" + XUri.DoubleEncode(path), "comments").
                  With("postedbyuserid", userid).Get();
            Assert.AreEqual(DreamStatus.Ok, msg.Status);
            Assert.AreEqual(1, msg.ToDocument()["@count"].AsInt);
            Assert.IsFalse(msg.ToDocument()[string.Format("comment[@id=\"{0}\"]", commentId3)].IsEmpty);
            Assert.IsTrue(msg.ToDocument()[string.Format("comment[@id=\"{0}\"]", commentId1)].IsEmpty);
            Assert.IsTrue(msg.ToDocument()[string.Format("comment[@id=\"{0}\"]", commentId2)].IsEmpty);

            p = Utils.BuildPlugForAdmin();

            msg = p.At("pages", "=" + XUri.DoubleEncode(path), "comments").
                  With("postedbyuserid", UserUtils.GetCurrentUserID(p)).Get();
            Assert.AreEqual(DreamStatus.Ok, msg.Status);
            Assert.AreEqual(2, msg.ToDocument()["@count"].AsInt);
            Assert.IsFalse(msg.ToDocument()[string.Format("comment[@id=\"{0}\"]", commentId1)].IsEmpty);
            Assert.IsFalse(msg.ToDocument()[string.Format("comment[@id=\"{0}\"]", commentId2)].IsEmpty);
            Assert.IsTrue(msg.ToDocument()[string.Format("comment[@id=\"{0}\"]", commentId3)].IsEmpty);

            PageUtils.DeletePageByID(p, id, true);
        }
Ejemplo n.º 12
0
        public async Task <T> DoAuditAsync <T>(T obj, EntityState state = EntityState.Default, string email = "", DatabaseName databaseName = DatabaseName.Default) where T : class, new()
        {
            if (DisableAudit)
            {
                return(obj);
            }

            if (email.IsNullOrEmpty())
            {
                email = UserUtils.GetCurrentEmail();
            }

            if (state == EntityState.Default && (obj as BaseModel) != null)
            {
                state = ((obj as BaseModel).Id == Guid.Empty) ?
                        EntityState.Added :
                        EntityState.Updated;
            }

            var    utcNow               = DateTime.UtcNow;
            var    entityType           = typeof(T).GetCustomAttributes(typeof(DbTableNameAttribute), false);
            var    dbTableNameAttribute = entityType.SingleOrDefault() as DbTableNameAttribute;
            string dbTableName;

            if (dbTableNameAttribute == null)
            {
                var entityBaseType = (!typeof(T).IsAbstract) ? typeof(T) : typeof(T).BaseType;

                dbTableName = entityBaseType?.Name ?? typeof(T).Name;

                dbTableNameAttribute = new DbTableNameAttribute(dbTableName);

                dbTableName = dbTableNameAttribute.TableName;
            }
            else
            {
                dbTableName = dbTableNameAttribute.TableName;
            }

            await Task.Run(() => Run(databaseName, cmd =>
            {
                var eventValue = (obj as IAuditableEntity);

                if (eventValue == null)
                {
                    return;
                }

                var audit = new AuditModel
                {
                    TablePkId = eventValue.DbTablePkId(),
                    ObjectId = eventValue.DbObjectId(),
                    Email = email,
                    DateCreated = utcNow,
                    DateModified = utcNow,
                    IsPublic = true,
                    IsActive = true,
                    IsDeleted = false,
                    TableName = dbTableName
                };

                switch (state)
                {
                case EntityState.Added:
                    audit.EventType = "A";
                    audit.EventValue = eventValue.AddEvent();
                    break;

                case EntityState.Deleted:
                    audit.EventType = "D";
                    audit.EventValue = eventValue.DeleteEvent();
                    break;

                case EntityState.Updated:
                    audit.EventType = "U";
                    audit.EventValue = eventValue.UpdateEvent();
                    break;
                }

                audit.Code = eventValue.DbCode();
                audit.Severity = eventValue.DbSeverity();

                cmd.CommandText = "[dbo].[SaveAudit]";

                cmd.AddParameter("@id", audit.Id);
                cmd.AddParameter("@isActive", audit.IsActive);
                cmd.AddParameter("@isPublic", audit.IsPublic);
                cmd.AddParameter("@isDeleted", audit.IsDeleted);
                cmd.AddParameter("@dateCreated", audit.DateCreated);
                cmd.AddParameter("@dateModified", audit.DateModified);
                cmd.AddParameter("@createdBy", audit.CreatedBy ?? "System");
                cmd.AddParameter("@updatedBy", audit.UpdatedBy ?? "System");
                cmd.AddParameter("@email", audit.Email);
                cmd.AddParameter("@tableName", audit.TableName);
                cmd.AddParameter("@eventType", audit.EventType);
                cmd.AddParameter("@eventValue", audit.EventValue);
                cmd.AddParameter("@tablePkId", audit.TablePkId);
                cmd.AddParameter("@objectId", audit.ObjectId);
                cmd.AddParameter("@severity", audit.Severity);
                cmd.AddParameter("@code", audit.Code);

                using (var reader = cmd.ExecuteReader())
                    while (reader.Read())
                    {
                        var jsonString = JsonConvert.SerializeObject(audit, Formatting.Indented, new JsonConverter[] { new StringEnumConverter() });

                        //_logger.BeautifyLog(string.Format("Created {0} audit : {1}{2}{1}", typeof(T).FullName, Environment.NewLine, jsonString));
                    }
            }));

            return(obj);
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Called when a user wants to update his permissions.
 /// </summary>
 /// <param name="permission">
 ///     New permission: should be 2-bit string like '3' -> 0b11.
 ///     First bit allows edition. Second bit allows deletion.
 /// </param>
 /// <returns></returns>
 public async Task UpdateUserPermission(string permission)
 {
     await UserUtils.UpdateUserPermission(Context, Clients, permission);
 }
Ejemplo n.º 14
0
 public ActionResult BroadcastAdmin()
 {
     ViewBag.IsAdmin = UserUtils.GetUser().IsAdmin;
     return(View("BroadcastAdmin", "_Layout"));
 }
Ejemplo n.º 15
0
        public JsonResult ModifyModule(ContentModule entity)
        {
            var result = new JsonResult()
            {
                Data = new
                {
                    success = false,
                    message = "There as an error processing your request"
                }
            };

            if (String.IsNullOrEmpty(entity.ModuleName))
            {
                return(result);
            }

            var editedContent = Context.ContentModules.FirstOrDefault(x => x.ContentModuleId == entity.ContentModuleId);

            if (editedContent == null)
            {
                return(result);
            }

            if (editedContent.ParentContentModuleId.HasValue)
            {
                editedContent = Context.ContentModules.FirstOrDefault(x => x.ContentModuleId == editedContent.ParentContentModuleId.Value);
                if (editedContent == null)
                {
                    return(result);
                }
            }

            SaveDraft(editedContent, editedContent.CreateDate);

            editedContent.DraftAuthorName   = UserUtils.CurrentMembershipUsername();
            editedContent.CreateDate        = DateTime.UtcNow;
            editedContent.ModuleName        = ContentUtils.ScrubInput(entity.ModuleName);
            editedContent.HTMLContent       = entity.HTMLContent;
            editedContent.HTMLUnparsed      = entity.HTMLUnparsed;
            editedContent.JSContent         = entity.JSContent;
            editedContent.CSSContent        = entity.CSSContent;
            editedContent.SchemaId          = entity.SchemaId;
            editedContent.SchemaEntryValues = entity.SchemaEntryValues;
            editedContent.IsActive          = true;

            var success = Context.SaveChanges();

            if (success > 0)
            {
                CachedObjects.GetCacheContentModules(true);

                BookmarkUtil.UpdateTitle("/admin/modules/" + editedContent.ContentModuleId + "/", editedContent.ModuleName);
                result.Data = new
                {
                    success = true,
                    message = "Content saved successfully.",
                    date    = SystemTime.CurrentLocalTime.ToString("dd/MM/yyy @ h:mm tt")
                };
            }

            return(result);
        }
Ejemplo n.º 16
0
        public void RevisionHideAndUnhide()
        {
            Plug p = Utils.BuildPlugForAdmin();

            string       id       = null;
            string       path     = null;
            string       fileid   = null;
            string       filename = null;
            DreamMessage msg      = PageUtils.SavePage(p, string.Empty, PageUtils.GenerateUniquePageName(), "filerevhidetest", out id, out path);
            string       filepath = FileUtils.CreateRamdomFile(Encoding.UTF8.GetBytes("My contents."));

            FileUtils.UploadFile(p, id, "test file rev 1", out fileid, filepath);
            FileUtils.UploadFile(p, id, "test file rev 2", out fileid, filepath);
            FileUtils.UploadFile(p, id, "test file rev 3", out fileid, filepath);

            string userid;
            string username;

            UserUtils.CreateRandomUser(p, "Contributor", out userid, out username);

            //Check that anon can see contents before hiding revs
            msg = Utils.BuildPlugForUser(username).At("files", fileid, "contents").With("revision", 2).GetAsync().Wait();
            Assert.AreEqual(DreamStatus.Ok, msg.Status, "reg user can't see contents even before hiding!");

            //Reinit plug to admin
            Utils.BuildPlugForAdmin();

            string comment        = "just cuz..";
            XDoc   hideRequestXml = new XDoc("revisions").Start("file").Attr("id", fileid).Attr("hidden", true).Attr("revision", 2).End();

            msg = p.At("files", fileid, "revisions").With("comment", comment).PostAsync(hideRequestXml).Wait();
            Assert.AreEqual(DreamStatus.Ok, msg.Status, "Non 200 status hiding revisions");

            //Ensure correct revisions coming back is visible + hidden
            msg = p.At("files", fileid, "info").With("revision", 1).GetAsync().Wait();
            Assert.AreEqual(DreamStatus.Ok, msg.Status, "files/{id}/info?revision=x returned non 200 status");
            Assert.IsFalse(msg.ToDocument()["/page[@revision = \"1\"]/@hidden"].AsBool ?? false, "Rev 1 is hidden!");

            //validate hidden rev
            msg = p.At("files", fileid, "info").With("revision", 2).GetAsync().Wait();
            Assert.AreEqual(DreamStatus.Ok, msg.Status, "files/{id}/info?revision=x returned non 200 status");
            Assert.IsTrue(msg.ToDocument()["/file[@revision = \"2\"]/@hidden"].AsBool ?? false, "Rev 2 is not hidden!");
            Assert.AreEqual(comment, msg.ToDocument()["/file[@revision = \"2\"]/description.hidden"].AsText, "hide comment missing or invalid");
            Assert.IsTrue(!string.IsNullOrEmpty(msg.ToDocument()["/file[@revision = \"2\"]/date.hidden"].AsText), "date.hidden missing");
            Assert.IsNotNull(msg.ToDocument()["/file[@revision = \"2\"]/user.hiddenby/@id"].AsUInt, "user.hiddenby id missing");

            msg = p.At("files", fileid, "info").With("revision", 3).GetAsync().Wait();
            Assert.AreEqual(DreamStatus.Ok, msg.Status, "files/{id}/info?revision=x returned non 200 status");
            Assert.IsFalse(msg.ToDocument()["/file[@revision = \"3\"]/@hidden"].AsBool ?? false, "Rev 3 is hidden!");

            //Ensure admin still has rights to see hidden contents
            msg = p.At("files", fileid).With("revision", 2).GetAsync().Wait();
            Assert.AreEqual(DreamStatus.Ok, msg.Status, "admin can't see hidden contents!");

            //Ensure non-admin cannot see hidden contents
            msg = Utils.BuildPlugForUser(username).At("files", fileid).With("revision", 2).GetAsync().Wait();
            Assert.IsTrue(msg.Status == DreamStatus.Unauthorized || msg.Status == DreamStatus.Forbidden, "reg user can still see contents!");

            //Attempt to unhide a rev by non admin
            hideRequestXml = new XDoc("revisions").Start("file").Attr("id", fileid).Attr("hidden", false).Attr("revision", 2).End();
            msg            = p.At("files", fileid, "revisions").With("comment", comment).PostAsync(hideRequestXml).Wait();
            Assert.AreEqual(DreamStatus.Forbidden, msg.Status, "non admin able to unhide rev");

            //Attempt to hide a rev by non admin
            hideRequestXml = new XDoc("revisions").Start("file").Attr("id", fileid).Attr("hidden", true).Attr("revision", 1).End();
            msg            = p.At("files", fileid, "revisions").With("comment", comment).PostAsync(hideRequestXml).Wait();
            Assert.AreEqual(DreamStatus.Ok, msg.Status, "DELETE holder unable to hide rev");

            //Unhide a rev as normal user (fail!)
            hideRequestXml = new XDoc("revisions").Start("file").Attr("id", fileid).Attr("hidden", false).Attr("revision", 1).End();
            msg            = p.At("files", fileid, "revisions").With("comment", comment).PostAsync(hideRequestXml).Wait();
            Assert.AreEqual(DreamStatus.Forbidden, msg.Status, "normal user able to unhide!");

            //Reinit plug to admin
            Utils.BuildPlugForAdmin();

            //Unhide a rev as admin
            hideRequestXml = new XDoc("revisions").Start("file").Attr("id", fileid).Attr("hidden", false).Attr("revision", 1).End();
            msg            = p.At("files", fileid, "revisions").With("comment", comment).PostAsync(hideRequestXml).Wait();
            Assert.AreEqual(DreamStatus.Ok, msg.Status, "admin unable to make rev visible");

            //confirm rev 1 is visible now
            msg = p.At("files", fileid, "info").With("revision", 1).GetAsync().Wait();
            Assert.AreEqual(DreamStatus.Ok, msg.Status, "files/{id}/info?revision=x returned non 200 status");
            Assert.IsFalse(msg.ToDocument()["/file[@revision = \"1\"]/@hidden"].AsBool ?? false, "Rev 1 is still hidden!");
        }
Ejemplo n.º 17
0
        public void InvokeADMINTemplateWithUnsafeContent()
        {
            // This test contains two parts:
            // 1. Invoke template (created by admin) by ADMIN
            // 2. Invoke template by user without UNSAFECONTENT permissions
            //
            // Expected: All content (unsafe included) is present

            // Log in as ADMIN
            Plug p = Utils.BuildPlugForAdmin();

            // Create a template with unsafe content
            string       safe_content     = "<p>This is a template</p>";
            string       unsafe_content   = "<p><script type=\"text/javascript\">document.write(\"With unsafe content\");</script></p>";
            string       template_content = safe_content + unsafe_content;
            string       template_name    = "test" + DateTime.Now.Ticks.ToString();
            string       template_path    = "Template:" + template_name;
            DreamMessage msg = p.At("pages", "=" + XUri.DoubleEncode(template_path), "contents")
                               .Post(DreamMessage.Ok(MimeType.TEXT_UTF8, template_content), new Result <DreamMessage>()).Wait();

            Assert.AreEqual(DreamStatus.Ok, msg.Status, "Template page creation failed!");

            // script contents are injected with CDATA sections, so retrieve contents with injection
            msg = p.At("pages", "=" + XUri.DoubleEncode(template_path), "contents").Get(new Result <DreamMessage>()).Wait();
            template_content = msg.ToDocument()["body"].AsText ?? String.Empty;

            // There are 3 different dekiscript methods to invoke templates
            string[] template_call = new string[] { "<pre class=\"script\">Template('" + template_name + "');</pre>",
                                                    "<pre class=\"script\">Template." + template_name + "();</pre>",
                                                    "<pre class=\"script\">wiki.Template('" + template_name + "');</pre>" };

            // Create page that calls template
            string page_id;
            string page_path;

            PageUtils.CreateRandomPage(p, out page_id, out page_path);

            for (int i = 0; i < template_call.Length; i++)
            {
                // Use template_call[i] as page contents
                msg = p.At("pages", "=" + XUri.DoubleEncode(page_path), "contents")
                      .With("edittime", String.Format("{0:yyyyMMddHHmmss}", DateTime.Now))
                      .Post(DreamMessage.Ok(MimeType.TEXT_UTF8, template_call[i]), new Result <DreamMessage>()).Wait();

                // Retrieve page contents and verify it matches _all_ template content
                msg = p.At("pages", "=" + XUri.DoubleEncode(page_path), "contents").Get(new Result <DreamMessage>()).Wait();
                Assert.AreEqual(template_content, msg.ToDocument()["body"].AsText ?? String.Empty, "Unexpected contents");
            }

            // Part 2: Invoke template as user without USC permissions
            string userid;
            string username;

            msg = UserUtils.CreateRandomContributor(p, out userid, out username);
            p   = Utils.BuildPlugForUser(username, "password");

            // Check that user does not have USC permissions
            Assert.IsFalse((msg.ToDocument()["permissions.effective/operations"].AsText ?? "UNSAFECONTENT").Contains("UNSAFECONTENT"), "Created user has UNSAFECONTENT permissions");

            for (int i = 0; i < template_call.Length; i++)
            {
                // Use template_call[i] as page contents
                msg = p.At("pages", "=" + XUri.DoubleEncode(page_path), "contents")
                      .With("edittime", String.Format("{0:yyyyMMddHHmmss}", DateTime.Now))
                      .Post(DreamMessage.Ok(MimeType.TEXT_UTF8, template_call[i]), new Result <DreamMessage>()).Wait();

                // Retrieve page contents and verify it matches _all_ template content
                msg = p.At("pages", "=" + XUri.DoubleEncode(page_path), "contents").Get(new Result <DreamMessage>()).Wait();
                Assert.AreEqual(template_content, msg.ToDocument()["body"].AsText ?? String.Empty, "Unexpected contents");
            }

            // Clean up
            PageUtils.DeletePageByName(p, template_path, true);
        }
Ejemplo n.º 18
0
        internal async void ReturnMyDetails(Message message)
        {
            try
            {
                var Bot = new TelegramBot(accessToken: ConfigurationManager.AppSettings[name: "accessKey"]);

                var u = UserUtils.GetUser(chatId: message.From.Id);

                if (u.ChatId != message.Chat.Id)
                {
                    var req = new SendMessage(chatId: message.Chat.Id, text: "You are not registered");
                    await Bot.MakeRequestAsync(request : req);

                    return;
                }

                var nodes = NodeUtils.GetNodeByUser(chatId: message.From.Id);

                var accounts = AccountUtils.GetAccountByUser(chatId: message.From.Id);

                List <string> accountString;
                List <string> ips = new List <string>();
                try
                {
                    var client = new AccountClient(Con);

                    if (nodes.Count > 0)
                    {
                        ips = nodes.Select(selector: n => ("Alias: " + n.Alias +
                                                           "\nIP: " + n.IP +
                                                           "\nDeposit address: \n" + (accounts.All(predicate: e => e.EncodedAddress != n.DepositAddress) ? "[ACCOUNT UNREGISTERED] " : "") + StringUtils.GetResultsWithHyphen(n.DepositAddress) +
                                                           "\nBalance: " + client.EndGetAccountInfo(client.BeginGetAccountInfoFromAddress(n.DepositAddress)).Account.Balance / 1000000 +
                                                           "\nTransactions check: " + AccountUtils.GetAccount(add: n.DepositAddress, user: message.Chat.Id).CheckTxs +
                                                           "\nHarvesting check: " + AccountUtils.GetAccount(add: n.DepositAddress, user: message.Chat.Id).CheckBlocks +
                                                           "\nhttps://supernodes.nem.io/details/" + n.SNodeID +
                                                           "\nhttp://explorer.ournem.com/#/s_account?account=" + n.DepositAddress + "\n\n")).ToList();
                    }

                    var req = new SendMessage(chatId: message.Chat.Id, text: "**Your registered nodes with associated accounts**");

                    await Bot.MakeRequestAsync(request : req);

                    foreach (var s in ips)
                    {
                        req = new SendMessage(chatId: message.Chat.Id, text: s);

                        await Bot.MakeRequestAsync(request : req);
                    }


                    var a = accounts.Select(selector: acc => acc.EncodedAddress).ToList();

                    req = new SendMessage(chatId: message.Chat.Id, text: "**Your registered accounts**");

                    if (a.Count > 0)
                    {
                        await Bot.MakeRequestAsync(request : req);
                    }

                    accountString = a.Select(selector: n =>
                                             "\nAccount address: \n" + StringUtils.GetResultsWithHyphen(n) +
                                             "\nBalance: " + client.EndGetAccountInfo(client.BeginGetAccountInfoFromAddress(n)).Account.Balance / 1000000 +
                                             "\nTransactions check: " + AccountUtils.GetAccount(add: n, user: message.Chat.Id).CheckTxs +
                                             "\nHarvesting check: " + AccountUtils.GetAccount(add: n, user: message.Chat.Id).CheckBlocks +
                                             "\nhttp://explorer.ournem.com/#/s_account?account=" + n + "\n\n").ToList();
                }
                catch (Exception e)
                {
                    Console.WriteLine(value: e);

                    accountString = new List <string> {
                        "Sorry something went wrong, please try again. Possibly your node could be offline."
                    };
                }

                foreach (var s in accountString)
                {
                    var reqAction = new SendMessage(chatId: message.Chat.Id, text: s);

                    await Bot.MakeRequestAsync(request : reqAction);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 19
0
        internal void ManageNodes(Chat chat, string text)
        {
            var Bot = new TelegramBot(accessToken: ConfigurationManager.AppSettings[name: "accessKey"]);

            // if the user is not known, add the user to the database
            if (UserUtils.GetUser(chatId: chat.Id)?.ChatId == null)
            {
                // add user based on their chat ID
                UserUtils.AddUser(userName: chat.Username, chatId: chat.Id);

                // declare message
                var msg1 = "You have been automatically registered, one moment please";

                // send message notifying they have been registered
                var reqAction1 = new SendMessage(chatId: chat.Id, text: msg1);

                // send message
                Bot.MakeRequestAsync(request: reqAction1);
            }

            // set up regex pattern matching sequences.
            var ip  = new Regex(pattern: @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");
            var ip2 = new Regex(pattern: @"[a-zA-Z0-9]{1,20}\.[a-zA-Z0-9]{1,20}\.[a-zA-Z0-9]{1,20}");
            var ip3 = new Regex(pattern: @"[a-zA-Z0-9]{1,20}\.[a-zA-Z0-9]{1,20}");

            // scan list of submitted ip's for any valid sequences
            var result = ip.Matches(input: text).Cast <Match>().Select(selector: m => m.Value)
                         .Concat(second: ip2.Matches(input: text).Cast <Match>().Select(selector: m => m.Value))
                         .Concat(second: ip3.Matches(input: text).Cast <Match>().Select(selector: m => m.Value)).ToArray();



            // declare a nodeClient to retrieve node data.
            var snodeClient = new SupernodeClient();

            // get a list of all supernodes
            snodeClient.BeginGetSupernodes(ar =>
            {
                try
                {
                    // check submitted list against the list of all supernodes
                    var validNodes = new SupernodeResponseData.Supernodes()
                    {
                        data = new List <SupernodeResponseData.Nodes>()
                    };

                    foreach (string userIp in result)
                    {
                        foreach (var node in ar.Content.data)
                        {
                            if (userIp != node.ip)
                            {
                                continue;
                            }

                            if (node.payoutAddress == null)
                            {
                                var bot = new TelegramBot(accessToken: ConfigurationManager.AppSettings[name: "accessKey"]);
                                var req = new SendMessage(chatId: chat.Id, text: "One of the nodes you have submitted is invalid, or has not been accepted into the supernode program yet, or it has not recieved its first payment. The invalid node was node registered. Please check your nodes and try again");

                                bot.MakeRequestAsync(request: req);

                                continue;
                            }

                            validNodes.data.Add(item: node);
                        }
                    }

                    // if the user wants to register a node
                    if (text.StartsWith(value: "/registerNode:") && text != "/registerNode:")
                    {
                        // automatically add the deposit account of each registered node as a monitored account
                        // nodes must be cross referenced with total supernode list to acquire the deposit address
                        // as the supernode API doesnt contain this information
                        string msg1;
                        try
                        {
                            AccountUtils.AddAccount(
                                chatId: chat.Id,
                                accounts: ar.Content.data.Where(predicate: x => validNodes.data.Any(predicate: y => y.ip == x.ip)).ToList()
                                .Select(selector: node => node.payoutAddress).ToList());

                            var nodesAdded = NodeUtils.AddNode(chatId: chat.Id, nodes: validNodes);


                            // return a message showing which accounts were registered
                            msg1 = ar.Content.data.Count > 0
                                ? nodesAdded.data.Aggregate(seed: "Nodes registered: \n \n", func: (current, n) => current + n.ip + "\n")
                                : "No nodes were added. It/they may be offline or have an invalid IP. Check your node ip's and try again";

                            // send message
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(value: e);
                            msg1 = "Something went wrong, please try again.";
                        }

                        var reqAction1 = new SendMessage(chatId: chat.Id, text: msg1);

                        Bot.MakeRequestAsync(request: reqAction1);
                    }

                    // if a user wants to unregister an account
                    if (text.StartsWith(value: "/unregisterNode:") && text != "/unregisterNode:")
                    {
                        string msg2;
                        try
                        {
                            // declare message assuming nothing goes wrong
                            msg2 = result.Length > 1 ? "Your nodes were removed" : "Your node was removed";

                            // make sure the user is registered
                            if (UserUtils.GetUser(chatId: chat.Id)?.ChatId != chat.Id)
                            {
                                // if not, tell them
                                var reqAction3 = new SendMessage(chatId: chat.Id, text: "You are not registered");
                                Bot.MakeRequestAsync(request: reqAction3);
                                return;
                            }

                            // get all user nodes
                            var userNodes = NodeUtils.GetNodeByUser(chatId: chat.Id);

                            // delete any nodes submitted
                            NodeUtils.DeleteNode(chatId: chat.Id, nodes: result.ToList());

                            // delete any associated deposit accounts that would have been automatically registered

                            AccountUtils.DeleteAccount(chatId: chat.Id,
                                                       accounts: userNodes.Where(predicate: y => AccountUtils.GetAccountByUser(chatId: chat.Id)
                                                                                 .Any(predicate: x => x.EncodedAddress == y.DepositAddress))
                                                       .Where(predicate: y => result.Any(predicate: x => x == y.IP))
                                                       .Select(selector: acc => acc.DepositAddress).ToList());
                        }
                        catch (Exception)
                        {
                            msg2 = "Something went wrong. Please try again. If the problem persists, please notify kodtycoon";
                        }

                        // send a message to notify user of any changes
                        var reqAction2 = new SendMessage(chatId: chat.Id, text: msg2);
                        Bot.MakeRequestAsync(request: reqAction2);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace);
                }
            }, 1);
        }
Ejemplo n.º 20
0
        public void SiteFeed_SetPageToPrivatePublic_AddRemoveGrant_CorrectFeedData()
        {
            // Log in as ADMIN
            Plug         p = Utils.BuildPlugForAdmin();
            DreamMessage msg;

            // Create a page
            string id;
            string path;

            PageUtils.CreateRandomPage(p, out id, out path);

            // Create a user to give and remove grant
            string userid;
            string username;

            UserUtils.CreateRandomContributor(p, out userid, out username);

            // Grant permissions to give user
            const string GRANT_ROLE = "contributor";

            // Variable security related feed entries
            string comment = String.Empty;
            int    type    = 0;


            for (int i = 0; i < (int)sec_ops.SET_PUBLIC; i++)
            {
                switch (i)
                {
                case (int)sec_ops.SET_PRIVATE:
                    // Set page to private
                    XDoc securityDoc = new XDoc("security")
                                       .Start("permissions.page")
                                       .Elem("restriction", "Private")
                                       .End();
                    msg = p.At("pages", id, "security").Post(securityDoc, new Result <DreamMessage>()).Wait();
                    Assert.AreEqual(DreamStatus.Ok, msg.Status, "Setting page to private failed!");
                    comment = "page restriction set to Private";
                    type    = 56;  // PAGE_RESTRICTION = 56
                    break;

                case (int)sec_ops.ADD_GRANT:
                    // Add grant to user
                    securityDoc = new XDoc("security")
                                  .Start("grants.added")
                                  .Start("grant")
                                  .Start("permissions")
                                  .Elem("role", GRANT_ROLE)
                                  .End()
                                  .Start("user")
                                  .Attr("id", userid)
                                  .End()
                                  .End()
                                  .End();
                    msg = p.At("pages", id, "security").Post(securityDoc, new Result <DreamMessage>()).Wait();
                    Assert.AreEqual(DreamStatus.Ok, msg.Status, "Adding user grant failed!");
                    comment = username + " has been added as " + GRANT_ROLE;
                    type    = 54;  // ADD_GRANT = 54
                    break;

                case (int)sec_ops.REMOVE_GRANT:
                    // Remove grant from user
                    securityDoc = new XDoc("security")
                                  .Start("grants.removed")
                                  .Start("grant")
                                  .Start("permissions")
                                  .Elem("role", GRANT_ROLE)
                                  .End()
                                  .Start("user")
                                  .Attr("id", userid)
                                  .End()
                                  .End()
                                  .End();
                    msg = p.At("pages", id, "security").Post(securityDoc, new Result <DreamMessage>()).Wait();
                    Assert.AreEqual(DreamStatus.Ok, msg.Status, "Removing user grant failed!");
                    comment = username + " has been revoked as " + GRANT_ROLE;
                    type    = 55;  // REMOVE_GRANT = 55
                    break;

                case (int)sec_ops.SET_PUBLIC:
                    // Set page back to public
                    securityDoc = new XDoc("security")
                                  .Start("permissions.page")
                                  .Elem("restriction", "Public")
                                  .End();
                    msg = p.At("pages", id, "security").Post(securityDoc, new Result <DreamMessage>()).Wait();
                    Assert.AreEqual(DreamStatus.Ok, msg.Status, "Setting page to public failed!");
                    comment = "page restriction set to Public";
                    type    = 56;  // PAGE_RESTRICTION = 56
                    break;

                default:
                    break;
                }

                // Retrieve feed entry
                msg = p.At("site", "feed").With("format", "rawdaily").With("limit", 1).GetAsync().Wait();
                Assert.AreEqual(DreamStatus.Ok, msg.Status, "Feed retrieval failed!");

                // Run checks

                int pageid = System.Convert.ToInt32(id);

                rc_id_check(msg);
                rc_comment_check(msg, comment);
                rc_cur_id_check(msg, pageid);
                rc_last_oldid_check(msg, 0);
                rc_this_oldid_check(msg, 0);
                rc_namespace_check(msg, 0);
                rc_timestamp_check(msg);
                rc_title_check(msg, path);
                rc_type_check(msg, type);
                rc_moved_to_ns_check(msg, 0);
                rc_moved_to_title_check(msg, String.Empty);
                rc_user_name_check(msg, USERNAME);
                rc_full_name_check(msg, String.Empty);
                rc_page_exists_check(msg, 1);
                rc_revision_check(msg, 1);
                cmnt_deleted_check(msg, 0);
                old_is_hidden_check(msg, false);
                rc_prev_revision_check(msg, 1);
                rc_summary_check(msg, "Edited once by " + USERNAME);
            }
        }
Ejemplo n.º 21
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!(Session["Email"] != null && Session["AuthToken"] != null && Request.Cookies["AuthToken"] != null))
            {
                Response.Redirect("~/Login.aspx", false);
                return;
            }

            if (!Session["AuthToken"].ToString().Equals(Request.Cookies["AuthToken"].Value))
            {
                Response.Redirect("~/Login.aspx", false);
                return;
            }

            if (UserUtils.AccountAgeMinute(Session["Email"].ToString()) >= 15)
            {
                Response.Redirect("~/AccountSettings.aspx");
                return;
            }

            // obtain the credit card information and decrypt
            byte[] ccNo     = null;
            byte[] ccExpiry = null;
            byte[] ccCVV    = null;

            // t-sql query string
            string queryString = "SELECT [CCNo], [CCExpiry], [CCCVV], [IV], [Key] FROM dbo.[Users] WHERE Email = @Email;";

            using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MYDBConnection"].ConnectionString))
            {
                // Create the Command and Parameter objects.
                SqlCommand command = new SqlCommand(queryString, connection);
                command.Parameters.AddWithValue("@Email", Session["Email"].ToString());

                // Open the connection in a try/catch block.
                // Create and execute the DataReader, writing the result
                // set to the console window.
                try
                {
                    connection.Open();
                    SqlDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        IV       = Convert.FromBase64String(reader["IV"].ToString());
                        Key      = Convert.FromBase64String(reader["Key"].ToString());
                        ccNo     = Convert.FromBase64String(reader["CCNo"].ToString());
                        ccExpiry = Convert.FromBase64String(reader["CCExpiry"].ToString());
                        ccCVV    = Convert.FromBase64String(reader["CCCVV"].ToString());
                    }
                    reader.Close();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            lbl_ccNo.Text     = decryptData(ccNo);
            lbl_ccExpiry.Text = decryptData(ccExpiry);
            lbl_ccCVV.Text    = decryptData(ccCVV);
        }
Ejemplo n.º 22
0
        public ActionResult Edit(int userId, EditUserModel model)
        {
            var user = new UserEntity(userId);

            if (user.IsNew)
            {
                throw new HttpException(404, SharedRes.Error.NotFound_User);
            }

            if (!RoleUtils.IsUserServiceAdmin() && !RoleUtils.IsUserOrgAdmin())
            {
                throw new HttpException(401, SharedRes.Error.Unauthorized_UserEdit);
            }

            if (RoleUtils.IsUserOrgAdmin() && user.OrganizationId != Membership.GetUser().GetUserId().OrganizationId)
            {
                throw new HttpException(401, SharedRes.Error.Unauthorized_OrganizationEdit);
            }

            if (ModelState.IsValid)
            {
                // Validate submitted role.
                if (!model.Role.HasValue || !(OrganizationUtils.GetAllowedRoles(model.OrganizationId).Any(r => r.RoleId == model.Role)))
                {
                    throw new HttpException(417, ControllerRes.Account.Invalid_RoleSpecified);
                }

                // Locations are only valid for non-admin users.
                bool isAdmin = RoleUtils.IsRoleForAdmin(model.Role.Value);
                if (!isAdmin)
                {
                    // Validate submitted locations are locations of the organization.
                    if (model.Locations.Except(new LinqMetaData().Location.Where(l => l.OrganizationId == model.OrganizationId).Select(l => l.LocationId).ToList()).Any())
                    {
                        throw new HttpException(404, SharedRes.Error.NotFound_Location);
                    }
                }

                // Set flag to indicate whether or not it's a pending registration.
                // Not using the posted back value in the model for security reasons.
                bool isPendingRegistration = user.UserAccountRestrictions.Count > 0 && user.UserAccountRestrictions[0].AccountRestriction.AccountRestrictionType == AccountRestrictionType.NewUser;

                // If not pending registration and username changed, validate username is unique.
                // Also, set flag to indicate if it's the current user changing own username.
                bool isCurrentUsernameChange = false;
                if (!isPendingRegistration && user.Username != model.UserName)
                {
                    if (UserUtils.IsUsernameUsed(model.UserName))
                    {
                        throw new HttpException(417, ControllerRes.Account.Invalid_DuplicateUsername);
                    }

                    isCurrentUsernameChange = Membership.GetUser().GetUserId().Id == userId;
                }

                // Set flag to indicate whether or not the email address in a registration
                // has changed.
                bool isRegistrationChange = isPendingRegistration && user.EmailAddress != model.EmailAddress;

                Transaction transaction = new Transaction(IsolationLevel.ReadCommitted, "user add");

                try
                {
                    transaction.Add(user);

                    // Username is empty in pending registrations and can't be changed.
                    // And current user username change isn't a simple change; don't do here.
                    if (!isPendingRegistration && !isCurrentUsernameChange)
                    {
                        user.Username = model.UserName;
                    }

                    user.EmailAddress = model.EmailAddress;
                    user.FirstName    = model.FirstName;
                    user.LastName     = model.LastName;

                    if (RoleUtils.IsUserServiceAdmin())
                    {
                        user.IsActive = model.IsActive;
                    }

                    // Did role change?
                    if (user.Roles.Count == 0 || user.Roles[0].RoleId != model.Role.Value)
                    {
                        user.Roles.DeleteMulti();
                        var userRole = user.Roles.AddNew();
                        userRole.RoleId = model.Role.Value;
                    }

                    int[] newLocations = new int[0];
                    int[] oldLocations;

                    if (!isAdmin)
                    {
                        // User is not an admin. So find the set of locations user has been added to,
                        // and the set of location user has been removed from.
                        newLocations = model.Locations.Except(user.UserAssignedLocations.Select(l => l.LocationId)).ToArray();
                        oldLocations = user.UserAssignedLocations.Select(l => l.LocationId).Except(model.Locations).ToArray();
                    }
                    else
                    {
                        // User is admin. So user will be removed from all locations (admins aren't
                        // assigned to locations).
                        oldLocations = user.UserAssignedLocations.Select(l => l.LocationId).ToArray();
                    }

                    if (oldLocations.Length > 0)
                    {
                        user.UserAssignedLocations.DeleteMulti(UserAssignedLocationFields.UserId == user.UserId & UserAssignedLocationFields.LocationId == oldLocations);
                    }

                    if (newLocations.Length > 0)
                    {
                        foreach (var loc in newLocations)
                        {
                            var assignedLocation = user.UserAssignedLocations.AddNew();
                            assignedLocation.LocationId = loc;
                        }
                    }

                    // If the registration email has changed, update the email address in the account
                    // restriction.
                    if (isRegistrationChange)
                    {
                        user.UserAccountRestrictions[0].AccountRestriction.EmailAddress = model.EmailAddress;
                    }

                    // Is current user changing own username?
                    if (isCurrentUsernameChange)
                    {
                        // Changing the current user's username requres special handling because the
                        // forms-auth cookies must be updated with the new username. The delegate will
                        // be invoked to save the new username updating the datbase. In this case, it
                        // needs to be done within the transaction created here.
                        //
                        // Have already validated the username as unique. So the only reason for this
                        // to fail is with some exception thrown, which will be handled in the "catch".
                        Membership.GetUser().ChangeUsername(model.UserName,
                                                            delegate(string username)
                        {
                            user.Username = username;
                            user.Save(true);
                            // ReSharper disable AccessToDisposedClosure
                            transaction.Commit();
                            // ReSharper restore AccessToDisposedClosure
                        });
                    }
                    else
                    {
                        user.Save(true);
                        transaction.Commit();
                    }
                }
                catch (Exception)
                {
                    transaction.Rollback();
                    throw new HttpException(500, SharedRes.Error.Error_DatabaseUnknown);
                }
                finally
                {
                    transaction.Dispose();
                }

                // If registration email has changed, need to re-send the registration email.
                if (isRegistrationChange)
                {
                    SendRegistrationEmail(model, user.UserAccountRestrictions[0].AccountRestriction.RestrictionKey);
                }
            }

            return((Request.IsAjaxRequest() || ControllerContext.IsChildAction)
                                           ? (ActionResult) new EmptyResult()
                                           : View(GetEditModel(userId)));
        }
 public Lobby Get(string id)
 {
     if (id == "0")
     {
         if (Variables.Lobby != null)
         {
             lock (Variables.LobbyPlayers) {
                 LobbyUtils.CalculateLobbyPlayerFieldColors();
                 Variables.Lobby.Players  = Variables.LobbyPlayers.OrderBy(lp => lp.Position);
                 Variables.Lobby.SLobbyId = Variables.Lobby.LobbyId.ToString();
                 foreach (var player in Variables.Lobby.Players)
                 {
                     player.SSteamId = player.SteamId.ToString();
                 }
                 return(Variables.Lobby);
             }
         }
         else
         {
             return(null);
         }
     }
     else
     {
         var longLobbyId  = ulong.Parse(id);
         var runningLobby = _repository.Lobbies.Include(l => l.Players).ThenInclude(ls => ls.User).FirstOrDefault(l => l.LobbyId == longLobbyId);
         var lobby        = new Commons.Models.Lobby {
             LobbyId  = runningLobby.LobbyId,
             SLobbyId = runningLobby.LobbyId.ToString(),
             GameType = runningLobby.GameType,
             Name     = runningLobby.Name,
             Ranked   = runningLobby.Ranked,
             Players  = runningLobby.Players.Where(p => p.Position > 0).OrderBy(p => p.Position).Select(p => new Player {
                 Name        = p.Name,
                 SteamId     = p.User != null ? p.User.SteamId : 0,
                 SSteamId    = p.User?.SteamId.ToString(),
                 LobbySlotId = p.Id,
                 Position    = p.Position,
                 Rank        = runningLobby.Ranked == 2 ? p.RankDM : p.RankRM,
                 RankRM      = p.RankRM,
                 RankDM      = p.RankDM,
                 Profile     = p.User != null ? new PlayerProfile {
                     Location           = p.User.Location,
                     ProfileDataFetched = p.User.ProfileDataFetched,
                     ProfilePrivate     = p.User.ProfilePrivate
                 } : null,
                 ReputationStats = p.User != null ? new PlayerReputationStats {
                     Games = p.User.Games,
                     PositiveReputation = p.User.PositiveReputation,
                     NegativeReputation = p.User.NegativeReputation
                 } : null,
                 GameStats = p.User != null ? UserUtils.GetGameStats(p.GamesStartedRM, p.GamesStartedDM, p.GamesWonRM, p.GamesWonDM, p.GamesEndedRM, p.GamesEndedDM) : null,
             }).ToList()
         };
         foreach (var player in lobby.Players)
         {
             LobbyUtils.CalculateUserFieldColors(player, lobby.Ranked);
         }
         return(lobby);
     }
 }
Ejemplo n.º 24
0
        protected void btn_submit_Click(object sender, EventArgs e)
        {
            // validate fields
            if (!Validate_Fields())
            {
                return;
            }

            string email    = tb_email.Text.Trim();
            string password = tb_password.Text.Trim();

            string input_fName = tb_fName.Text.Trim();
            string input_lName = tb_lName.Text.Trim();

            string input_ccCVV = tb_ccCVV.Text.Trim();

            string newPassword        = tb_newPassword.Text.Trim();
            string confirmNewPassword = tb_confirmNewPassword.Text.Trim();

            if (!UserUtils.Exist(email))
            {
                showFeedback("Invalid email address.");
                return;
            }

            if (!UserUtils.Authenticate(email, password))
            {
                showFeedback("Sorry, with the information you've provided. We still can't verify that you're the account owner.");
                return;
            }

            string userId = null;

            string firstName = null, lastName = null;
            string cipherText = null;
            string iv         = null;
            string key        = null;

            string existPassSalt = null;
            string existPassHash = null;

            using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MYDBConnection"].ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT * FROM [dbo].[Users] WHERE Email = @Email", con))
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("@Email", email);

                    if (con.State == ConnectionState.Closed || con.State == ConnectionState.Broken)
                    {
                        con.Open();
                    }

                    SqlDataReader sdr = cmd.ExecuteReader();
                    if (sdr.Read())
                    {
                        userId = sdr["Id"].ToString();

                        firstName = sdr["FirstName"].ToString();
                        lastName  = sdr["LastName"].ToString();

                        existPassSalt = sdr["PasswordSalt"].ToString();
                        existPassHash = sdr["PasswordHash"].ToString();

                        cipherText = sdr["CCCVV"].ToString();
                        iv         = sdr["IV"].ToString();
                        key        = sdr["Key"].ToString();
                    }
                }
            }
            string plainText = DataCrypt.Decrypt(cipherText, iv, key);

            if (!(plainText.Equals(input_ccCVV) && firstName.Equals(input_fName) && lastName.Equals(input_lName)))
            {
                showFeedback("Invalid details provided.");
                return;
            }

            if (Password.ComparePasswordHash(Password.GetPasswordHash(newPassword, existPassSalt), existPassHash))
            {
                showFeedback("Your new password cannot be a password you've used before.");
                return;
            }

            Password.UpdatePassword(userId, Convert.ToBase64String(Password.GetPasswordHash(tb_newPassword.Text.Trim(), existPassSalt)));
            UserUtils.UnlockAccount(email);
            lbl_feedback.ForeColor = Color.Green;
            showFeedback("Password has been updated.");
        }
Ejemplo n.º 25
0
        public void TestEmptyDeltaCascadesNothing()
        {
            //Assumptions:
            // Role 'Contributor' exists
            // Role 'Viewer' exists
            //Actions:
            // Create User1
            // User1 is contributor /A/B and Viewer on /A
            //Expected result:
            // nothing changed

            Plug p = Utils.BuildPlugForAdmin();

            string baseTreePath = PageUtils.BuildPageTree(p);

            string       userid1 = null;
            DreamMessage msg     = UserUtils.CreateRandomContributor(p, out userid1);

            XDoc securityDoc = new XDoc("security")
                               .Start("permissions.page")
                               .Elem("restriction", "Private")
                               .End()
                               .Start("grants")
                               .Start("grant")
                               .Start("permissions")
                               .Elem("role", "Contributor")
                               .End()
                               .Start("user").Attr("id", userid1).End()
                               .End()
                               .End();

            msg = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A/B"), "security").
                  WithQuery("cascade=absolute").Put(securityDoc);
            Assert.AreEqual(DreamStatus.Ok, msg.Status);

            securityDoc = new XDoc("security")
                          .Start("permissions.page")
                          .Elem("restriction", "Private")
                          .End()
                          .Start("grants")
                          .Start("grant")
                          .Start("permissions")
                          .Elem("role", "Viewer")
                          .End()
                          .Start("user").Attr("id", userid1).End()
                          .End()
                          .End();

            msg = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A"), "security").
                  WithQuery("cascade=none").Put(securityDoc);
            Assert.AreEqual(DreamStatus.Ok, msg.Status);

            msg = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A/B"), "security").Get();
            Assert.AreEqual("Contributor", msg.ToDocument()[string.Format("grants/grant[user/@id=\"{0}\"]/permissions/role", userid1)].Contents);

            securityDoc = new XDoc("security")
                          .Start("permissions.page")
                          .Elem("restriction", "Private")
                          .End()
                          .Start("grants")
                          .Start("grant")
                          .Start("permissions")
                          .Elem("role", "Viewer")
                          .End()
                          .Start("user").Attr("id", userid1).End()
                          .End()
                          .End();

            msg = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A"), "security").
                  WithQuery("cascade=delta").Put(securityDoc);
            Assert.AreEqual(DreamStatus.Ok, msg.Status);

            msg = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A"), "security").Get();
            Assert.AreEqual("Viewer", msg.ToDocument()[string.Format("grants/grant[user/@id=\"{0}\"]/permissions/role", userid1)].Contents);

            msg = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A/B"), "security").Get();
            Assert.AreEqual("Contributor", msg.ToDocument()[string.Format("grants/grant[user/@id=\"{0}\"]/permissions/role", userid1)].Contents);
        }
Ejemplo n.º 26
0
        public ActionResult Index()
        {
            ContentViewViewModel model = null;

            //Remove query string
            var thisUri = new Uri(Request.Url.GetLeftPart(UriPartial.Path));

            // Check for content pages before returning a 404
            var title = GetPageTitle(thisUri);

            // If url has a subdirectory, try the master url list to see if it is a child page
            bool hasSubDirectory = title.Contains("/");

            if (hasSubDirectory)
            {
                model = GetSubDirectoryModel(title);
            }

            // If not a subdirectory try based on permalink / title
            if (model == null || model.ThePage == null)
            {
                model = new ContentViewViewModel {
                    ThePage = ContentLoader.GetDetailsByTitle(title)
                };
            }

            // If we found a hit, return the view, otherwise 404
            if (model.ThePage != null)
            {
                model.TheTemplate = ContentLoader.GetContentTemplate(model.ThePage.Template);
                model.PageData    = ContentUtils.GetFormattedPageContentAndScripts(model.ThePage.HTMLContent);

                if (UserUtils.UserIsAdmin())
                {
                    var userName = UserUtils.CurrentMembershipUsername();
                    var user     = Context.Users.First(usr => usr.Username == userName);

                    var pageModel         = new EditContentViewModel();
                    var editContentHelper = new EditContentHelper(Context);
                    editContentHelper.LoadContentViewById(model.ThePage.ContentPageId, pageModel);

                    pageModel.BookmarkTitle = model.ThePage.Title;
                    pageModel.IsBookmarked  =
                        Context.Bookmarks.Any(
                            bookmark =>
                            bookmark.Title == title && bookmark.Url == Request.RawUrl &&
                            bookmark.UserId == user.UserId);


                    ViewBag.PageModel = pageModel;
                }

                ViewBag.IsPage      = true;
                ViewBag.PageId      = model.ThePage.ContentPageId;
                ViewBag.IsPublished = model.ThePage.IsActive;
                ViewBag.OGType      = model.ThePage.OGType ?? "website";
                ViewBag.MetaDesc    = model.ThePage.MetaDescription ?? "";
                ViewBag.Title       = model.ThePage.Title;
                ViewBag.OGTitle     = model.ThePage.Title ?? model.ThePage.OGTitle;
                ViewBag.OGImage     = model.ThePage.OGImage ?? "";

                // Set the page Canonical Tag and OGURl
                ViewBag.Canonical = GetCanonical(model.ThePage);
                ViewBag.OGUrl     = model.ThePage.OGUrl ?? ViewBag.Canonical;

                ViewBag.Index  = model.ThePage.NoIndex ? "noindex" : "index";
                ViewBag.Follow = model.ThePage.NoFollow ? "nofollow" : "follow";

                return(View(model.TheTemplate.ViewLocation, model));
            }

            model = new ContentViewViewModel {
                ThePage = ContentLoader.GetDetailsByTitle("404")
            };

            model.TheTemplate = ContentLoader.GetContentTemplate(model.ThePage.Template);
            model.PageData    = ContentUtils.GetFormattedPageContentAndScripts(model.ThePage.HTMLContent);

            ViewBag.IsPage      = true;
            ViewBag.PageId      = model.ThePage.ContentPageId;
            ViewBag.IsPublished = model.ThePage.IsActive;
            ViewBag.Title       = model.ThePage.Title;
            ViewBag.Index       = "noindex";
            ViewBag.Follow      = "nofollow";

            HttpContext.Response.StatusCode = 404;
            Response.TrySkipIisCustomErrors = true;
            return(View(model.TheTemplate.ViewLocation, model));
        }
Ejemplo n.º 27
0
        public void TestCascadingWithSkipIfUnableToSet()
        {
            //Assumptions:
            //Actions:
            //  Create user with "Contributor" role
            //  Admin sets restriction:private on A/B
            //  User adds grant for self viewer on A/*
            //  User sets grant for self viewer on A/*
            //Expected result:
            //  User is viewer on A, A/B/C, A/B/D, A/E but no change on A/B

            Plug p = Utils.BuildPlugForAdmin();

            string baseTreePath = PageUtils.BuildPageTree(p);

            string       userid   = null;
            string       username = null;
            DreamMessage msg      = UserUtils.CreateRandomContributor(p, out userid, out username);

            XDoc securityDoc = new XDoc("security")
                               .Start("permissions.page")
                               .Elem("restriction", "Private")
                               .End();

            msg = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A/B"), "security").
                  WithQuery("cascade=none").Put(securityDoc);
            Assert.AreEqual(DreamStatus.Ok, msg.Status, "restrict /A/B to private");

            p = Utils.BuildPlugForUser(username, "password");

            securityDoc = new XDoc("security")
                          .Start("grants.added")
                          .Start("grant")
                          .Start("permissions")
                          .Elem("role", "Viewer")
                          .End()
                          .Start("user").Attr("id", userid).End()
                          .End()
                          .End();

            msg = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A"), "security").
                  WithQuery("cascade=delta").Post(securityDoc);
            Assert.AreEqual(DreamStatus.Ok, msg.Status, "grant viewer on /A/*");

            p = Utils.BuildPlugForAdmin(); // relogin as admin

            msg = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A"), "security").Get();
            Assert.AreEqual(msg.ToDocument()[string.Format("grants/grant[user/@id=\"{0}\"]/permissions/role", userid)].Contents, "Viewer", "confirm viewer grant on /A");

            msg = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A/B"), "security").Get();
            Assert.AreEqual(msg.ToDocument()["permissions.page/restriction"].Contents, "Private", "confirm private restriction on /A/B");
            Assert.AreEqual(msg.ToDocument()["grants/grant[2]"].IsEmpty, true, "confirm single grant on /A/B");

            msg = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A/B/C"), "security").Get();
            var doc = msg.ToDocument();

            Assert.AreEqual(doc[string.Format("grants/grant[user/@id=\"{0}\"]/permissions/role", userid)].Contents, "Viewer", "confirm viewer grant on /A/B/C");
            Assert.AreEqual(string.IsNullOrEmpty(doc["permissions.page/operations"].AsText), true, "confirm no available operations on /A/B/C");

            p = Utils.BuildPlugForUser(username, "password"); // relogin as user

            securityDoc = new XDoc("security")
                          .Start("permissions.page")
                          .Elem("restriction", "Private")
                          .End()
                          .Start("grants")
                          .Start("grant")
                          .Start("permissions")
                          .Elem("role", "Contributor")
                          .End()
                          .Start("user").Attr("id", userid).End()
                          .End()
                          .End();

            msg = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A"), "security").
                  WithQuery("cascade=absolute").Put(securityDoc);
            Assert.AreEqual(DreamStatus.Ok, msg.Status, "grant contributor on /A/*");

            p = Utils.BuildPlugForAdmin(); // relogin as admin

            msg = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A"), "security").Get();
            Assert.AreEqual(msg.ToDocument()[string.Format("grants/grant[user/@id=\"{0}\"]/permissions/role", userid)].Contents, "Contributor", "confirm contributor grant on /A");

            msg = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A/B"), "security").Get();
            Assert.AreEqual(msg.ToDocument()["permissions.page/restriction"].Contents, "Private", "reconfirm private restriction on /A/B");
            Assert.AreEqual(msg.ToDocument()["grants/grant[2]"].IsEmpty, true, "reconfirm single grant on /A/B");

            msg = p.At("pages", "=" + XUri.DoubleEncode(baseTreePath + "/A/B/C"), "security").Get();
            Assert.AreEqual(msg.ToDocument()[string.Format("grants/grant[user/@id=\"{0}\"]/permissions/role", userid)].Contents, "Contributor", "confirm contributor grant on /A/B/C");
            Assert.AreEqual(msg.ToDocument()["permissions.page/restriction"].Contents, "Private", "confirm private restriction on /A/B/C");
        }
        public void CourseTracker_Resident_RequiredCoursePass()
        {
            ///  1.Navigate to the login page login as a AMA staff
            UserInfo            role = UserUtils.GetUser(UserRole.Ama_Staff);
            LoginPage           LP   = Navigation.GoToLoginPage(browser);
            EducationCenterPage ED   = LP.LoginAsUser("10021373", "password");

            if (BrowserName == BrowserNames.Firefox)
            {
                Browser.WaitForElement(Bys.EducationCenterPage.GcepLnk, ElementCriteria.IsEnabled);
            }

            ///  2.click to GCEP link  navigate to Gcep page and waiting load icon disappear
            GCEPPage Gcep = ED.ClickToAdvance(ED.GcepLnk);


            string CourseTracker = Gcep.ResidentCourseTrackerLbl.Text;

            if (!CourseTracker.Contains('/'))
            {
                if (!CourseTracker.Contains("0"))
                {
                    string[] CourseTrackernotNull = CourseTracker.Split(' ');
                    int      regCoursCount        = Convert.ToInt16(CourseTrackernotNull[3]);
                }
                else
                {
                    string[] CoursetrackerwithNull = CourseTracker.Split(' ');
                    int      NoRegCourse           = Convert.ToInt16(CoursetrackerwithNull[2]);
                }
                Gcep.ClickToAdvance(Gcep.SignOutLnk);

                LP = Navigation.GoToLoginPage(browser);
                ED = LP.LoginAsUser(role.Username, role.Password);
                if (BrowserName == BrowserNames.Firefox)
                {
                    Browser.WaitForElement(Bys.EducationCenterPage.GcepLnk, ElementCriteria.IsEnabled);
                }
                Gcep = ED.ClickToAdvance(ED.GcepLnk);

                ///  3.from Gcep navigating to institution managment searching for institution looking for curriculum and if their any curriculum with the same name deleting and starting create new curriculum.
                InstitutionsPage     Instute1 = Gcep.ClickToAdvance(Gcep.InstitutionManagLnk);
                InstitutionsGCEPPage InsGcep1 = Instute1.SearchforInstitutions("Ellis Hospital");

                ProgramsPage Program1 = InsGcep1.ClickToAdvance(InsGcep1.InstitutionProgramManagmentLnk);
                Program1.UnassignCurriculum();


                CurriculumMngPage Curriculum1 = InsGcep1.ClickToAdvance(InsGcep1.InstitutionCurriculumTmpLnk);
                Curriculum1.Search("Learning111!!!");
                Curriculum1.DeleteCurriculum("Learning111!!!");
                CurriculumCoursePage CurCoursPage = Curriculum1.ClickToAdvance(Curriculum1.CreateCurriculumTemplateBtn);

                ///  4.Form course page choosing available courses from table by index
                CurCoursPage.AddOrRemoveCourses(CurCoursPage.AvailableCoursesTbl, CurCoursPage.AddSelectedBtn, 8, 9, 10, 11, 12, 13, 14, 15, 16);

                // List<string> CourseNames = new List<string>();
                List <string> CourseNames = CurCoursPage.GetTheNamesChoosenCourses();


                int CountofCoursewasAssigned = CourseNames.Count;


                ///  5. Giving the name for curriculum passing parameter from TestCase as a string
                CurCoursPage.CurriculumNameTxt.Clear();
                CurCoursPage.CurriculumNameTxt.SendKeys("Learning111!!!");

                ///  6.Saving curriculum and navigating to the pgy pages to assigne course to students
                PGYAssignmentPage PGY = CurCoursPage.ClickToAdvance(CurCoursPage.NextBtn);

                ///  7.Choosing student years to assign course by index for each course
                PGY.Grid_ClickElementWithoutTextInsideRow(PGY.CourseTbl, 1, 4);
                PGY.Grid_ClickElementWithoutTextInsideRow(PGY.CourseTbl, 2, 4);
                PGY.Grid_ClickElementWithoutTextInsideRow(PGY.CourseTbl, 3, 4);
                PGY.Grid_ClickElementWithoutTextInsideRow(PGY.CourseTbl, 4, 4);
                PGY.Grid_ClickElementWithoutTextInsideRow(PGY.CourseTbl, 5, 4);
                PGY.Grid_ClickElementWithoutTextInsideRow(PGY.CourseTbl, 6, 4);
                PGY.Grid_ClickElementWithoutTextInsideRow(PGY.CourseTbl, 7, 4);
                PGY.Grid_ClickElementWithoutTextInsideRow(PGY.CourseTbl, 8, 4);
                PGY.Grid_ClickElementWithoutTextInsideRow(PGY.CourseTbl, 9, 4);


                ///  8. Saving curriculum and navigating to curriculum management page again
                PGY.ClickToAdvance(PGY.SaveExitBtn);

                /// 9.Finding curriculum what we create and assigning to the programm
                Curriculum1.Search("Learning111!!!");
                Curriculum1.Actioncell.Click();
                AssignProgramPage Assign = Curriculum1.ClickToAdvance(Curriculum1.AssignToProgrammLnk);

                ///  10.Choosing starting date and ending date for  program  and clicking next button
                string StartingDate = Assign.ChoosingStartDate();
                string EndingDate   = Assign.ChoosingEndDate(1, "MM/d/yyyy");
                Assign.AssignProgramm();
                AssignSummaryPage Summary = Assign.ClickToAdvance(Assign.NextBtn);

                ///  11.Verifying from Assign Summary page program is displayed
                Assert.IsTrue(Summary.CreatedProgramName.Displayed);
                Assert.AreEqual((Summary.CreatedProgramName.Text), "Learning111!!!");

                ///  12.Verifying Assing confirmation test page curriculum name and starting date and ending dates are there which we choose.
                AssignConfirmationPage Confirmation = Summary.ClickToAdvance(Summary.NextBtn);
                // Assert.IsTrue(Confirmation.Grid_CellTextFound(Confirmation.ProgramSummaryTbl, StartingDate + " - " + EndingDate));
                Thread.Sleep(0500);
                Confirmation.ConfirmBtn.Click();

                ///  13.Signing out and Signing in as a Resindent counting required courses from myRequiredCourses
                Curriculum1.ClickToAdvance(Curriculum1.SignOutLnk);

                Thread.Sleep(2500);
                LP   = Navigation.GoToLoginPage(browser);
                ED   = LP.LoginAsUser("10021373", "password");//10021375,10021377,21387
                Gcep = ED.ClickToAdvance(ED.GcepLnk);
                //Assert.True(Gcep.VerificationOfChoosenCoursesAssignedForResident(browser, CourseNames), "Course count are not equal");
                Thread.Sleep(2000);
                string   CourseTrackerAfterAssignment = Gcep.ResidentCourseTrackerLbl.Text;
                string[] courseword2 = CourseTrackerAfterAssignment.Split(' ');
                //string[] countofcourses1 = courseword2[2].Split('/');
                //string[] courseword = CourseTracker.Split(' ');
                int CountofcoursesOnResidentGcepaftercourseAssignment = Convert.ToInt16(courseword2[3]);

                Thread.Sleep(2000);
                int CountofcoursesOnResidentGcepaftercourseAssigmentCompleted = Convert.ToInt16(courseword2[2]);

                Thread.Sleep(2000);

                Assert.True(CountofcoursesOnResidentGcepaftercourseAssignment.Equals(CountofCoursewasAssigned));
            }
            do
            {
                ElemSet.ScrollToElement(browser, Gcep.FaceBookLnk);
            }while (!Gcep.ResidentGcepShowElectiveCourseLnk.Displayed);


            ElemSet.ScrollToElement(browser, Gcep.ResidentCourseTrackerLbl);

            CourseTestPage Course = Gcep.ResidentStartCourseOrContinue(browser, "AUTOMATION_002");


            Gcep = Course.TestPass();

            do
            {
                ElemSet.ScrollToElement(browser, Gcep.FaceBookLnk);
            }while (!Gcep.ResidentGcepShowElectiveCourseLnk.Displayed);

            Assert.IsTrue(Gcep.VerificationCourseCompletion(browser, "AUTOMATION_002", "View Certificate"), "View Certificet button not visible");

            string CourseTrackerAfterTestCompletion = Gcep.ResidentCourseTrackerLbl.Text;

            string[] courseword3 = CourseTrackerAfterTestCompletion.Split(' ');
            int      CountOfCompletedRegCourseafterPassingTest = Convert.ToInt16(courseword3[2]);

            //int some = CountofcoursesOnResidentGcepaftercourseAssigmentCompleted + 1;
            //Assert.True(CountofcoursesOnResidentGcepaftercourseAssigmentCompleted + 1 == (CountOfCompletedRegCourseafterPassingTest));
            Gcep.ClickToAdvance(Gcep.SignOutLnk);

            Thread.Sleep(2500);
            LP   = Navigation.GoToLoginPage(browser);
            ED   = LP.LoginAsUser(role.Username, role.Password);//10021375,10021377,21387
            Gcep = ED.ClickToAdvance(ED.GcepLnk);

            InstitutionsPage     Instute = Gcep.ClickToAdvance(Gcep.InstitutionManagLnk);
            InstitutionsGCEPPage InsGcep = Instute.SearchforInstitutions("Ellis Hospital");

            ProgramsPage Program = InsGcep.ClickToAdvance(InsGcep.InstitutionProgramManagmentLnk);

            Program.UnassignCurriculum();

            CurriculumMngPage Curriculum = InsGcep.ClickToAdvance(InsGcep.InstitutionCurriculumTmpLnk);

            Curriculum.Search("Learning111!!!");
            Curriculum.DeleteCurriculum("Learning111!!!");
        }
Ejemplo n.º 29
0
        public void NewPagesMovedPagesWrongRestrictions()
        {
            //Assumptions:
            //  Role 'Contributor' exist
            //Actions:
            //  Create user user1 with "Contributor" role
            //  Create user user2 with "Contributor" role
            //  Create page page1
            //  Set page1 restriction as private
            //  Set grant to page1 for user1
            //  Set page2 restriction as private
            //  Set grant to page2 for user2
            //  Move page page2 to page1
            //Expected result:
            //  List of grants didn't change for page2

            Plug p = Utils.BuildPlugForAdmin();

            string       userid1 = null;
            DreamMessage msg     = UserUtils.CreateRandomContributor(p, out userid1);

            string pageid1   = null;
            string pagename1 = null;

            msg = PageUtils.CreateRandomPage(p, out pageid1, out pagename1);

            XDoc securityDoc = new XDoc("security")
                               .Start("permissions.page")
                               .Elem("restriction", "Private")
                               .End()
                               .Start("grants")
                               .Start("grant")
                               .Start("permissions")
                               .Elem("role", "Contributor")
                               .End()
                               .Start("user").Attr("id", userid1).End()
                               .End()
                               .End();

            msg = p.At("pages", pageid1, "security").Put(securityDoc);
            Assert.IsTrue(msg.IsSuccessful, "Failed to set page to private");

            string userid2 = null;

            msg = UserUtils.CreateRandomContributor(p, out userid2);

            string pageid2   = null;
            string pagename2 = null;

            msg = PageUtils.CreateRandomPage(p, out pageid2, out pagename2);

            securityDoc = new XDoc("security")
                          .Start("permissions.page")
                          .Elem("restriction", "Private")
                          .End()
                          .Start("grants")
                          .Start("grant")
                          .Start("permissions")
                          .Elem("role", "Contributor")
                          .End()
                          .Start("user").Attr("id", userid2).End()
                          .End()
                          .End();

            msg = p.At("pages", pageid2, "security").Put(securityDoc);
            Assert.IsTrue(msg.IsSuccessful, "Failed to set page to private");

            msg = PageUtils.MovePage(p, pagename2, pagename1 + "/" + pagename2);

            msg = p.At("pages", pageid2, "security").Get();
            Assert.IsTrue(msg.IsSuccessful);

            Assert.AreEqual(msg.ToDocument()["permissions.page/restriction"].Contents, "Private");
            Assert.AreEqual(msg.ToDocument()[string.Format("grants/grant[user/@id=\"{0}\"]/permissions/role", userid2)].Contents, "Contributor");
            Assert.IsTrue(msg.ToDocument()[string.Format("grants/grant[user/@id=\"{0}\"]/permissions/role", userid1)].IsEmpty);
        }
Ejemplo n.º 30
0
        protected void Change_Password(object sender, EventArgs e)
        {
            // validate inputs
            if (!ValidateFields())
            {
                return;
            }

            if (UserUtils.AccountAgeMinute(Session["Email"].ToString()) <= 5)
            {
                showFeedback("You have previously changed your password, you may reset again after 5 minutes after previous reset.");
                return;
            }

            string email       = Session["email"].ToString();
            string password    = tb_curPassword.Text.Trim();
            string newPassword = tb_newPassword.Text.Trim();

            string pHash  = null;
            string pSalt  = null;
            string userId = null;

            string pHashNew = null;

            string queryString = "SELECT * FROM dbo.[Users] WHERE [Email] = @Email;";

            using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MYDBConnection"].ConnectionString))
            {
                // Create the Command and Parameter objects.
                SqlCommand command = new SqlCommand(queryString, connection);
                command.Parameters.AddWithValue("@Email", email);

                // Open the connection in a try/catch block.
                // Create and execute the DataReader, writing the result
                // set to the console window.
                try
                {
                    connection.Open();
                    SqlDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        pHash  = reader["PasswordHash"].ToString();
                        pSalt  = reader["PasswordSalt"].ToString();
                        userId = reader["Id"].ToString();
                    }
                    reader.Close();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            // ensure
            if (pHash != null && pSalt != null)
            {
                // ensure authentication before authorizing
                if (Password.ComparePasswordHash(Password.GetPasswordHash(password, pSalt), pHash))
                {
                    // get string hash of the new password to check and change if there are no existance of it
                    pHashNew = Convert.ToBase64String(Password.GetPasswordHash(newPassword, pSalt));

                    bool passwordHistory = false;

                    // checks in password history if password has been used before
                    // https://docs.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql?view=sql-server-ver15#a-specifying-integer-constants-for-offset-and-fetch-values
                    string qStr = "SELECT [Hash] FROM [dbo].[PasswordHistory] WHERE UserId = @UserId and Hash = @Hash ORDER BY CreatedOn DESC OFFSET 0 ROW FETCH first 2 ROWS ONLY;";
                    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MYDBConnection"].ConnectionString))
                    {
                        using (SqlDataAdapter sda = new SqlDataAdapter(qStr, con))
                        {
                            sda.SelectCommand.CommandType = CommandType.Text;
                            sda.SelectCommand.Parameters.AddWithValue("@UserId", userId);
                            sda.SelectCommand.Parameters.AddWithValue("@Hash", pHashNew);

                            DataSet da = new DataSet();
                            sda.Fill(da);
                            passwordHistory = (da.Tables[0].Rows.Count > 0);
                        }
                    }

                    if (passwordHistory)
                    {
                        showFeedback("Previously 2 old passwords cannot be used.");
                        return;
                    }

                    Password.UpdatePassword(userId, pHashNew);
                    Password.SavePasswordHashToHistory(userId, pHash);
                    showFeedback("Password has been updated.");
                    lbl_feedback.ForeColor = Color.Green;
                }
                else
                {
                    showFeedback("Current password is invalid, please try again.");
                    return;
                }
            }
        }