/// <summary>
        /// Runs before page actions
        /// </summary>
        public override async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
        {
            LoggedInUser = await PuzzleUser.GetPuzzleUserForCurrentUser(_context, User, userManager);

            // Required to have the rest of page execution occur
            await next.Invoke();
        }
Пример #2
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            _context.Events.Add(Event);

            var loggedInUser = await PuzzleUser.GetPuzzleUserForCurrentUser(_context, User, _userManager);

            if (loggedInUser != null)
            {
                _context.EventAdmins.Add(new EventAdmins()
                {
                    Event = Event, Admin = loggedInUser
                });
                _context.EventAuthors.Add(new EventAuthors()
                {
                    Event = Event, Author = loggedInUser
                });
            }

            await _context.SaveChangesAsync();

            return(RedirectToPage("./Index"));
        }
Пример #3
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."));
            }

            var thisPuzzleUser = await PuzzleUser.GetPuzzleUserForCurrentUser(_context, User, _userManager);

            // enforce access rights, do not let these change!
            Input.ID             = thisPuzzleUser.ID;
            Input.IsGlobalAdmin  = thisPuzzleUser.IsGlobalAdmin;
            Input.IdentityUserId = thisPuzzleUser.IdentityUserId;

            _context.Entry(thisPuzzleUser).State = EntityState.Detached;
            _context.Attach(Input).State         = EntityState.Modified;

            await _context.SaveChangesAsync(true);

            await _signInManager.RefreshSignInAsync(user);

            StatusMessage = "Your profile has been updated";
            return(RedirectToPage());
        }
        public async Task IsPlayerOnTeamCheck(AuthorizationHandlerContext authContext, IAuthorizationRequirement requirement)
        {
            EventRole role = GetEventRoleFromRoute();

            if (role != EventRole.play)
            {
                return;
            }

            PuzzleUser puzzleUser = await PuzzleUser.GetPuzzleUserForCurrentUser(dbContext, authContext.User, userManager);

            Team team = await GetTeamFromRoute();

            Event thisEvent = await GetEventFromRoute();

            if (thisEvent != null)
            {
                Team userTeam = await UserEventHelper.GetTeamForPlayer(dbContext, thisEvent, puzzleUser);

                if (userTeam != null && userTeam.ID == team.ID)
                {
                    authContext.Succeed(requirement);
                }
            }
        }
        public async Task IsPuzzleAuthorCheck(AuthorizationHandlerContext authContext, IAuthorizationRequirement requirement)
        {
            EventRole role = GetEventRoleFromRoute();

            if (role != EventRole.author)
            {
                return;
            }

            PuzzleUser puzzleUser = await PuzzleUser.GetPuzzleUserForCurrentUser(dbContext, authContext.User, userManager);

            Puzzle puzzle = await GetPuzzleFromRoute();

            Event thisEvent = await GetEventFromRoute();

            if (thisEvent != null && await UserEventHelper.IsAuthorOfPuzzle(dbContext, puzzle, puzzleUser))
            {
                authContext.Succeed(requirement);
            }

            if (puzzle != null)
            {
                dbContext.Entry(puzzle).State = EntityState.Detached;
            }
        }
Пример #6
0
        public async Task <IActionResult> Post(string eventId, int puzzleId, List <int> query_puzzle_ids, int?min_solve_count, string annotations,
                                               string last_sync_time)
        {
            // Find what team this user is on, relative to the event.

            Event currentEvent = await EventHelper.GetEventFromEventId(context, eventId);

            if (currentEvent == null)
            {
                return(Unauthorized());
            }
            PuzzleUser user = await PuzzleUser.GetPuzzleUserForCurrentUser(context, User, userManager);

            if (user == null)
            {
                return(Unauthorized());
            }
            Team team = await UserEventHelper.GetTeamForPlayer(context, currentEvent, user);

            if (team == null)
            {
                return(Unauthorized());
            }

            var helper   = new SyncHelper(context);
            var response = await helper.GetSyncResponse(currentEvent.ID, team.ID, puzzleId, query_puzzle_ids, min_solve_count,
                                                        annotations, last_sync_time, false);

            return(Json(response));
        }
Пример #7
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            if (string.IsNullOrEmpty(PuzzleUser.Email))
            {
                ModelState.AddModelError("PuzzleUser.Email", "An email is required.");
            }
            else if (!MailHelper.IsValidEmail(PuzzleUser.Email))
            {
                ModelState.AddModelError("PuzzleUser.Email", "This email address is not valid.");
            }

            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var thisPuzzleUser = await PuzzleUser.GetPuzzleUserForCurrentUser(_context, User, _userManager);

            if (thisPuzzleUser != null)
            {
                _context.Entry(thisPuzzleUser).State = EntityState.Detached;
            }

            _context.Attach(PuzzleUser).State = EntityState.Modified;

            await _context.SaveChangesAsync();

            return(Redirect(returnUrl));
        }
        public async Task <IActionResult> Index(string eventId, int puzzleId)
        {
            Event currentEvent = await EventHelper.GetEventFromEventId(context, eventId);

            PuzzleUser user = await PuzzleUser.GetPuzzleUserForCurrentUser(context, User, userManager);

            Team team = await UserEventHelper.GetTeamForPlayer(context, currentEvent, user);

            Puzzle thisPuzzle = await context.Puzzles.FirstOrDefaultAsync(m => m.ID == puzzleId);

            // Find the material file with the latest-alphabetically ShortName that contains the substring "customPage".
            var materialFile = await(from f in context.ContentFiles
                                     where f.Puzzle == thisPuzzle && f.FileType == ContentFileType.PuzzleMaterial && f.ShortName.Contains("customPage")
                                     orderby f.ShortName descending
                                     select f).FirstOrDefaultAsync();

            if (materialFile == null)
            {
                return(Content("ERROR:  There's no custom page uploaded for this puzzle"));
            }

            var materialUrl = materialFile.Url;

            // Download that material file.
            string fileContents;

            using (var wc = new System.Net.WebClient())
            {
                fileContents = await wc.DownloadStringTaskAsync(materialUrl);
            }

            // Return the file contents to the user.
            return(Content(fileContents, "text/html"));
        }
        public async Task <SubmissionResponse> PostSubmitAnswerAsync([FromBody] AnswerSubmission submission, [FromRoute] string eventId, [FromRoute] int puzzleId)
        {
            Event currentEvent = await EventHelper.GetEventFromEventId(context, eventId);

            PuzzleUser user = await PuzzleUser.GetPuzzleUserForCurrentUser(context, User, userManager);

            return(await SubmissionEvaluator.EvaluateSubmission(context, user, currentEvent, puzzleId, submission.SubmissionText, submission.AllowFreeformSharing));
        }
Пример #10
0
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext authContext,
                                                             IsGlobalAdminRequirement requirement)
        {
            PuzzleUser puzzleUser = await PuzzleUser.GetPuzzleUserForCurrentUser(dbContext, authContext.User, userManager);

            if (puzzleUser.IsGlobalAdmin)
            {
                authContext.Succeed(requirement);
            }
        }
Пример #11
0
        public static async Task IsEventAdminCheck(AuthorizationHandlerContext authContext, PuzzleServerContext dbContext, UserManager <IdentityUser> userManager, IAuthorizationRequirement requirement)
        {
            PuzzleUser puzzleUser = await PuzzleUser.GetPuzzleUserForCurrentUser(dbContext, authContext.User, userManager);

            Event thisEvent = await AuthorizationHelper.GetEventFromContext(authContext);

            EventRole role = AuthorizationHelper.GetEventRoleFromContext(authContext);

            if (thisEvent != null && role == EventRole.admin && await puzzleUser.IsAdminForEvent(dbContext, thisEvent))
            {
                authContext.Succeed(requirement);
            }
        }
        public async Task IsEventAdminCheck(AuthorizationHandlerContext authContext, IAuthorizationRequirement requirement)
        {
            EventRole role = GetEventRoleFromRoute();

            if (role != EventRole.admin)
            {
                return;
            }

            PuzzleUser puzzleUser = await PuzzleUser.GetPuzzleUserForCurrentUser(dbContext, authContext.User, userManager);

            Event thisEvent = await GetEventFromRoute();

            if (thisEvent != null && puzzleUser != null && await puzzleUser.IsAdminForEvent(dbContext, thisEvent))
            {
                authContext.Succeed(requirement);
            }
        }
Пример #13
0
        public static async Task IsPuzzleAuthorCheck(AuthorizationHandlerContext authContext, PuzzleServerContext dbContext, UserManager <IdentityUser> userManager, IAuthorizationRequirement requirement)
        {
            PuzzleUser puzzleUser = await PuzzleUser.GetPuzzleUserForCurrentUser(dbContext, authContext.User, userManager);

            Puzzle puzzle = await AuthorizationHelper.GetPuzzleFromContext(authContext);

            Event thisEvent = await AuthorizationHelper.GetEventFromContext(authContext);

            EventRole role = AuthorizationHelper.GetEventRoleFromContext(authContext);

            if (thisEvent != null && role == EventRole.author && await UserEventHelper.IsAuthorOfPuzzle(dbContext, puzzle, puzzleUser))
            {
                authContext.Succeed(requirement);
            }

            if (puzzle != null)
            {
                dbContext.Entry(puzzle).State = EntityState.Detached;
            }
        }
Пример #14
0
        public static async Task IsPlayerOnTeamCheck(AuthorizationHandlerContext authContext, PuzzleServerContext dbContext, UserManager <IdentityUser> userManager, IAuthorizationRequirement requirement)
        {
            PuzzleUser puzzleUser = await PuzzleUser.GetPuzzleUserForCurrentUser(dbContext, authContext.User, userManager);

            Team team = await AuthorizationHelper.GetTeamFromContext(authContext);

            Event thisEvent = await AuthorizationHelper.GetEventFromContext(authContext);

            EventRole role = AuthorizationHelper.GetEventRoleFromContext(authContext);

            if (thisEvent != null && role == EventRole.play)
            {
                Team userTeam = await UserEventHelper.GetTeamForPlayer(dbContext, thisEvent, puzzleUser);

                if (userTeam != null && userTeam.ID == team.ID)
                {
                    authContext.Succeed(requirement);
                }
            }
        }
Пример #15
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var thisPuzzleUser = await PuzzleUser.GetPuzzleUserForCurrentUser(_context, User, _userManager);

            if (thisPuzzleUser != null)
            {
                _context.Entry(thisPuzzleUser).State = EntityState.Detached;
            }

            _context.Attach(PuzzleUser).State = EntityState.Modified;

            await _context.SaveChangesAsync();

            return(Redirect(returnUrl));
        }
        public static async Task IsEventAuthorCheck(AuthorizationHandlerContext authContext, PuzzleServerContext dbContext, UserManager <IdentityUser> userManager, IAuthorizationRequirement requirement)
        {
            EventRole role = AuthorizationHelper.GetEventRoleFromContext(authContext);

            if (role != EventRole.author)
            {
                return;
            }

            PuzzleUser puzzleUser = await PuzzleUser.GetPuzzleUserForCurrentUser(dbContext, authContext.User, userManager);

            if (authContext.Resource is AuthorizationFilterContext filterContext)
            {
                Event thisEvent = await AuthorizationHelper.GetEventFromContext(authContext);

                if (thisEvent != null && await puzzleUser.IsAuthorForEvent(dbContext, thisEvent))
                {
                    authContext.Succeed(requirement);
                }
            }
        }
        public async Task PlayerCanSeePuzzleCheck(AuthorizationHandlerContext authContext, IAuthorizationRequirement requirement)
        {
            PuzzleUser puzzleUser = await PuzzleUser.GetPuzzleUserForCurrentUser(dbContext, authContext.User, userManager);

            Puzzle puzzle = await GetPuzzleFromRoute();

            Event thisEvent = await GetEventFromRoute();

            if (thisEvent != null && puzzle != null)
            {
                Team team = await UserEventHelper.GetTeamForPlayer(dbContext, thisEvent, puzzleUser);

                if (team != null)
                {
                    IQueryable <PuzzleStatePerTeam> statesQ = PuzzleStateHelper.GetFullReadOnlyQuery(dbContext, thisEvent, puzzle, team);

                    if (statesQ.FirstOrDefault().UnlockedTime != null || thisEvent.AreAnswersAvailableNow)
                    {
                        authContext.Succeed(requirement);
                    }
                }
            }
        }
Пример #18
0
        public async Task <IActionResult> Index(string eventId, int puzzleId)
        {
            Event currentEvent = await EventHelper.GetEventFromEventId(context, eventId);

            if (currentEvent == null)
            {
                return(Content("ERROR:  That event doesn't exist"));
            }

            PuzzleUser user = await PuzzleUser.GetPuzzleUserForCurrentUser(context, User, userManager);

            if (user == null)
            {
                return(Content("ERROR:  You aren't logged in"));
            }

            Team team = await UserEventHelper.GetTeamForPlayer(context, currentEvent, user);

            if (team == null)
            {
                return(Content("ERROR:  You're not on a team"));
            }

            Puzzle thisPuzzle = await context.Puzzles.FirstOrDefaultAsync(m => m.ID == puzzleId);

            if (thisPuzzle == null)
            {
                return(Content("ERROR:  That's not a valid puzzle ID"));
            }

            if (!currentEvent.AreAnswersAvailableNow)
            {
                var puzzleState = await(from state in context.PuzzleStatePerTeam
                                        where state.Puzzle == thisPuzzle && state.Team == team
                                        select state).FirstOrDefaultAsync();
                if (puzzleState == null || puzzleState.UnlockedTime == null)
                {
                    return(Content("ERROR:  You haven't unlocked this puzzle yet"));
                }
            }

            // Find the material file with the latest-alphabetically ShortName that contains the substring "client".

            var materialFile = await(from f in context.ContentFiles
                                     where f.Puzzle == thisPuzzle && f.FileType == ContentFileType.PuzzleMaterial && f.ShortName.Contains("client")
                                     orderby f.ShortName descending
                                     select f).FirstOrDefaultAsync();

            if (materialFile == null)
            {
                return(Content("ERROR:  There's no sync client registered for this puzzle"));
            }

            var materialUrl = materialFile.Url;

            // Start doing a sync asynchronously while we download the file contents.

            var helper = new SyncHelper(context);
            Task <Dictionary <string, object> > responseTask = helper.GetSyncResponse(currentEvent.ID, team.ID, puzzleId, null, 0, null, null, true);

            // Download that material file.

            string fileContents;

            using (var wc = new System.Net.WebClient())
            {
                fileContents = await wc.DownloadStringTaskAsync(materialUrl);
            }

            // Wait for the asynchronous sync we started earlier to complete, then serialize
            // its results and use them to replace the substring "@SYNC" where it appears
            // in the downloaded file contents.

            Dictionary <string, object> response = await responseTask;
            var responseSerialized = JsonConvert.SerializeObject(response);
            var initialSyncString  = HttpUtility.JavaScriptStringEncode(responseSerialized);

            fileContents = fileContents.Replace("@SYNC", initialSyncString);

            // Return the file contents to the user.

            return(Content(fileContents, "text/html"));
        }
Пример #19
0
        /// <summary>
        /// Returns whether the user is authorized to view the file
        /// </summary>
        /// <param name="eventId">The current event</param>
        /// <param name="puzzle">The puzzle the file belongs to</param>
        /// <param name="content">The file</param>
        private async Task <bool> IsAuthorized(int eventId, Puzzle puzzle, ContentFile content)
        {
            Event currentEvent = await(from ev in context.Events
                                       where ev.ID == eventId
                                       select ev).SingleAsync();
            PuzzleUser user = await PuzzleUser.GetPuzzleUserForCurrentUser(context, User, userManager);

            // Admins can see all files
            if (await user.IsAdminForEvent(context, currentEvent))
            {
                return(true);
            }

            // Authors can see all files attached to their puzzles
            if (await UserEventHelper.IsAuthorOfPuzzle(context, puzzle, user))
            {
                return(true);
            }

            Team team = await UserEventHelper.GetTeamForPlayer(context, currentEvent, user);

            if (team == null)
            {
                return(false);
            }

            // Once answers are available, so are all other files
            if (currentEvent.AreAnswersAvailableNow)
            {
                return(true);
            }

            PuzzleStatePerTeam puzzleState = await PuzzleStateHelper.GetFullReadOnlyQuery(context, currentEvent, puzzle, team).SingleAsync();

            switch (content.FileType)
            {
            case ContentFileType.Answer:
                // The positive case is already handled above by checking AreAnswersAvailableNow
                return(false);

            case ContentFileType.Puzzle:
            case ContentFileType.PuzzleMaterial:
                if (puzzleState.UnlockedTime != null)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }

            case ContentFileType.SolveToken:
                if (puzzleState.SolvedTime != null)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }

            default:
                throw new NotImplementedException();
            }
        }
Пример #20
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            using (var transaction = _context.Database.BeginTransaction())
            {
                //
                // Add the event and save, so the event gets an ID.
                //
                Event.TeamRegistrationBegin       = DateTime.UtcNow;
                Event.TeamRegistrationEnd         = Event.AnswerSubmissionEnd;
                Event.TeamNameChangeEnd           = Event.AnswerSubmissionEnd;
                Event.TeamMembershipChangeEnd     = Event.AnswerSubmissionEnd;
                Event.TeamMiscDataChangeEnd       = Event.AnswerSubmissionEnd;
                Event.TeamDeleteEnd               = Event.AnswerSubmissionEnd;
                Event.AnswersAvailableBegin       = Event.AnswerSubmissionEnd;
                Event.StandingsAvailableBegin     = DateTime.UtcNow;
                Event.LockoutIncorrectGuessLimit  = 5;
                Event.LockoutIncorrectGuessPeriod = 1;
                Event.LockoutDurationMultiplier   = 2;
                Event.MaxSubmissionCount          = 50;
                Event.MaxNumberOfTeams            = 120;
                Event.MaxExternalsPerTeam         = 9;
                Event.MaxTeamSize = 12;
                _context.Events.Add(Event);

                await _context.SaveChangesAsync();

                //
                // Add start puzzle, three module puzzles, and one module meta (marked as the final event puzzle for this demo)
                //
                Puzzle start = new Puzzle
                {
                    Name     = "!!!Get Hopping!!!",
                    Event    = Event,
                    IsPuzzle = false,
                    IsGloballyVisiblePrerequisite = true,
                    Description = "Start the event",
                };
                _context.Puzzles.Add(start);

                Puzzle easy = new Puzzle
                {
                    Name                 = "Bunny Slope",
                    Event                = Event,
                    IsPuzzle             = true,
                    SolveValue           = 10,
                    HintCoinsForSolve    = 1,
                    Group                = "Thumper's Stumpers",
                    OrderInGroup         = 1,
                    MinPrerequisiteCount = 1,
                    Description          = "Bunsweeper",
                };
                _context.Puzzles.Add(easy);

                Puzzle intermediate = new Puzzle
                {
                    Name                        = "Rabbit Run (automatically solves in ~3 mins)",
                    Event                       = Event,
                    IsPuzzle                    = true,
                    SolveValue                  = 10,
                    HintCoinsForSolve           = 2,
                    Group                       = "Thumper's Stumpers",
                    OrderInGroup                = 2,
                    MinPrerequisiteCount        = 1,
                    MinutesToAutomaticallySolve = 3,
                    Description                 = "Rabbit's Cube",
                };
                _context.Puzzles.Add(intermediate);

                Puzzle hard = new Puzzle
                {
                    Name                 = "Hare-Raising",
                    Event                = Event,
                    IsPuzzle             = true,
                    SolveValue           = 10,
                    HintCoinsForSolve    = 3,
                    Group                = "Thumper's Stumpers",
                    OrderInGroup         = 3,
                    MinPrerequisiteCount = 1,
                    Description          = "Lateral Leaping",
                };
                _context.Puzzles.Add(hard);

                Puzzle meta = new Puzzle
                {
                    Name                 = "Lagomorph Meta",
                    Event                = Event,
                    IsPuzzle             = true,
                    IsMetaPuzzle         = true,
                    IsFinalPuzzle        = true,
                    SolveValue           = 100,
                    Group                = "Thumper's Stumpers",
                    OrderInGroup         = 99,
                    MinPrerequisiteCount = 2,
                    Description          = "Word Hutch",
                };
                _context.Puzzles.Add(meta);

                Puzzle other = new Puzzle
                {
                    Name                 = "Rabbit Season",
                    Event                = Event,
                    IsPuzzle             = true,
                    SolveValue           = 10,
                    Group                = "Daffy's Delights",
                    OrderInGroup         = 1,
                    MinPrerequisiteCount = 1,
                    Description          = "Hip Hop Identification",
                    CustomURL            = "https://www.bing.com/images/search?q=%22rabbit%22",
                };
                _context.Puzzles.Add(other);

                Puzzle cheat = new Puzzle
                {
                    Name                 = "You're Despicable (cheat code)",
                    Event                = Event,
                    IsPuzzle             = true,
                    IsCheatCode          = true,
                    SolveValue           = -1,
                    Group                = "Daffy's Delights",
                    OrderInGroup         = 2,
                    MinPrerequisiteCount = 1,
                    Description          = "Duck Konundrum",
                };
                _context.Puzzles.Add(cheat);

                Puzzle lockIntro = new Puzzle
                {
                    Name                 = "Wouldn't you know... (whistle stop intro)",
                    Event                = Event,
                    IsPuzzle             = true,
                    SolveValue           = 0,
                    Group                = "Roger's Railway",
                    OrderInGroup         = 1,
                    MinPrerequisiteCount = 1,
                    Description          = "Whistle Hop Intro",
                };
                _context.Puzzles.Add(lockIntro);

                Puzzle lockPuzzle = new Puzzle
                {
                    Name                  = "...Locked! (whistle stop, lasts 5 minutes)",
                    Event                 = Event,
                    IsPuzzle              = true,
                    SolveValue            = 0,
                    Group                 = "Roger's Railway",
                    OrderInGroup          = 2,
                    MinPrerequisiteCount  = 1,
                    MinutesOfEventLockout = 5,
                    Description           = "Whistle Hop",
                };
                _context.Puzzles.Add(lockPuzzle);

                Puzzle kitchenSyncPuzzle = new Puzzle
                {
                    Name                 = "Kitchen Sync",
                    Event                = Event,
                    IsPuzzle             = true,
                    SolveValue           = 10,
                    Group                = "Sync Test",
                    OrderInGroup         = 1,
                    MinPrerequisiteCount = 1
                };
                _context.Puzzles.Add(kitchenSyncPuzzle);

                Puzzle heatSyncPuzzle = new Puzzle
                {
                    Name                 = "Heat Sync",
                    Event                = Event,
                    IsPuzzle             = true,
                    SolveValue           = 10,
                    Group                = "Sync Test",
                    OrderInGroup         = 2,
                    MinPrerequisiteCount = 1
                };
                _context.Puzzles.Add(heatSyncPuzzle);

                Puzzle lipSyncPuzzle = new Puzzle
                {
                    Name                 = "Lip Sync",
                    Event                = Event,
                    IsPuzzle             = true,
                    SolveValue           = 10,
                    Group                = "Sync Test",
                    OrderInGroup         = 3,
                    MinPrerequisiteCount = 1
                };
                _context.Puzzles.Add(lipSyncPuzzle);

                Puzzle syncTestMetapuzzle = new Puzzle
                {
                    Name                 = "Sync Test",
                    Event                = Event,
                    IsPuzzle             = true,
                    IsMetaPuzzle         = true,
                    SolveValue           = 50,
                    Group                = "Sync Test",
                    OrderInGroup         = 99,
                    MinPrerequisiteCount = 1,
                    MaxAnnotationKey     = 400
                };
                _context.Puzzles.Add(syncTestMetapuzzle);

                await _context.SaveChangesAsync();

                //
                // Add responses, PARTIAL is a partial, ANSWER is the answer.
                //
                _context.Responses.Add(new Response()
                {
                    Puzzle = easy, SubmittedText = "PARTIAL", ResponseText = "Keep going..."
                });
                _context.Responses.Add(new Response()
                {
                    Puzzle = easy, SubmittedText = "ANSWER", ResponseText = "Correct!", IsSolution = true
                });
                _context.Responses.Add(new Response()
                {
                    Puzzle = intermediate, SubmittedText = "PARTIAL", ResponseText = "Keep going..."
                });
                _context.Responses.Add(new Response()
                {
                    Puzzle = intermediate, SubmittedText = "ANSWER", ResponseText = "Correct!", IsSolution = true
                });
                _context.Responses.Add(new Response()
                {
                    Puzzle = hard, SubmittedText = "PARTIAL", ResponseText = "Keep going..."
                });
                _context.Responses.Add(new Response()
                {
                    Puzzle = hard, SubmittedText = "ANSWER", ResponseText = "Correct!", IsSolution = true
                });
                _context.Responses.Add(new Response()
                {
                    Puzzle = meta, SubmittedText = "PARTIAL", ResponseText = "Keep going..."
                });
                _context.Responses.Add(new Response()
                {
                    Puzzle = meta, SubmittedText = "ANSWER", ResponseText = "Correct!", IsSolution = true
                });
                _context.Responses.Add(new Response()
                {
                    Puzzle = other, SubmittedText = "PARTIAL", ResponseText = "Keep going..."
                });
                _context.Responses.Add(new Response()
                {
                    Puzzle = other, SubmittedText = "ANSWER", ResponseText = "Correct!", IsSolution = true
                });
                _context.Responses.Add(new Response()
                {
                    Puzzle = cheat, SubmittedText = "PARTIAL", ResponseText = "Keep going..."
                });
                _context.Responses.Add(new Response()
                {
                    Puzzle = cheat, SubmittedText = "ANSWER", ResponseText = "Correct!", IsSolution = true
                });
                _context.Responses.Add(new Response()
                {
                    Puzzle = lockIntro, SubmittedText = "PARTIAL", ResponseText = "Keep going..."
                });
                _context.Responses.Add(new Response()
                {
                    Puzzle = lockIntro, SubmittedText = "ANSWER", ResponseText = "Correct!", IsSolution = true
                });
                _context.Responses.Add(new Response()
                {
                    Puzzle = lockPuzzle, SubmittedText = "PARTIAL", ResponseText = "Keep going..."
                });
                _context.Responses.Add(new Response()
                {
                    Puzzle = lockPuzzle, SubmittedText = "ANSWER", ResponseText = "Correct!", IsSolution = true
                });
                _context.Responses.Add(new Response()
                {
                    Puzzle = kitchenSyncPuzzle, SubmittedText = "PARTIAL", ResponseText = "Keep going..."
                });
                _context.Responses.Add(new Response()
                {
                    Puzzle = kitchenSyncPuzzle, SubmittedText = "SYNC", ResponseText = "Correct!", IsSolution = true
                });
                _context.Responses.Add(new Response()
                {
                    Puzzle = heatSyncPuzzle, SubmittedText = "PARTIAL", ResponseText = "Keep going..."
                });
                _context.Responses.Add(new Response()
                {
                    Puzzle = heatSyncPuzzle, SubmittedText = "OR", ResponseText = "Correct!", IsSolution = true
                });
                _context.Responses.Add(new Response()
                {
                    Puzzle = lipSyncPuzzle, SubmittedText = "PARTIAL", ResponseText = "Keep going..."
                });
                _context.Responses.Add(new Response()
                {
                    Puzzle = lipSyncPuzzle, SubmittedText = "SWIM", ResponseText = "Correct!", IsSolution = true
                });
                _context.Responses.Add(new Response()
                {
                    Puzzle = syncTestMetapuzzle, SubmittedText = "PARTIAL", ResponseText = "Keep going..."
                });
                _context.Responses.Add(new Response()
                {
                    Puzzle = syncTestMetapuzzle, SubmittedText = "SYNCORSWIM", ResponseText = "Correct!", IsSolution = true
                });

                string hint1Description = "Tell me about the rabbits, George.";
                string hint1Content     = "O.K. Some day – we’re gonna get the jack together and we’re gonna have a little house and a couple of acres an’ a cow and some pigs and...";
                string hint2Description = "Go on... George. How I get to tend the rabbits.";
                string hint2Content     = "Well, we’ll have a big vegetable patch and a rabbit-hutch and chickens.";
                _context.Hints.Add(new Hint()
                {
                    Puzzle = easy, Description = hint1Description, DisplayOrder = 0, Cost = 0, Content = hint1Content
                });
                _context.Hints.Add(new Hint()
                {
                    Puzzle = easy, Description = hint2Description, DisplayOrder = 1, Cost = 1, Content = hint2Content
                });
                _context.Hints.Add(new Hint()
                {
                    Puzzle = intermediate, Description = hint1Description, DisplayOrder = 0, Cost = 0, Content = hint1Content
                });
                _context.Hints.Add(new Hint()
                {
                    Puzzle = intermediate, Description = hint2Description, DisplayOrder = 1, Cost = 1, Content = hint2Content
                });
                _context.Hints.Add(new Hint()
                {
                    Puzzle = hard, Description = hint1Description, DisplayOrder = 0, Cost = 0, Content = hint1Content
                });
                _context.Hints.Add(new Hint()
                {
                    Puzzle = hard, Description = hint2Description, DisplayOrder = 1, Cost = 1, Content = hint2Content
                });
                _context.Hints.Add(new Hint()
                {
                    Puzzle = meta, Description = hint1Description, DisplayOrder = 0, Cost = 0, Content = hint1Content
                });
                _context.Hints.Add(new Hint()
                {
                    Puzzle = meta, Description = hint2Description, DisplayOrder = 1, Cost = 1, Content = hint2Content
                });

                await _context.SaveChangesAsync();

                //
                // Set up prequisite links.
                // The first two depend on start puzzle, then the third depends on one of the first two, then the meta depends on two of the first three.
                //
                _context.Prerequisites.Add(new Prerequisites()
                {
                    Puzzle = easy, Prerequisite = start
                });
                _context.Prerequisites.Add(new Prerequisites()
                {
                    Puzzle = intermediate, Prerequisite = start
                });
                _context.Prerequisites.Add(new Prerequisites()
                {
                    Puzzle = hard, Prerequisite = easy
                });
                _context.Prerequisites.Add(new Prerequisites()
                {
                    Puzzle = hard, Prerequisite = intermediate
                });
                _context.Prerequisites.Add(new Prerequisites()
                {
                    Puzzle = meta, Prerequisite = easy
                });
                _context.Prerequisites.Add(new Prerequisites()
                {
                    Puzzle = meta, Prerequisite = intermediate
                });
                _context.Prerequisites.Add(new Prerequisites()
                {
                    Puzzle = meta, Prerequisite = hard
                });
                _context.Prerequisites.Add(new Prerequisites()
                {
                    Puzzle = other, Prerequisite = start
                });
                _context.Prerequisites.Add(new Prerequisites()
                {
                    Puzzle = cheat, Prerequisite = start
                });
                _context.Prerequisites.Add(new Prerequisites()
                {
                    Puzzle = lockIntro, Prerequisite = start
                });
                _context.Prerequisites.Add(new Prerequisites()
                {
                    Puzzle = lockPuzzle, Prerequisite = lockIntro
                });
                _context.Prerequisites.Add(new Prerequisites()
                {
                    Puzzle = kitchenSyncPuzzle, Prerequisite = start
                });
                _context.Prerequisites.Add(new Prerequisites()
                {
                    Puzzle = heatSyncPuzzle, Prerequisite = start
                });
                _context.Prerequisites.Add(new Prerequisites()
                {
                    Puzzle = lipSyncPuzzle, Prerequisite = start
                });
                _context.Prerequisites.Add(new Prerequisites()
                {
                    Puzzle = syncTestMetapuzzle, Prerequisite = start
                });

                await _context.SaveChangesAsync();

                //
                // Create puzzle pieces.
                //
                _context.Pieces.Add(MakePiece(syncTestMetapuzzle, 0, 1, "xxx xxxx'x x xXxxx!", 3, "What Crocodile Dundee might say"));
                _context.Pieces.Add(MakePiece(syncTestMetapuzzle, 1, 2, "xxx xxxx xxxx xxx Xxxxx", 1, "In <i>Hey Diddle Diddle</i>, what the dish did"));
                _context.Pieces.Add(MakePiece(syncTestMetapuzzle, 1, 3, "xxXx", 1, "It smells"));
                _context.Pieces.Add(MakePiece(syncTestMetapuzzle, 2, 4, "xxX", 4, "You reach things by extending it"));
                _context.Pieces.Add(MakePiece(syncTestMetapuzzle, 2, 5, "Xxx xxxxx", 1, "Result of the <i>Exxon Valdez</i> crash"));
                _context.Pieces.Add(MakePiece(syncTestMetapuzzle, 2, 6, "xxxxX", 2, "What you make out of turkey drippings"));
                _context.Pieces.Add(MakePiece(syncTestMetapuzzle, 3, 7, "xxxXx xxx", 4, "Another name for a slow cooker"));
                _context.Pieces.Add(MakePiece(syncTestMetapuzzle, 4, 8, "xXxxxx", 3, "The index is one of them"));
                _context.Pieces.Add(MakePiece(syncTestMetapuzzle, 4, 9, "xxxxX", 2, "It can suffer when you play tennis"));
                _context.Pieces.Add(MakePiece(syncTestMetapuzzle, 4, 10, "xxxxxxX xxxxxxx", 2, "What Chekov asked strangers the location of in Star Trek IV, garnering suspicion due to his Russian accent"));

                await _context.SaveChangesAsync();

                //
                // Create teams. Can we add players to these?
                //
                Team team1 = new Team {
                    Name = "Team Bugs", Event = Event
                };
                _context.Teams.Add(team1);

                Team team2 = new Team {
                    Name = "Team Babs", Event = Event
                };
                _context.Teams.Add(team2);

                Team team3 = new Team {
                    Name = "Team Buster", Event = Event
                };
                _context.Teams.Add(team3);

                Team teamLoneWolf = null;
                if (AddCreatorToLoneWolfTeam)
                {
                    teamLoneWolf = new Team {
                        Name = "Lone Wolf", Event = Event
                    };
                    _context.Teams.Add(teamLoneWolf);
                }

                var demoCreatorUser = await PuzzleUser.GetPuzzleUserForCurrentUser(_context, User, _userManager);

                if (demoCreatorUser != null)
                {
                    //
                    // Event admin/author
                    //
                    _context.EventAdmins.Add(new EventAdmins()
                    {
                        Event = Event, Admin = demoCreatorUser
                    });
                    _context.EventAuthors.Add(new EventAuthors()
                    {
                        Event = Event, Author = demoCreatorUser
                    });

                    //
                    // Puzzle author (for Thumper module only)
                    //
                    _context.PuzzleAuthors.Add(new PuzzleAuthors()
                    {
                        Puzzle = easy, Author = demoCreatorUser
                    });
                    _context.PuzzleAuthors.Add(new PuzzleAuthors()
                    {
                        Puzzle = intermediate, Author = demoCreatorUser
                    });
                    _context.PuzzleAuthors.Add(new PuzzleAuthors()
                    {
                        Puzzle = hard, Author = demoCreatorUser
                    });
                    _context.PuzzleAuthors.Add(new PuzzleAuthors()
                    {
                        Puzzle = meta, Author = demoCreatorUser
                    });
                }

                // TODO: Files (need to know how to detect whether local blob storage is configured)
                // Is there a point to adding Feedback or is that quick/easy enough to demo by hand?

                await _context.SaveChangesAsync();

                if (teamLoneWolf != null)
                {
                    _context.TeamMembers.Add(new TeamMembers()
                    {
                        Team = teamLoneWolf, Member = demoCreatorUser
                    });
                }

                // line up all hints
                var teams = await _context.Teams.Where((t) => t.Event == Event).ToListAsync();

                var hints = await _context.Hints.Where((h) => h.Puzzle.Event == Event).ToListAsync();

                var puzzles = await _context.Puzzles.Where(p => p.Event == Event).ToListAsync();

                foreach (Team team in teams)
                {
                    foreach (Hint hint in hints)
                    {
                        _context.HintStatePerTeam.Add(new HintStatePerTeam()
                        {
                            Hint = hint, Team = team
                        });
                    }
                    foreach (Puzzle puzzle in puzzles)
                    {
                        _context.PuzzleStatePerTeam.Add(new PuzzleStatePerTeam()
                        {
                            PuzzleID = puzzle.ID, TeamID = team.ID
                        });
                    }
                }

                await _context.SaveChangesAsync();

                //
                // Mark the start puzzle as solved if we were asked to.
                //
                if (StartTheEvent)
                {
                    await PuzzleStateHelper.SetSolveStateAsync(_context, Event, start, null, DateTime.UtcNow);
                }

                transaction.Commit();
            }

            return(RedirectToPage("./Index"));
        }
Пример #21
0
        /// <summary>
        /// Returns the team for the currently signed in player
        /// </summary>
        /// <param name="puzzlerServerContext">Current PuzzleServerContext</param>
        /// <param name="thisEvent">The event that's being checked</param>
        /// <param name="user">The claim for the user being checked</param>
        /// <param name="userManager">The UserManager for the current context</param>
        /// <returns>The user's team for this event</returns>
        public static async Task <Team> GetTeamForCurrentPlayer(PuzzleServerContext puzzleServerContext, Event thisEvent, ClaimsPrincipal user, UserManager <IdentityUser> userManager)
        {
            PuzzleUser pUser = await PuzzleUser.GetPuzzleUserForCurrentUser(puzzleServerContext, user, userManager);

            return(await GetTeamForPlayer(puzzleServerContext, thisEvent, pUser));
        }