Esempio n. 1
0
        public async Task <bool> TicketUsed(string hash)
        {
            var reqip = Request.HttpContext.Connection.RemoteIpAddress;
            var conf  = SetupController.GetESConfiguration(contentRootPath);
            //var acl = new List<IPAddress>();

            //if (conf.VotingSystemTicketAPI != null)
            //{
            //    var host = new Uri(conf.VotingSystemTicketAPI).Host;
            //    foreach (var a in Dns.GetHostEntry(host).AddressList)
            //    {
            //        acl.Add(a);
            //    }
            //}

            //var check = acl.FirstOrDefault(a => a.Equals(reqip));
            //if (check == default(IPAddress))
            //{
            //    Response.StatusCode = 403;
            //    return false;
            //}

            var dp        = dataProtector.CreateProtector("EligereMetadataExchange");
            var plainHash = dp.Unprotect(hash);

            var ticketq = from t in _context.VotingTicket
                          join v in _context.Voter on t.Id equals v.VotingTicketFk
                          where t.Hash == plainHash
                          select t;

            var ticket = await ticketq.FirstOrDefaultAsync();

            if (ticket == null)
            {
                throw new Exception($"Invalid ticket hash {plainHash}");
            }

            var voter = await _context.Voter.Include(v => v.ElectionFkNavigation).FirstOrDefaultAsync(v => v.VotingTicketFk == ticket.Id);

            if (ticket == null)
            {
                throw new Exception($"Internal error, inconsistent DB on ticket");
            }

            var rnd = new Random();

            voter.Vote = DateTime.Now + TimeSpan.FromMinutes(rnd.Next(10) - 5);
            await _context.SaveChangesAsync();

            return(true);
        }
Esempio n. 2
0
        public async Task <string> RunningElections()
        {
            var reqip = Request.HttpContext.Connection.RemoteIpAddress;
            var conf  = SetupController.GetESConfiguration(contentRootPath);
            var acl   = new List <IPAddress>();

            if (conf.VotingSystemTicketAPI != null)
            {
                var host = new Uri(conf.VotingSystemTicketAPI).Host;
                foreach (var a in Dns.GetHostEntry(host).AddressList)
                {
                    acl.Add(a);
                }
            }

            var check = acl.FirstOrDefault(a => a.Equals(reqip));

            if (check == default(IPAddress))
            {
                Response.StatusCode = 403;
                return(null);
            }

            var time4open  = DateTime.Now + TimeSpan.FromMinutes(15); // Early comers (should be a parameter!)
            var time4close = DateTime.Now - TimeSpan.FromMinutes(15); //Late comers (should be a parameter!)
            var electionsq = from e in _context.Election
                             where e.Active && (e.PollStartDate <= time4open) && (e.PollEndDate >= time4close)
                             select e;

            var elections = await electionsq.ToListAsync();

            var electionids = elections.ConvertAll(e => e.Id);

            // FixMe: this should be changed when multiple VS systems will be introduced
            if (elections.Count > 1 && elections.GroupBy(e => e.PollingStationGroupId).Count() > 1)
            {
                throw new Exception("Multiple elections with different PollingStationGroupIds");
            }

            var groupid = elections[0].PollingStationGroupId == null?Guid.NewGuid() : elections[0].PollingStationGroupId;

            // Ignoring name, election_scope_id, start_date, end_date, type, geopolitical_units
            var electionDescription = new ElectionGuard.ElectionDescription();

            electionDescription.ballot_styles =
                new ElectionGuard.BallotStyle[] {
                new ElectionGuard.BallotStyle()
                {
                    object_id = groupid.ToString()
                }
            };

            var partiesq = from p in _context.Party
                           join b in _context.BallotName on p.Id equals b.PartyFk
                           where electionids.Contains(b.ElectionFk)
                           select p;

            var parties = await partiesq.ToListAsync();

            if (parties.Count > 0)
            {
                var partydescs = parties.ConvertAll(p => new ElectionGuard.PartyDescription()
                {
                    object_id = p.Id.ToString(),
                    name      = new ElectionGuard.ListOfLocalizedText()
                    {
                        text = new ElectionGuard.LocalizedText[] {
                            new ElectionGuard.LocalizedText()
                            {
                                language = "it", value = p.Name
                            }
                        }
                    }
                });
                electionDescription.parties = partydescs.ToArray();
            }


            var ballotnamesq = from b in _context.BallotName
                               where electionids.Contains(b.ElectionFk)
                               select b;

            var ballotnames = await ballotnamesq.ToListAsync();

            var ballotids = new Dictionary <Guid, string>();

            electionDescription.candidates =
                ballotnames.ConvertAll(b => {
                ballotids.Add(b.Id, (b.IsCandidate.HasValue && b.IsCandidate.Value ? "*" : "") + b.Id.ToString());
                return(new ElectionGuard.Candidate()
                {
                    object_id = ballotids[b.Id],
                    ballot_name = new ElectionGuard.BallotName()
                    {
                        party_id = b.PartyFk.ToString(),
                        text = new ElectionGuard.LocalizedText[] {
                            new ElectionGuard.LocalizedText()
                            {
                                language = "it", value = b.BallotNameLabel
                            }
                        }
                    }
                });
            }).ToArray();

            var contests = new List <ElectionGuard.Contest>();
            var i        = 0;

            foreach (var e in elections)
            {
                var contest = new ElectionGuard.Contest();
                contest.object_id      = e.Id.ToString();
                contest.name           = e.Name;
                contest.sequence_order = i++;
                var config = ElectionConfiguration.FromJson(e.Configuration);
                contest.votes_allowed                    = config.NumPreferences;
                contest.number_elected                   = config.EligibleSeats;
                contest.electoral_district_id            = "https://eligere.unipi.it"; // To be added to configuration
                contest.extensions                       = new Dictionary <string, string>();
                contest.extensions["HasCandidates"]      = config.HasCandidates.ToString();
                contest.extensions["CandidatesType"]     = config.CandidatesType.ToString();
                contest.extensions["IdentificationType"] = config.IdentificationType.ToString();
                contest.extensions["PollStartDate"]      = e.PollStartDate.ToString(CultureInfo.GetCultureInfo("it-it"));
                contest.extensions["PollEndDate"]        = e.PollEndDate.ToString(CultureInfo.GetCultureInfo("it-it"));
                var ob = ballotnames.Where(b => b.ElectionFk == e.Id && b.SequenceOrder.HasValue).OrderBy(b => b.SequenceOrder).ThenBy(b => b.BallotNameLabel).ToList();
                var ub = ballotnames.Where(b => b.ElectionFk == e.Id && !b.SequenceOrder.HasValue).OrderBy(b => b.BallotNameLabel).ToList();
                ob.AddRange(ub);
                var ballotselections = new List <ElectionGuard.BallotSelection>();
                var j = 0;
                foreach (var b in ob)
                {
                    var bs = new ElectionGuard.BallotSelection();
                    bs.object_id      = ballotids[b.Id]; // Should be ok
                    bs.candidate_id   = ballotids[b.Id];
                    bs.sequence_order = j++;
                    ballotselections.Add(bs);
                }
                contest.ballot_selections = ballotselections.ToArray();
                contests.Add(contest);
            }
            electionDescription.contests = contests.ToArray();
            var sret = JsonSerializer.Serialize <ElectionGuard.ElectionDescription>(electionDescription);
            var dp   = dataProtector.CreateProtector("EligereMetadataExchange");

            return(dp.Protect(sret));
        }