Beispiel #1
0
        private DateTime setUpPoll()
        {
            DateTime time = DateTime.Now.Add(timeToWait);

            PollController.AddNewPoll(userID, question, time);
            return(time);
        }
Beispiel #2
0
        public async Task NewPoll(string time, [Remainder] string pollName)
        {
            // Discord user info
            var msg       = Context.Message;
            var discordId = msg.Author.Username;

            //Set all the date time info
            var      currentTime = DateTime.Now;
            var      userTime    = DateTime.Parse(time);
            var      timeToWait  = userTime.Subtract(currentTime);
            TimeSpan timeToGo    = timeToWait;

            PollSchema pollInfo = PollController.AddNewPoll(discordId, pollName, userTime);

            // Handle the timer if its in the past
            if (timeToGo < TimeSpan.Zero)
            {
                await ReplyAsync("Time Passed Fam");
            }

            //EVENT HANDLER FOR THE TIMER REACHING THE TIME
            this.timer = new System.Threading.Timer(x =>
            {
                this.EndPollNote(pollInfo);
            }, null, timeToGo, Timeout.InfiniteTimeSpan);

            //Message to confirm the poll has been set up
            await ReplyAsync($"{discordId} has started a new poll. [id = {pollInfo.Id}] \n {pollName} \n You have until {userTime} to vote! \n Use 'votepoll [id] [yes/no]'");
        }
            public void NonInviteOnly_XTokenGuidHeader_ReturnsHeaderValueAsTokenGuid()
            {
                IDbSet <Poll>   polls   = DbSetTestHelper.CreateMockDbSet <Poll>();
                IDbSet <Ballot> ballots = DbSetTestHelper.CreateMockDbSet <Ballot>();

                var ballot = new Ballot()
                {
                    TokenGuid = TokenGuid
                };

                Poll nonInviteOnlyPoll = CreateNonInviteOnlyPoll();

                nonInviteOnlyPoll.Ballots.Add(ballot);

                ballots.Add(ballot);
                polls.Add(nonInviteOnlyPoll);

                IContextFactory contextFactory = ContextFactoryTestHelper.CreateContextFactory(polls);

                PollController controller = CreatePollController(contextFactory);

                AddXTokenGuidHeader(controller, TokenGuid);


                PollRequestResponseModel response = controller.Get(PollId);

                Assert.AreEqual(TokenGuid, response.TokenGuid);
            }
            public void NoXTokenGuidHeader_Response_Choices_ContainsVoteValueZero()
            {
                const int choiceId = 42;

                var choice = new Choice()
                {
                    Id               = choiceId,
                    Name             = "A choice",
                    Description      = "Some description",
                    PollChoiceNumber = 13
                };

                Poll poll = CreateNonInviteOnlyPoll();

                poll.Choices.Add(choice);

                IDbSet <Poll> polls = DbSetTestHelper.CreateMockDbSet <Poll>();

                polls.Add(poll);
                IDbSet <Choice> choices = DbSetTestHelper.CreateMockDbSet <Choice>();

                choices.Add(choice);

                IContextFactory contextFactory = ContextFactoryTestHelper.CreateContextFactory(polls, choices);

                PollController controller = CreatePollController(contextFactory);


                PollRequestResponseModel response = controller.Get(PollId);

                PollRequestChoiceResponseModel responseChoice = response.Choices.Single();

                Assert.AreEqual(0, responseChoice.VoteValue);
            }
        public void GetPollNewest()
        {
            var searchResultsByCategory = new Mock <IReadOnlyListBaseCore <IPollSearchResultsByCategory> >(MockBehavior.Strict);

            searchResultsByCategory.Setup(_ => _.GetEnumerator()).Returns(new List <IPollSearchResultsByCategory>().GetEnumerator());

            var pollSearchResults = new Mock <IPollSearchResults>(MockBehavior.Strict);

            pollSearchResults.SetupGet(_ => _.SearchResultsByCategory).Returns(searchResultsByCategory.Object);

            var pollSearchResultsFactory = new Mock <IObjectFactory <IPollSearchResults> >(MockBehavior.Strict);

            pollSearchResultsFactory.Setup(_ => _.Fetch(PollSearchResultsQueryType.Newest)).Returns(pollSearchResults.Object);

            var controller = new PollController();

            controller.PollSearchResultsFactory = new Lazy <IObjectFactory <IPollSearchResults> >(() => pollSearchResultsFactory.Object);
            var polls = controller.Get("newest");

            Assert.AreEqual(0, polls.Count());

            pollSearchResultsFactory.VerifyAll();
            pollSearchResults.VerifyAll();
            searchResultsByCategory.VerifyAll();
        }
            public void InviteOnly_XTokenGuidHeader_BallotInPoll_ReturnsHeaderValueAsTokenGuid()
            {
                var ballot = new Ballot()
                {
                    TokenGuid = TokenGuid
                };

                Poll poll = CreateInviteOnlyPoll();

                poll.Ballots.Add(ballot);

                IDbSet <Poll> polls = DbSetTestHelper.CreateMockDbSet <Poll>();

                polls.Add(poll);
                IDbSet <Ballot> ballots = DbSetTestHelper.CreateMockDbSet <Ballot>();

                ballots.Add(ballot);

                IContextFactory contextFactory = ContextFactoryTestHelper.CreateContextFactory(polls, ballots);

                PollController controller = CreatePollController(contextFactory);

                AddXTokenGuidHeader(controller, TokenGuid);


                controller.Get(PollId);
            }
Beispiel #7
0
        public void Delete_Poll_Failed_Check()
        {
            setUpPoll();

            Assert.That(PollController.DeletePoll(1, "test"), Is.EqualTo(false));

            File.Delete(Constants.pollPath);
        }
Beispiel #8
0
        public void Poll_Stop_Running_Check()
        {
            setUpPoll();

            Assert.That(PollController.stopPollRunning(question), Is.EqualTo(true));

            File.Delete(Constants.pollPath);
        }
Beispiel #9
0
        public void Add_Poll_Check()
        {
            setUpPoll();

            Assert.That(PollController.FindPoll(question), Is.EqualTo(true));

            File.Delete(Constants.pollPath);
        }
Beispiel #10
0
        public void Delete_Auto_Poll_Check()
        {
            setUpPoll();

            Assert.That(PollController.DeletePollEnd(question));

            File.Delete(Constants.pollPath);
        }
Beispiel #11
0
        public void GetPoll_ShouldReturnCorrectPoll()
        {
            var controller = new PollController(GetTestPoll());

            var result = controller.GetPoll(2);

            Assert.IsInstanceOfType(result, typeof(DbQuery <ActivityDTO>));
        }
Beispiel #12
0
        public void Delete_Poll_Admin_Check()
        {
            setUpPoll();

            Assert.That(PollController.DeletePoll(1, "Admin2"), Is.EqualTo(true));

            File.Delete(Constants.pollPath);
        }
        void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
        {
            if (DateTime.UtcNow.Subtract(lastPollCheck).TotalMinutes > 15)
            {
                PollController.AutoClosePolls();
                lastPollCheck = DateTime.UtcNow;
            }

            Account acc = null;

            if (Request[GlobalConst.ASmallCakeCookieName] != null)
            {
                var testAcc = Account.AccountByName(new ZkDataContext(), Request[GlobalConst.ASmallCakeLoginCookieName]);
                if (testAcc != null)
                {
                    if (AuthTools.ValidateSiteAuthToken(testAcc.Name, testAcc.Password, Request[GlobalConst.ASmallCakeCookieName]))
                    {
                        acc = testAcc;
                    }
                }
            }
            if (acc == null)
            {
                if (Request[GlobalConst.LoginCookieName] != null)
                {
                    acc = AuthServiceClient.VerifyAccountHashed(Request[GlobalConst.LoginCookieName], Request[GlobalConst.PasswordHashCookieName]);
                }
            }

            if (acc != null)
            {
                var ip = GetUserIP();
                using (var db = new ZkDataContext()) {
                    var penalty = Punishment.GetActivePunishment(acc.AccountID, ip, null, x => x.BanSite, db);
                    if (penalty != null)
                    {
                        Response.Write(string.Format("You are banned! (IP match to account {0})\n", penalty.AccountByAccountID.Name));
                        Response.Write(string.Format("Ban expires: {0} UTC\n", penalty.BanExpires));
                        Response.Write(string.Format("Reason: {0}\n", penalty.Reason));
                        Response.End();
                    }
                    else
                    {
                        HttpContext.Current.User = acc;
                        // todo replace with safer permanent cookie
                        Response.SetCookie(new HttpCookie(GlobalConst.LoginCookieName, acc.Name)
                        {
                            Expires = DateTime.Now.AddMonths(12)
                        });
                        Response.SetCookie(new HttpCookie(GlobalConst.PasswordHashCookieName, acc.Password)
                        {
                            Expires = DateTime.Now.AddMonths(12)
                        });
                    }
                }
            }
        }
Beispiel #14
0
        public void GetAllPoll_ShouldReturnAllPoll()
        {
            var testPoll   = GetTestPoll();
            var controller = new PollController(testPoll);

            var result = controller.GetAllPolls() as DbQuery <ActivityDTO>;

            Assert.AreEqual(testPoll.Count, result.Count());
        }
Beispiel #15
0
        public async Task VoteOnPoll(string id, string vote)
        {
            // Discord user info
            var msg       = Context.Message;
            var discordId = msg.Author.Username;

            string hasVoted = PollController.VoteOnPoll(id, vote, discordId);

            await ReplyAsync(hasVoted);
        }
Beispiel #16
0
        public void Get_Polls_Check()
        {
            setUpPoll();

            string answer = PollController.ReurnCurrentPolls();

            Assert.AreEqual(answer, $"1, {question}?,Yes: 0, No: 0 \n");

            File.Delete(Constants.pollPath);
        }
            public void InviteOnly_XTokenGuidHeader_BallotInPoll_ReturnsPoll()
            {
                const string   pollName = "Why are we here?";
                const PollType pollType = PollType.UpDown;

                var ballot = new Ballot()
                {
                    TokenGuid = TokenGuid
                };

                var poll = new Poll()
                {
                    UUID     = PollId,
                    Name     = pollName,
                    PollType = pollType,

                    MaxPoints  = 5,
                    MaxPerVote = 1,

                    ExpiryDateUtc = null,

                    NamedVoting  = false,
                    ChoiceAdding = false,
                    InviteOnly   = true
                };

                poll.Ballots.Add(ballot);

                IDbSet <Poll> polls = DbSetTestHelper.CreateMockDbSet <Poll>();

                polls.Add(poll);
                IDbSet <Ballot> ballots = DbSetTestHelper.CreateMockDbSet <Ballot>();

                ballots.Add(ballot);
                IContextFactory contextFactory = ContextFactoryTestHelper.CreateContextFactory(polls, ballots);

                PollController controller = CreatePollController(contextFactory);

                AddXTokenGuidHeader(controller, TokenGuid);


                PollRequestResponseModel response = controller.Get(PollId);


                Assert.AreEqual(pollName, response.Name);
                Assert.AreEqual(pollType.ToString(), response.PollType);
                Assert.IsNull(response.ExpiryDateUtc);

                Assert.AreEqual(5, response.MaxPoints);
                Assert.AreEqual(1, response.MaxPerVote);

                Assert.IsFalse(response.NamedVoting);
                Assert.IsFalse(response.ChoiceAdding);
                Assert.IsFalse(response.UserHasVoted);
            }
        private static void TestPollPut(Action <Mock <IObjectFactory <IPoll> >, Poll, Mock <IPoll> > pollFactorySetup,
                                        Func <PollController, Poll, Poll> pollControllerInvocation)
        {
            var pollModel = EntityCreator.Create <Poll>(_ => _.PollOptions = null);

            var poll = new Mock <IPoll>(MockBehavior.Strict);

            poll.SetupSet(_ => _.PollCategoryID       = pollModel.PollCategoryID);
            poll.SetupSet(_ => _.PollQuestion         = pollModel.PollQuestion);
            poll.SetupSet(_ => _.PollImageLink        = pollModel.PollImageLink);
            poll.SetupSet(_ => _.PollMaxAnswers       = pollModel.PollMaxAnswers);
            poll.SetupSet(_ => _.PollMinAnswers       = pollModel.PollMinAnswers);
            poll.SetupSet(_ => _.PollStartDate        = pollModel.PollStartDate);
            poll.SetupSet(_ => _.PollEndDate          = pollModel.PollEndDate);
            poll.SetupSet(_ => _.PollAdminRemovedFlag = pollModel.PollAdminRemovedFlag);
            poll.SetupSet(_ => _.PollDateRemoved      = pollModel.PollDateRemoved);
            poll.SetupSet(_ => _.PollDeletedFlag      = pollModel.PollDeletedFlag);
            poll.SetupSet(_ => _.PollDeletedDate      = pollModel.PollDeletedDate);
            poll.SetupSet(_ => _.PollDescription      = pollModel.PollDescription);

            poll.SetupGet(_ => _.PollID).Returns(pollModel.PollID);
            poll.SetupGet(_ => _.UserID).Returns(pollModel.UserID);
            poll.SetupGet(_ => _.PollCategoryID).Returns(pollModel.PollCategoryID);
            poll.SetupGet(_ => _.PollQuestion).Returns(pollModel.PollQuestion);
            poll.SetupGet(_ => _.PollImageLink).Returns(pollModel.PollImageLink);
            poll.SetupGet(_ => _.PollMaxAnswers).Returns(pollModel.PollMaxAnswers);
            poll.SetupGet(_ => _.PollMinAnswers).Returns(pollModel.PollMinAnswers);
            poll.SetupGet(_ => _.PollStartDate).Returns(pollModel.PollStartDate);
            poll.SetupGet(_ => _.PollEndDate).Returns(pollModel.PollEndDate);
            poll.SetupGet(_ => _.PollAdminRemovedFlag).Returns(pollModel.PollAdminRemovedFlag);
            poll.SetupGet(_ => _.PollDateRemoved).Returns(pollModel.PollDateRemoved);
            poll.SetupGet(_ => _.PollDeletedFlag).Returns(pollModel.PollDeletedFlag);
            poll.SetupGet(_ => _.PollDeletedDate).Returns(pollModel.PollDeletedDate);
            poll.SetupGet(_ => _.PollDescription).Returns(pollModel.PollDescription);
            poll.SetupGet(_ => _.PollOptions).Returns(new BusinessList <IPollOption>());
            poll.Setup(_ => _.Save()).Returns(poll.Object);

            var pollFactory = new Mock <IObjectFactory <IPoll> >(MockBehavior.Strict);

            pollFactorySetup(pollFactory, pollModel, poll);

            var auth = new Mock <IMyVoteAuthentication>(MockBehavior.Strict);

            auth.Setup(_ => _.GetCurrentUserID()).Returns(pollModel.UserID);

            var controller = new PollController();

            controller.PollFactory          = new Lazy <IObjectFactory <IPoll> >(() => pollFactory.Object);
            controller.MyVoteAuthentication = auth.Object;

            var result = pollControllerInvocation(controller, pollModel);

            pollFactory.VerifyAll();
            poll.Verify();
        }
            public void InviteOnly_NoXTokenGuidHeader_ThrowsUnauthorized()
            {
                IDbSet <Poll> polls = DbSetTestHelper.CreateMockDbSet <Poll>();

                polls.Add(CreateInviteOnlyPoll());
                IContextFactory contextFactory = ContextFactoryTestHelper.CreateContextFactory(polls);

                PollController controller = CreatePollController(contextFactory);

                controller.Get(PollId);
            }
            public void XTokenGuidHeader_Response_Choices_ContainsVoteValuesForBallot()
            {
                const int choiceId = 42;

                var choice = new Choice()
                {
                    Id               = choiceId,
                    Name             = "A choice",
                    Description      = "Some description",
                    PollChoiceNumber = 13
                };

                var vote = new Vote()
                {
                    Choice = choice, VoteValue = 3
                };

                var ballot = new Ballot()
                {
                    TokenGuid = TokenGuid
                };

                ballot.Votes.Add(vote);

                Poll poll = CreateNonInviteOnlyPoll();

                poll.Ballots.Add(ballot);
                poll.Choices.Add(choice);

                IDbSet <Poll> polls = DbSetTestHelper.CreateMockDbSet <Poll>();

                polls.Add(poll);
                IDbSet <Choice> choices = DbSetTestHelper.CreateMockDbSet <Choice>();

                choices.Add(choice);
                IDbSet <Vote> votes = DbSetTestHelper.CreateMockDbSet <Vote>();

                votes.Add(vote);
                IDbSet <Ballot> ballots = DbSetTestHelper.CreateMockDbSet <Ballot>();

                ballots.Add(ballot);
                IContextFactory contextFactory = ContextFactoryTestHelper.CreateContextFactory(polls, ballots, votes, choices);

                PollController controller = CreatePollController(contextFactory);

                AddXTokenGuidHeader(controller, TokenGuid);


                PollRequestResponseModel response = controller.Get(PollId);

                PollRequestChoiceResponseModel responseChoice = response.Choices.Single();

                Assert.AreEqual(3, responseChoice.VoteValue);
            }
Beispiel #21
0
        public PollControllerTest()
        {
            var ILogger = new Mock <ILogger <PollController> >();
            ILogger <PollController> logger = ILogger.Object;

            var iPollRepository        = new Mock <IPollRepository>().Object;
            var iPollStatsRepository   = new Mock <IPollStatsRepository>().Object;
            var iPollOptionsRepository = new Mock <IPollOptionsRepository>().Object;

            _pollController = new PollController(logger, iPollRepository, iPollStatsRepository, iPollOptionsRepository);
        }
        private void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
        {
            if (DateTime.UtcNow.Subtract(lastPollCheck).TotalMinutes > 60)
            {
                PollController.AutoClosePolls(); // this is silly here, should be a seaprate timer/thread
                lastPollCheck = DateTime.UtcNow;
            }

            Account acc = null;


            if (FormsAuthentication.IsEnabled && User.Identity.IsAuthenticated)
            {
                acc = Account.AccountByName(new ZkDataContext(), User.Identity.Name);
            }
            else if (Request[GlobalConst.SessionTokenVariable] != null)
            {
                int id = 0;
                if (Global.Server?.SessionTokens.TryRemove(Request[GlobalConst.SessionTokenVariable], out id) == true)
                {
                    acc = new ZkDataContext().Accounts.Find(id);
                }
            }

            if (acc != null)
            {
                var ip        = Request.UserHostAddress;
                var lastLogin = acc.AccountUserIDs.OrderByDescending(x => x.LastLogin).FirstOrDefault();
                var userID    = lastLogin?.UserID;
                var installID = lastLogin?.InstallID;
                var penalty   = Punishment.GetActivePunishment(acc.AccountID, ip, userID, installID, x => x.BanSite);
                if (penalty != null)
                {
                    Response.Write(string.Format("You are banned! (IP match to account {0})\n", penalty.AccountByAccountID.Name));
                    Response.Write(string.Format("Ban expires: {0} UTC\n", penalty.BanExpires));
                    Response.Write(string.Format("Reason: {0}\n", penalty.Reason));
                    Response.End();
                }
                else
                {
                    HttpContext.Current.User = acc;
                    FormsAuthentication.SetAuthCookie(acc.Name, true);
                }
            }

            // remove cake from URL
            var removeCake = Regex.Replace(Request.Url.ToString(), $"([?|&])({GlobalConst.SessionTokenVariable}=[^&?]+[?|&]*)", m => m.Groups[1].Value);

            if (removeCake != Request.Url.ToString())
            {
                Response.Redirect(removeCake, true);
            }
        }
            public void NonExistentPoll_ThrowsNotFound()
            {
                Guid unknownPollId = new Guid("0D5C94A2-F219-4327-9EED-4DCE2ECFAB6A");

                IDbSet <Poll>   polls          = DbSetTestHelper.CreateMockDbSet <Poll>();
                IContextFactory contextFactory = ContextFactoryTestHelper.CreateContextFactory(polls);

                PollController controller = CreatePollController(contextFactory);


                controller.Get(unknownPollId);
            }
        public void setup()
        {
            _redChoice = new Choice()
            {
                Name = "Red"
            };

            UUIDs     = new[] { Guid.NewGuid(), Guid.NewGuid(), _templateUUID, Guid.NewGuid() };
            _mainPoll = new Poll()
            {
                UUID = UUIDs[0], ManageId = Guid.NewGuid()
            };
            _otherPoll = new Poll()
            {
                UUID = UUIDs[1], ManageId = Guid.NewGuid()
            };

            _templateUUID        = Guid.NewGuid();
            _templateCreatedDate = DateTime.UtcNow.AddDays(-5);
            _templatePoll        = new Poll()
            {
                UUID           = _templateUUID,
                ManageId       = Guid.NewGuid(),
                CreatedDateUtc = _templateCreatedDate,
                Choices        = new List <Choice>()
                {
                    _redChoice
                },
                CreatorIdentity = UserId
            };

            _dummyPolls = new InMemoryDbSet <Poll>(true)
            {
                _mainPoll, _otherPoll, _templatePoll
            };

            var mockContextFactory = new Mock <IContextFactory>();
            var mockContext        = new Mock <IVotingContext>();

            mockContextFactory.Setup(a => a.CreateContext()).Returns(mockContext.Object);
            mockContext.Setup(a => a.Polls).Returns(_dummyPolls);
            mockContext.Setup(a => a.SaveChanges()).Callback(SaveChanges);

            _metricHandler = new Mock <IMetricHandler>();

            _controller = new PollController(mockContextFactory.Object, _metricHandler.Object, new Mock <ICorrespondenceService>().Object)
            {
                Request       = new HttpRequestMessage(),
                Configuration = new HttpConfiguration()
            };
        }
            public void NonInviteOnly_XTokenGuidHeader_BallotNotInPoll_ThrowsNotFound()
            {
                IDbSet <Poll> polls = DbSetTestHelper.CreateMockDbSet <Poll>();

                polls.Add(CreateNonInviteOnlyPoll());
                IContextFactory contextFactory = ContextFactoryTestHelper.CreateContextFactory(polls);

                PollController controller = CreatePollController(contextFactory);

                AddXTokenGuidHeader(controller, TokenGuid);


                controller.Get(PollId);
            }
            public void InviteOnly_NoXTokenGuidHeader_DoesNotCreateBallot()
            {
                IDbSet <Poll> polls = DbSetTestHelper.CreateMockDbSet <Poll>();

                polls.Add(CreateInviteOnlyPoll());
                IDbSet <Ballot> ballots        = DbSetTestHelper.CreateMockDbSet <Ballot>();
                IContextFactory contextFactory = ContextFactoryTestHelper.CreateContextFactory(polls, ballots);

                PollController controller = CreatePollController(contextFactory);

                controller.Get(PollId);

                Assert.AreEqual(0, ballots.Count());
            }
Beispiel #27
0
        public async Task CurrentPolls()
        {
            // Search the db for current reminders (active)
            string currentPolls = PollController.ReurnCurrentPolls();

            if (currentPolls == "")
            {
                await ReplyAsync("There are no active Polls!");
            }
            else
            {
                await ReplyAsync(currentPolls);
            }
        }
            public void NonInviteOnly_MultipleXTokenGuidHeader_ThrowsBadRequest()
            {
                IDbSet <Poll> polls = DbSetTestHelper.CreateMockDbSet <Poll>();

                polls.Add(CreateNonInviteOnlyPoll());
                IContextFactory contextFactory = ContextFactoryTestHelper.CreateContextFactory(polls);

                PollController controller = CreatePollController(contextFactory);

                AddXTokenGuidHeader(controller, TokenGuid);
                AddXTokenGuidHeader(controller, TokenGuid);


                controller.Get(PollId);
            }
Beispiel #29
0
        public void Vote_Poll_No_Check()
        {
            File.Delete(Constants.pollPath);

            setUpPoll();

            string voted = PollController.VoteOnPoll("1", "no", "Admin");

            Assert.AreEqual(voted, "Thanks for the vote");

            string answer = PollController.ReurnCurrentPolls();

            Assert.AreEqual(answer, $"1, {question}?,Yes: 0, No: 1 \n");

            File.Delete(Constants.pollPath);
        }
Beispiel #30
0
        public void Vote_Poll_Failed_Check()
        {
            File.Delete(Constants.pollPath);

            setUpPoll();

            string voted = PollController.VoteOnPoll("1", "cake", "Admin");

            Assert.AreEqual(voted, "Did not update");

            string answer = PollController.ReurnCurrentPolls();

            Assert.AreEqual(answer, $"1, {question}?,Yes: 0, No: 0 \n");

            File.Delete(Constants.pollPath);
        }