public async Task <TokenResponse> GoogleAuthenticateUseCase(string hackneyToken) { var validToken = _authManager.ValidateHackneyJwtToken(hackneyToken); // Check if user exists. Not? Create var userDomain = await _authManager.GetOrCreateUser(validToken).ConfigureAwait(false); // Create token and return to user if (!await _authManager.ValidateUser(userDomain.Email).ConfigureAwait(false)) { throw new ApiException("Authentication failed. Invalid token.", (int)HttpStatusCode.Unauthorized); } var user = _authManager.GetUser(); // Get roles from user groups var currentRolesList = GetCurrentUserRoles(validToken.Groups); var currentRoleIds = currentRolesList.Select(r => r.GetId()).ToList(); // Get active roles and determine ones to add or remove var activeUserRoles = await _userRolesGateway.GetUserRolesAsync(user.Id, true); var activeUserRoleIds = activeUserRoles.Select(ur => ur.RoleId).ToList(); var rolesToAdd = currentRolesList.Where(r => !activeUserRoleIds.Contains(r.GetId())) .Select(r => r.GetDisplayName()); var rolesToRemove = activeUserRoles.Where(activeUserRole => !currentRoleIds.Contains(activeUserRole.RoleId)) .ToList(); // Remove roles _userRolesGateway.RemoveUserRoles(rolesToRemove); await _dbManager.SaveAsync(); // Add new roles await _authManager.AssignRolesToUser(user.Id, rolesToAdd); // Return response with token var res = new TokenResponse { UserId = user.Id, Name = user.Name, Token = await _authManager.CreateToken().ConfigureAwait(false), Groups = validToken.Groups, Roles = currentRolesList.Select(r => r.GetDisplayName()) }; return(res); }