Esempio n. 1
0
        public async Task <IActionResult> PutPlayer([FromRoute] Guid id, [FromBody] Player player)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != player.Id)
            {
                return(BadRequest());
            }

            _context.Entry(player).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PlayerExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
        public async Task <IActionResult> SignUp([Bind("TeamName, Password, CompetitionID")] Team team)
        {
            if (ModelState.IsValid)
            {
                //BCryptPasswordHash bCryptPasswordHash = new BCryptPasswordHash();
                var salt         = BCryptPasswordHash.GetRandomSalt();
                var hashPassword = BCryptPasswordHash.HashPassword(team.Password, salt);
                team.Password = hashPassword;
                team.Salt     = salt;
                _context.Add(team);
                //get userId
                //var userId = this.User.FindFirst(ClaimTypes.NameIdentifier).Value;
                //Migrating to new way to get user object
                var user = await _userManager.GetUserAsync(HttpContext.User);

                TeamUser teamUser = new TeamUser();
                teamUser.UserId   = user.Id;
                teamUser.UserName = user.UserName;

                teamUser.TeamId = team.TeamID;
                _context.Add(teamUser);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index", "Competitions"));
            }
            ViewData["CompetitionID"] = team.CompetitionID;
            return(View());
        }
Esempio n. 3
0
        public async Task <IActionResult> Details(int id, [Bind("ID,Name,Description,Value,Flag,CompetitionID,CompetitionCategoryID")] Challenge challenge, List <IFormFile> files)
        {
            if (id != challenge.ID)
            {
                return(NotFound());
            }

            if (files.Count != 0)
            {
                var competition = await _context.Competitions
                                  .Include(c => c.CompetitionCategories)
                                  .ThenInclude(cc => cc.Challenges)
                                  .AsNoTracking()
                                  .FirstOrDefaultAsync(m => m.ID == challenge.CompetitionID);

                var competitionCategory = await _context.CompetitionCategories
                                          .AsNoTracking()
                                          .FirstOrDefaultAsync(m => m.ID == challenge.CompetitionCategoryID);

                var temp_Challenge = await _context.Challenges
                                     .AsNoTracking()
                                     .FirstOrDefaultAsync(m => m.ID == challenge.ID);

                await DeleteFile(competition.BucketName, competitionCategory.CategoryName, temp_Challenge.FileName);

                foreach (var file in files)
                {
                    challenge.FileName = file.FileName;
                    await UploadFileToS3(file, competition.BucketName, competitionCategory.CategoryName);
                }
            }


            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(challenge);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ChallengeExists(challenge.ID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction("Index", "Challenges", new { id = challenge.CompetitionID }));
            }
            return(View(challenge));
        }
        public async Task <IActionResult> Create([Bind("ID,CategoryName")] CategoryDefault categoryDefault)
        {
            if (ModelState.IsValid)
            {
                _context.Add(categoryDefault);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(categoryDefault));
        }
        public async Task <IActionResult> Create([Bind("TeamID,TeamName,Password,CompetitionID")] Team team)
        //public async Task<IActionResult> Create([Bind("TeamID, TeamName, Score")] Team team)
        {
            if (ModelState.IsValid)
            {
                _context.Add(team);
                await _context.SaveChangesAsync();

                //return RedirectToAction(nameof(Index));
                return(RedirectToAction("Index", "Teams", new { id = team.CompetitionID }));
            }
            return(View(team));
            //return RedirectToAction("Index", "Teams", new { id = team.CompetitionID });
        }
Esempio n. 6
0
        public async Task <IActionResult> OmlResult([FromBody] OmlScore score)
        {
            if (!Request.Cookies.ContainsKey("judgeid"))
            {
                return(Unauthorized());
            }

            var judgeId = Request.Cookies["judgeid"];

            var teamInBase = from it in _dbContext.OMLScoreBoard
                             where it.Round == score.Round
                             where it.TeamId == score.TeamId
                             select it;

            if (!teamInBase.Any())
            {
                score.JudgeId = judgeId;
                await _dbContext.OMLScoreBoard.AddAsync(score);

                await _dbContext.SaveChangesAsync();

                return(Ok());
            }

            var record = teamInBase.First();

            if (record.Saved == 1)
            {
                return(Forbid());
            }

            record.JudgeId          = judgeId;
            record.BlackBlockState  = score.BlackBlockState;
            record.BlueBlockState   = score.BlueBlockState;
            record.BrokenWall       = score.BrokenWall;
            record.FinishCorrectly  = score.FinishCorrectly;
            record.LiesCorrectly    = score.LiesCorrectly;
            record.LiesIncorrectly  = score.LiesIncorrectly;
            record.None             = score.None;
            record.PartiallyCorrect = score.PartiallyCorrect;
            record.Saved            = score.Saved;
            record.StaysCorrectly   = score.StaysCorrectly;
            record.StaysIncorrectly = score.StaysIncorrectly;
            record.TimeMils         = score.TimeMils;
            await _dbContext.SaveChangesAsync();

            return(Ok());
        }
        public async Task <IActionResult> StartNewRound(string category)
        {
            if (!Request.Headers.ContainsKey("token"))
            {
                return(BadRequest(ScoreBoardPostError.TokenNotPassed));
            }
            var token = Request.Headers["token"][0];

            var payload = JWTJudgeProvider.DecodeToken(token);

            if (payload == null)
            {
                return(BadRequest(ScoreBoardPostError.InvalidToken));
            }

            if (payload.Status != "admin")
            {
                return(BadRequest(ScoreBoardPostError.AccessDenied));
            }

            var roundQuery = from tRound in _dbContext.Rounds
                             where tRound.Category == category
                             orderby tRound.Round
                             select tRound;

            foreach (var round in roundQuery)
            {
                round.Current = 0;
            }

            if (!roundQuery.Any())
            {
                _dbContext.Rounds.Add(new CompetitionRound {
                    Category = category, Round = 1, Current = 1
                });
            }
            else
            {
                var lastRound = roundQuery.Last().Round;
                _dbContext.Rounds.Add(new CompetitionRound {
                    Category = category, Round = lastRound + 1, Current = 1
                });
            }

            await _dbContext.SaveChangesAsync();

            return(Ok());
        }
 public async Task <IActionResult> Edit([Bind("ID, TimeStamp, CompetitionID, TeamID, ChallengeID, TeamChallengeID, Score, PreviousHash, Hash")] Block block)
 {
     if (ModelState.IsValid)
     {
         try
         {
             _context.Update(block);
             await _context.SaveChangesAsync();
         }
         catch (DbUpdateConcurrencyException)
         {
             if (!BlockExists(block.ID))
             {
                 return(NotFound());
             }
             else
             {
                 throw;
             }
         }
         return(RedirectToAction("Index", "Blockchain", new { id = block.CompetitionID }));
     }
     return(RedirectToAction("Index", "Blockchain", new { id = block.CompetitionID }));
 }
        public async Task <IActionResult> Details([Bind("ID, Flag, CompetitionID")] Challenge challenge, int?id)
        {
            if (challenge.Flag == null)
            {
                var temp_challenge1 = await _context.Challenges
                                      .FirstOrDefaultAsync(m => m.ID == challenge.ID);

                var competition1 = await _context.Competitions.FindAsync(temp_challenge1.CompetitionID);

                string bucketName = competition1.BucketName;
                var    category   = await _context.CompetitionCategories.FindAsync(temp_challenge1.CompetitionCategoryID);

                string folderName = category.CategoryName;
                if (temp_challenge1.FileName != null)
                {
                    string fileName     = temp_challenge1.FileName;
                    Regex  pattern      = new Regex("[+]");
                    string tempFileName = pattern.Replace(fileName, "%2B");
                    tempFileName.Replace(' ', '+');
                    ViewData["FileLink"] = "https://s3-ap-southeast-1.amazonaws.com/" + bucketName + "/" + folderName + "/" + tempFileName;
                }
                ViewData["CompetitionID"] = temp_challenge1.CompetitionID;
                ViewData["ChallengeID"]   = temp_challenge1.ID;

                ViewData["Invalid"]   = true;
                ViewData["WrongFlag"] = false;
                return(View(temp_challenge1));
            }

            Team team = null;

            var competition = await _context.Competitions
                              .Include(c => c.CompetitionCategories)
                              .ThenInclude(cc => cc.Challenges)
                              .Include(c => c.Teams)
                              .ThenInclude(t => t.TeamUsers)
                              .AsNoTracking()
                              .FirstOrDefaultAsync(m => m.ID == challenge.CompetitionID);

            var userId = this.User.FindFirst(ClaimTypes.NameIdentifier).Value;

            foreach (var Team in competition.Teams)
            {
                foreach (var TeamUser in Team.TeamUsers)
                {
                    if (TeamUser.UserId.Equals(userId))
                    {
                        team = Team;
                        break;
                    }
                }
            }

            //Get all challenges this team has solved
            var teamChallengesList = await _context.Teams
                                     .Include(t => t.TeamChallenges)
                                     .AsNoTracking()
                                     .FirstOrDefaultAsync(m => m.TeamID == team.TeamID);

            foreach (var teamChallenges in teamChallengesList.TeamChallenges)
            {
                if (teamChallenges.ChallengeId == challenge.ID)
                {
                    if (teamChallenges.Solved == true)
                    {
                        return(RedirectToAction("Details", "Challenges", new { id }));
                    }
                }
            }

            var localvarchallenge = await _context.Challenges
                                    .AsNoTracking()
                                    .FirstOrDefaultAsync(m => m.ID == challenge.ID);

            //if (ModelState.IsValid)
            //{
            //    _context.Add(challenge);
            //    await _context.SaveChangesAsync();
            //    return RedirectToAction(nameof(Index));
            //}

            //if (challenge.CompetitionID == null)
            //{
            //    return NotFound();
            //}

            var temp_challenge = await _context.Challenges
                                 .FirstOrDefaultAsync(m => m.ID == challenge.ID);

            if (temp_challenge == null)
            {
                return(NotFound());
            }
            // Flag is correct
            if (challenge.Flag.Equals(temp_challenge.Flag))
            {
                //Add entry to TeamChallenge
                TeamChallenge teamChallenge = new TeamChallenge();
                teamChallenge.ChallengeId = localvarchallenge.ID;
                teamChallenge.TeamId      = team.TeamID;
                teamChallenge.Solved      = true;
                _context.Add(teamChallenge);
                await _context.SaveChangesAsync();

                //Add entry to chain
                //Block and block data
                Block block = new Block();
                block.TimeStamp       = DateTime.Now;
                block.CompetitionID   = challenge.CompetitionID;
                block.TeamID          = team.TeamID;
                block.ChallengeID     = localvarchallenge.ID;
                block.TeamChallengeID = teamChallenge.TeamChallengeID;
                block.Score           = localvarchallenge.Value;
                //Previous Hash
                Blockchain blockchain  = new Blockchain(_context);
                Block      latestBlock = await blockchain.GetLatestBlock();

                block.PreviousHash = latestBlock.Hash;
                //Current Hash
                string data = block.TimeStamp + ";" + block.CompetitionID + ";" + block.TeamID + ";" + block.ChallengeID + ";" + block.TeamChallengeID + ";" + block.Score + ";" + block.PreviousHash;
                block.Hash = GenerateSHA512String(data);

                _context.Add(block);
                await _context.SaveChangesAsync();

                //Add points to team score
                team.Score += localvarchallenge.Value;
                _context.Update(team);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index", "Challenges", new { id = challenge.CompetitionID }));
            }
            else
            {
                //Wrong flag
                TeamChallenge teamChallenge = new TeamChallenge();
                teamChallenge.ChallengeId = localvarchallenge.ID;
                teamChallenge.TeamId      = team.TeamID;
                teamChallenge.Solved      = false;
                _context.Add(teamChallenge);
                await _context.SaveChangesAsync();

                var Challenge = await _context.Challenges
                                .FirstOrDefaultAsync(m => m.ID == id);

                if (Challenge == null)
                {
                    return(NotFound());
                }
                //Stop field from being populated at View
                Challenge.Flag = null;

                var Competition = await _context.Competitions.FindAsync(Challenge.CompetitionID);

                string bucketName = Competition.BucketName;
                var    category   = await _context.CompetitionCategories.FindAsync(Challenge.CompetitionCategoryID);

                string folderName = category.CategoryName;
                if (Challenge.FileName != null)
                {
                    string fileName     = Challenge.FileName;
                    Regex  pattern      = new Regex("[+]");
                    string tempFileName = pattern.Replace(fileName, "%2B");
                    tempFileName.Replace(' ', '+');
                    ViewData["FileLink"] = "https://s3-ap-southeast-1.amazonaws.com/" + bucketName + "/" + folderName + "/" + tempFileName;
                }
                ViewData["CompetitionID"] = Challenge.CompetitionID;
                ViewData["ChallengeID"]   = Challenge.ID;

                //if (ValidateUserJoined(Challenge.CompetitionID).Result == true)
                //{
                ViewData["Invalid"]   = false;
                ViewData["WrongFlag"] = true;
                return(View(Challenge));
                //}
            }
        }
        //public async Task<IActionResult> Create([Bind("ID,CompetitionName,Status,BucketName")] Competition competition, [Bind("CategoryName")] CompetitionCategory competitionCategory, string[] SelectedCategories)
        public async Task <IActionResult> Create(CategoriesViewModelIEnumerable model)
        //public async Task<IActionResult> Create(string[] CategoriesList)
        {
            /*foreach (var CategoryName in model.SelectedCategories)
             * {
             *  Console.WriteLine(CategoryName);
             * }*/
            //Console.WriteLine(model.competition.BucketName);
            //Tested and working^
            //Console.WriteLine(model.SelectedCategories.ElementAt(0));
            //Console.WriteLine(competitionCategory.Categories.ElementAt(0).CategoryName);
            if (model.SelectedCategories == null)
            {
                return(RedirectToAction("Create"));
            }

            model.Competition.Status = "Upcoming";
            if (ModelState.IsValid)
            {
                //Generate bucketname programtically
                model.Competition.BucketName            = GenerateBucketName(model.Competition.CompetitionName);
                model.Competition.CompetitionCategories = new Collection <CompetitionCategory>();
                foreach (var CategoryName in model.SelectedCategories)
                {
                    //model.competitionCategory = _context.CompetitionCategories.Find("CompetitionID");
                    //model.competitionCategory.CompetitionID = model.competition.ID;
                    //model.competitionCategory.CategoryName = CategoryName;

                    //competitionCategory.CategoryName = CategoryName;
                    //competitionCategory.CompetitionID = model.competition.ID;

                    //CompetitionCategoriesTempList.Add

                    model.Competition.CompetitionCategories.Add(new CompetitionCategory {
                        CompetitionID = model.Competition.ID, CategoryName = CategoryName
                    });

                    //competitionCategory.competitionID = _context.Competitions.Find("ID");\
                    //model.competition = new Competition();
                    //model.competition.CompetitionCategories.Add(new CompetitionCategory { CompetitionID = model.competition.ID, CategoryName = CategoryName });
                    //await _context.SaveChangesAsync();
                }
                _context.Add(model.Competition);
                await _context.SaveChangesAsync();

                try
                {
                    PutBucketResponse response = await S3Client.PutBucketAsync(model.Competition.BucketName);

                    if (response.HttpStatusCode == HttpStatusCode.OK)
                    {
                        //return RedirectToAction("");
                    }
                    else
                    {
                        //return RedirectToAction("");
                        //return RedirectToAction(nameof(Index));
                    }
                }
                catch (AmazonS3Exception e)
                {
                    ViewData["Exception"] = e.Message;
                    //return View();
                }
                //return RedirectToAction(nameof(Index));
            }
            else
            {
            }
            //return View(competition);
            //return View(model);
            //Testing create folder dynamically
            foreach (var CategoryName in model.SelectedCategories)
            {
                CreateFolder(model.Competition.BucketName, CategoryName);
            }
            //Testing create folder dynamically
            return(RedirectToAction("Index"));
        }