public async Task <ReasonResult <QueueModel> > TryJoinQueue(ClaimsUser user) { var currentGame = await _dbContext.Games .FirstOrDefaultAsync(x => x.GameState == GameState.InProgress && (x.PlayerOne == user.Id || x.PlayerTwo == user.Id)); QueueModel output; if (currentGame == null) { output = new QueueModel() { InQueueSince = await AddPlayerToQueue(user.Id), }; } else { _logger.LogInformation("Player tried to join game while already in a game, {@details}", new { GameId = currentGame.Id, UserId = user.Id }); output = new QueueModel() { GameId = currentGame.Id, }; } return(ReasonResult <QueueModel> .Success(output)); }
public async Task <string> GetJwtRequestToken() { //TBC: Stubbed claimsUser must be replaced with Login validation var claimsUser = new ClaimsUser() { UserId = Guid.NewGuid(), FirstName = "Evo", LastName = "Developer", Username = "******" }; var createdDateTimeOffset = DateTimeOffset.UtcNow; var claims = new List <Claim> { new Claim(JwtRegisteredClaimNames.Sub, claimsUser.UserId.ToString()), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, ConvertUtcDateToJsonString(createdDateTimeOffset), ClaimValueTypes.Integer64), new Claim("ClaimsUser", claimsUser.ToJson()) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Key"])); var signingCreds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature); var token = new JwtSecurityToken( issuer: _configuration["JWT:Issuer"], audience: _configuration["JWT:Audience"], claims: claims, expires: createdDateTimeOffset.AddMinutes(30).UtcDateTime, signingCredentials: signingCreds ); return(new JwtSecurityTokenHandler().WriteToken(token)); }
protected ClaimsUser GetUserObjectFromClaims(IEnumerable <Claim> userClaims) { var user = new ClaimsUser(); user.GivenName = userClaims.FirstOrDefault(claim => claim.Type == ClaimTypes.GivenName)?.Value; user.Surname = userClaims.FirstOrDefault(claim => claim.Type == ClaimTypes.Surname)?.Value; user.ObjectId = userClaims.FirstOrDefault(claim => claim.Type == ObjectIdSchemaUri)?.Value; return(user); }
public async Task <DbUser> UserByEmailOrCreateAsync(ClaimsUser claimsUser) { claimsUser.ThrowIfNull(nameof(claimsUser)); DbUser dbUser = await ByEmailOrNullAsync(claimsUser.Email) ?? await CreateUserAsync(claimsUser); return(dbUser); }
public AuthenticationViewModel(ClaimsUser claimsUser) { if (claimsUser == null) { IsAuthenticated = false; return; } IsAuthenticated = claimsUser.IsAuthenticated; Name = claimsUser.Name; PictureUri = claimsUser.PictureUri; }
public void OnAuthorization(AuthorizationFilterContext context) { var user = new ClaimsUser(context.HttpContext.User); if (!user.HasAuth) { throw new AuthenticationException("You have to be authorized to execute the operation"); } if (user.Role < _minimalRole) { throw new NoPermissionsException("You are not allowed to interact with this action"); } }
public AuthorizationManager( IUserClaimsProvider claimsProvider, IUserRepository userRepository) { _userRepository = userRepository; if (claimsProvider.WithinWebRequest()) { _executionWithinBackgroundTask = false; _claimsUser = new ClaimsUser(claimsProvider.GetUserClaims()); } else { _executionWithinBackgroundTask = true; } }
public async Task <ReasonResult <GameModel> > GetGameByIdAsync(int id, ClaimsUser user) { var game = await _dbContext.Games.FirstOrDefaultAsync(x => x.Id == id); if (game == null) { return(ReasonResult <GameModel> .NotFound()); } if (game.PlayerOne != user.Id && game.PlayerTwo != user.Id) { return(ReasonResult <GameModel> .NotFound()); } return(ReasonResult <GameModel> .Success(new GameModel(game))); }
public async Task <IActionResult> LoginViaGoogleCallbackAsync() { var result = await HttpContext.AuthenticateAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme); if (result?.Succeeded != true) { throw new InvalidOperationException("External authentication error"); } if (result.Principal == null) { throw new InvalidOperationException("External authentication error"); } var externalUser = new ClaimsUser(result.Principal); // try to determine the unique id of the external user - the most common claim type for that are the sub claim and the NameIdentifier // depending on the external provider, some other claim type might be used if (externalUser.Email == null) { throw new ResourceNotFoundException("Unknown userid"); } // use externalProvider and externalUserId to find your user, or provision a new user DbUser user = await _userIdentityService.UserByEmailOrCreateAsync(externalUser); await _signInManager.SignInAsync(user, true); await _events.RaiseAsync(new UserLoginSuccessEvent( username : user.UserName, subjectId : user.Id.ToString(), name : user.UserName)); // delete temporary cookie used during external authentication await HttpContext.SignOutAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme); var returnUrl = result.Properties.Items["returnUrl"]; if (string.IsNullOrEmpty(returnUrl)) { returnUrl = Url.Action("Index", "Home"); } return(Redirect(returnUrl)); }
// public is for test purposes. public async Task <DbUser> CreateUserAsync(ClaimsUser claimsUser) { _emailDomainValidatorService.Validate(claimsUser.Email); var user = new DbUser { UserName = claimsUser.Email, Email = claimsUser.Email, FirstName = claimsUser.FirstName, LastName = claimsUser.LastName, EmailConfirmed = true }; IdentityResult createUserResult = await _userManager.CreateAsync(user); if (!createUserResult.Succeeded) { throw CreateException($"Cannot create new user '{claimsUser.Email}'\r\n", createUserResult); } string role = (await ChooseUserRoleAsync()).ToString(); IdentityResult roleAddingResult = await _userManager.AddToRoleAsync(user, role); if (!roleAddingResult.Succeeded) { throw CreateException($"Cannot add role '{role}' to user '{claimsUser.Email}'\r\n", roleAddingResult); } var claimsAddingResult = await _userManager.AddClaimsAsync( user : user, claims : claimsUser.Claims().Concat(user.Claims(role))); if (!claimsAddingResult.Succeeded) { throw CreateException($"Cannot add claims to user '{claimsUser.Email}'\r\n", claimsAddingResult); } return(user); }
public async Task <ReasonResult <GameModel> > TakeTurnAsync(int id, int turnX, int turnY, ClaimsUser user) { var game = await _dbContext.Games .FirstOrDefaultAsync(x => x.Id == id); if (game == null) { return(ReasonResult <GameModel> .NotFound()); } BoardPlayer player; if (game.PlayerOne == user.Id) { player = BoardPlayer.PlayerOne; } else if (game.PlayerTwo == user.Id) { player = BoardPlayer.PlayerTwo; } else { return(ReasonResult <GameModel> .NotFound()); } if (game.GameState != GameState.InProgress) { _logger.LogInformation("Player tried to take turn on game with incorrect state, {@details}", new { GameId = game.Id, GameState = game.GameState, UserId = user.Id, }); return(ReasonResult <GameModel> .BadRequest(new[] { GameInWrongState })); } var oldDecompressedBoardState = new DecompressedBoardState(game.BoardHistory); var takeTurnResult = oldDecompressedBoardState.TryTakeTurn(turnX, turnY, player, out var newDecompressedBoardState); switch (takeTurnResult) { case TakeTurnResult.Success: { _logger.LogInformation("Player took turn, {@details}", new { GameId = game.Id, UserId = user.Id, GameState = game.GameState, X = turnX, Y = turnY, OldBoardHistory = oldDecompressedBoardState.BoardHistory, NewBoardHistory = newDecompressedBoardState.BoardHistory, Snapshot = newDecompressedBoardState.ToString(), }); UpdateGameUsingDecompressedBoardState(game, newDecompressedBoardState); await _dbContext.SaveChangesAsync(); return(ReasonResult <GameModel> .Success(new GameModel(game))); } case TakeTurnResult.NotInProgress: return(ReasonResult <GameModel> .BadRequest(new[] { GameInWrongState })); case TakeTurnResult.TileAlreadySet: return(ReasonResult <GameModel> .BadRequest(new[] { TileAlreadySet })); case TakeTurnResult.WrongPlayer: return(ReasonResult <GameModel> .BadRequest(new[] { ActingOnWrongTurn })); default: throw new Exception($"Unknown failure state reached during {nameof(DecompressedBoardState)}.{nameof(DecompressedBoardState.TryTakeTurn)}"); } }
public IndexViewModel(ClaimsUser claimsUser) : base(claimsUser) { }
public QuestionViewModel(ClaimsUser claimsUser) : base(claimsUser) { }