Beispiel #1
0
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var user = await _userManager.GetUserAsync(context.HttpContext.User);

            if (user is not null && !String.IsNullOrEmpty(user.RefreshToken))
            {
                if (user.ExpiresAt < DateTime.Now.AddMinutes(5)) //Check if the access token will expire in 5 minutes
                {
                    // Update the authorization tokens and sign the user in again
                    await _tokenRefresher.RefreshTokens(user, signInUser : true);
                }
            }

            await base.OnActionExecutionAsync(context, next);
        }
Beispiel #2
0
        public async Task <IActionResult> IssueChallenge(int?id)
        {
            if (id is null)
            {
                return(NotFound());
            }

            var user = await _userManager.GetUserAsync(User);

            var game = await _context.Game.Include(g => g.HomePlayer.User)
                       .Include(g => g.AwayPlayer.User)
                       .Include(g => g.Match)
                       .FirstOrDefaultAsync(g => g.GameId == id);

            if (game.HomePlayer == null || game.AwayPlayer == null || game.HomePlayer.User.Id != user.Id)
            {
                return(NotFound());
            }

            var awayUser = await _userManager.FindByIdAsync(game.AwayPlayer.UserId + "");

            bool userRefreshed = false, awayRefreshed = false;

            userRefreshed = await _tokenRefresher.RefreshTokens(user, false);

            awayRefreshed = await _tokenRefresher.RefreshTokens(awayUser, false);

            if (!userRefreshed)
            {
                Log.Information("User access token expired");

                await _signInManager.SignOutAsync();

                return(RedirectToAction(nameof(AdminController.Index), "Home"));
            }

            GameJson gameJson = new GameJson
            {
                GameId           = game.GameId.ToString(),
                ChallengeId      = game.ChallengeId,
                Fen              = game.CurrentFen,
                ChallengeUrl     = game.ChallengeUrl,
                MatchId          = game.MatchId,
                Moves            = new List <string>(),
                Completed        = false,
                Result           = "",
                BlackPlayerId    = game.BoardPosition % 2 == 1 ? game.HomePlayer.User.LichessId : game.AwayPlayer.User.LichessId,
                WhitePlayerId    = game.BoardPosition % 2 == 0 ? game.HomePlayer.User.LichessId : game.AwayPlayer.User.LichessId,
                HomePlayerRating = game.Completed ? $"{game.HomePlayerRatingBefore} -> {game.HomePlayerRatingAfter}" : $"{game.HomePlayerRatingAfter}",
                AwayPlayerRating = game.Completed ? $"{game.AwayPlayerRatingBefore} -> {game.AwayPlayerRatingAfter}" : $"{game.AwayPlayerRatingAfter}",
                HomePoints       = game.HomePoints.ToString(),
                AwayPoints       = game.AwayPoints.ToString()
            };

            // If JV, colors are swapped
            if (game.BoardPosition > 7)
            {
                string temp = gameJson.BlackPlayerId;
                gameJson.BlackPlayerId = gameJson.WhitePlayerId;
                gameJson.WhitePlayerId = temp;
            }

            bool challengeCreated = false;

            LichessApi.LichessApiClient client = new LichessApiClient(user.AccessToken);

            if (awayRefreshed)
            {
                CreateGameRequest request = new CreateGameRequest
                {
                    Rated          = true,
                    ClockLimit     = game.Match.ClockTimeLimit,
                    ClockIncrement = game.Match.ClockIncrement,
                    Color          = game.BoardPosition % 2 == 0 ? Color.White : Color.Black,
                    Variant        = GameVariant.Standard,
                    Fen            = game.CurrentFen,
                    Message        = "Your EPC team game with {opponent} is ready: {game}."
                };

                // Jv board colors are swapped
                if (game.BoardPosition > 7)
                {
                    if (request.Color == Color.White)
                    {
                        request.Color = Color.Black;
                    }
                    else
                    {
                        request.Color = Color.White;
                    }
                }

                try
                {
                    var response = await client.Challenges.CreateGame(awayUser.LichessId, awayUser.AccessToken, request);

                    game.CurrentFen    = response.Game.InitialFen;
                    game.ChallengeUrl  = response.Game.Url;
                    game.ChallengeId   = response.Game.Id;
                    game.ChallengeJson = JsonConvert.SerializeObject(response);
                    game.IsStarted     = true;

                    gameJson.Status    = response.Game.Status.Name;
                    gameJson.IsStarted = true;

                    challengeCreated = true;
                }
                catch (Exception e)
                {
                    Log.Error(e, "Unable to create challenge");
                }
            }
            else // This has to be a pure challenge request
            {
                ChallengeRequest request = new ChallengeRequest
                {
                    Rated          = true,
                    ClockLimit     = game.Match.ClockTimeLimit,
                    ClockIncrement = game.Match.ClockIncrement,
                    Color          = game.BoardPosition % 2 == 0 ? Color.White : Color.Black,
                    Variant        = GameVariant.Standard,
                    Fen            = game.CurrentFen,
                    Message        = "Your EPC team game with {opponent} is ready: {game}."
                };

                // Jv board colors are swapped
                if (game.BoardPosition > 7)
                {
                    if (request.Color == Color.White)
                    {
                        request.Color = Color.Black;
                    }
                    else
                    {
                        request.Color = Color.White;
                    }
                }

                try
                {
                    var response = await client.Challenges.CreateChallenge(awayUser.LichessId, request);

                    game.ChallengeUrl  = response.Challenge.Url;
                    game.ChallengeId   = response.Challenge.Id;
                    game.ChallengeJson = JsonConvert.SerializeObject(response);
                    game.IsStarted     = true;

                    gameJson.Status    = response.Challenge.Status;
                    gameJson.IsStarted = true;

                    challengeCreated = true;
                }
                catch (Exception e)
                {
                    Log.Error(e, "Unable to create challenge");
                }
            }

            if (challengeCreated)
            {
                MatchUpdateViewModel vm = new MatchUpdateViewModel
                {
                    MatchId = game.MatchId,
                    Games   = new List <GameJson>(new GameJson[] { gameJson })
                };

                // Issue an immediate match update
                await _hubContext.Clients.Groups("match_" + game.Match.MatchId).SendAsync("UpdateMatches", vm);

                _context.Game.Update(game);
                await _context.SaveChangesAsync();
            }
            else
            {
                Log.Information("Challenge Url was empty");

                // This likely happens if the user AccessToken expires and Refresh fails

                await _signInManager.SignOutAsync();

                return(RedirectToAction(nameof(AdminController.Index), "Home"));
            }

            return(Redirect(game.ChallengeUrl));
        }