public override async Task OnConnectedAsync() { string accessToken = Context.GetHttpContext().Request.Query["access_token"]; if (string.IsNullOrEmpty(accessToken)) { Context.Abort(); } var player = _accountCenter.GetGamePlayer(accessToken); if (player != null) { player.ConnectionId = Context.ConnectionId; var gameCore = _gameManager.GetGameCore(GameId, Clients); if (gameCore != null) { var reg = await gameCore.RegisterPlayer(player); if (!reg) { Context.Abort(); } gameCore.Start(); await base.OnConnectedAsync(); return; } } Context.Abort(); }
public override async Task OnConnectedAsync() { var t = Context.GetHttpContext().Request.Query["Password"]; if (t != Game.Password) { Context.Abort(); return; } if (Context.GetHttpContext().Request.Query["Board"] == "true") { return; } Game.PlayerAmount++; if (Game.User1.ConnectionId == "") { Game.User1.ConnectionId = Context.ConnectionId; } else if (Game.User2.ConnectionId == "") { Game.User2.ConnectionId = Context.ConnectionId; } if (Game.PlayerAmount == 2) { await Clients.Client(Game.User1.ConnectionId).SendAsync("StartAndPlay"); await Clients.Client(Game.User2.ConnectionId).SendAsync("StartAndWait"); } }
/// <inheritdoc /> public override async Task OnConnectedAsync() { await base.OnConnectedAsync() .ConfigureAwaitFalseVoid(); if (Logger.IsEnabled(LogLevel.Information)) { Logger.LogInformation($"Account Connected: {ClaimsReader.GetAccountName(Context.User)}:{ClaimsReader.GetAccountId(Context.User)} with SignalR UserId: {Context.UserIdentifier}"); } try { foreach (var listener in OnConnectionHubListeners) { HubOnConnectionState connectionState = await listener.OnConnected(this).ConfigureAwaitFalse(); //if the listener indicated we need to abort for whatever reason we //should believe it and just abort. if (connectionState == HubOnConnectionState.Abort) { Context.Abort(); break; } } } catch (Exception e) { if (Logger.IsEnabled(LogLevel.Error)) { Logger.LogError($"Account: {ClaimsReader.GetAccountName(Context.User)}:{ClaimsReader.GetAccountId(Context.User)} failed to properly connect to hub. Error: {e.ToString()}\n\nStack: {e.StackTrace}"); } Context.Abort(); } }
public async Task StartAuth(string token) { var user = await _socket.GetUserByAccessToken(token); if (user == null) { // Send User the info that he isnt allowed Context.Abort(); return; } var foundEntry = MyUsers.AddOrUpdate(user.Id, new List <string> { Context.ConnectionId }, (key, value) => { value.Add(Context.ConnectionId); return(value); }); var groupChats = await _groupChat.GetByUserAsync(user); foreach (var groupChat in groupChats) { await Groups.AddToGroupAsync(Context.ConnectionId, "groupchat#" + groupChat.Id); } }
public override async Task OnConnectedAsync() { var id = Context.User.FindFirstValue(ClaimTypes.NameIdentifier).ToUpper(); _connections.Add(id, Context.ConnectionId); var deviceIdParsed = Guid.TryParse(Context.GetHttpContext().Request.Query["device_id"].ToString(), out Guid deviceId); if (deviceIdParsed) { using (var applicationDbContext = ApplicationDbContext.FromConnectionString(_config)) { var device = await applicationDbContext.Workers .Where(x => x.User.NormalizedUserName == id && x.DeviceId == deviceId) .FirstOrDefaultAsync(); if (device != null) { if (device.ConnexionId != null) { Context.Abort(); } else { device.ConnexionId = Context.ConnectionId; await applicationDbContext.SaveChangesAsync(); } } } } await base.OnConnectedAsync(); }
public Task SelfKickOff() { DevLog.Write($"SelfKickOff. Client: {Context.ConnectionId}", LOG_LEVEL.INFO); Context.Abort(); return(Task.CompletedTask); }
public override async Task OnConnectedAsync() { if (!Context.GetHttpContext().Request.Query.TryGetValue("proposalId", out var proposalIdQuery)) { Context.Abort(); return; } var proposalIdString = proposalIdQuery.FirstOrDefault(); if (proposalIdString == null || !int.TryParse(proposalIdString, out var proposalId)) { Context.Abort(); return; } var proposal = await _proposalDbContext.Proposals .AsNoTracking() .FirstOrDefaultAsync(p => p.Id == proposalId); if (!(await _authorizationService.AuthorizeAsync(Context.User, proposal, FormOperation.View)).Succeeded) { Context.Abort(); return; } await Groups.AddToGroupAsync(Context.ConnectionId, proposalId.ToString()); await base.OnConnectedAsync(); }
public override async Task OnDisconnectedAsync(Exception exception) { if (_users.TryGetValue(Context.User.Identity.Name, out var user)) { if (user.ConnectionId != Context.ConnectionId) { Context.Abort(); } else { _users.TryRemove(Context.User.Identity.Name, out _); var currentGames = _games.Values.Where(g => g.Players.Count(p => p.User.UserName == Context.User.Identity.Name) > 0).ToList(); foreach (var g in currentGames) { if (g.State == GameState.Waiting) { _ = _games.TryRemove(g.GameId, out _); } if (g.State != GameState.End) { g.LeftGame(Context.ConnectionId); await UpdateGameToPlayers(g); } } await base.OnDisconnectedAsync(exception); } } }
// We store the CircuitHost through a *handle* here because Context.Items is tied to the lifetime // of the connection. It's possible that a misbehaving client could cause disposal of a CircuitHost // but keep a connection open indefinitely, preventing GC of the Circuit and related application state. // Using a handle allows the CircuitHost to clear this reference in the background. // // See comment on error handling on the class definition. private async ValueTask <CircuitHost> GetActiveCircuitAsync([CallerMemberName] string callSite = "") { var handle = (CircuitHandle)Context.Items[CircuitKey]; var circuitHost = handle?.CircuitHost; if (handle != null && circuitHost == null) { // This can occur when a circuit host does not exist anymore due to an unhandled exception. // We can reject this and terminate the connection. Log.CircuitHostShutdown(_logger, callSite); await NotifyClientError(Clients.Caller, "Circuit has been shut down due to error."); Context.Abort(); return(null); } else if (circuitHost == null) { // This can occur when a circuit host does not exist anymore due to an unhandled exception. // We can reject this and terminate the connection. Log.CircuitHostNotInitialized(_logger, callSite); await NotifyClientError(Clients.Caller, "Circuit not initialized."); Context.Abort(); return(null); } return(circuitHost); }
public async Task JoinGroup(JoinKanbanHubRequest request) { var group = await(from g in Database.Query <Group>() where g.Key == request.GroupId select g).FirstOrDefaultAsync(); if (group == null) { Context.Abort(); return; } var kanbanBoard = (from kb in @group.KanbanBoards where kb.Id == request.BoardId select kb).FirstOrDefault(); if (kanbanBoard == null) { Context.Abort(); return; } var memberData = kanbanBoard.Members.Find(km => km.UserId == Context.User.Identity.Name); if (memberData == null) { Context.Abort(); return; } await Groups.AddToGroupAsync(Context.ConnectionId, $"Group/${request.GroupId}/Kanban/${request.BoardId}"); }
public override async Task OnConnectedAsync() { try { var user = Context.User as ClaimsPrincipal; var userExternalId = user.GetClaimValue("client_userExternalId"); var APIKey = user.GetClaimValue("client_APIKey"); var appInfo = await _applicationRepository.GetByAPIKeyAsync(APIKey); var userInfo = await _userRepository.GetByExternalIdAsync(appInfo.Id, userExternalId); await _distributedCache.SetObjectAsync(Context.ConnectionId, userInfo); var httpContext = Context.GetHttpContext(); var access_token = httpContext.Request.Query["access_token"].ToString(); var result = await _hubService.MakeUserOnline(userInfo.AppId, userInfo.Id, Context.ConnectionId, access_token); if (!result) { Context.Abort(); } } catch { Context.Abort(); } }
public override async Task OnConnectedAsync() { await base.OnConnectedAsync(); if (!Context.User.IsInRole(Strings.System)) { var connections = await _reliableStateManager.GetOrAddAsync <IReliableDictionary <string, string> >("Connections"); using (ITransaction tx = _reliableStateManager.CreateTransaction()) { var success = await connections.TryAddAsync(tx, Context.UserIdentifier, Context.ConnectionId); await tx.CommitAsync(); if (!success) { Context.Abort(); return; } ConnectedUserIds.Add(Context.UserIdentifier); await Groups.AddToGroupAsync(Context.ConnectionId, TenantId); await Clients.Group(TenantId).ShowUsersOnLine((await GetConnectionsDictionary(connections)).Where(x => x.Key.StartsWith(TenantId)).Count()); await Clients.Caller.ConnectionId(Context.ConnectionId); await Clients.Group(Strings.System).ConnectionsChanged(await GetConnectionsDictionary(connections)); } } else { await Groups.AddToGroupAsync(Context.ConnectionId, Strings.System); } }
internal async Task LoginAsAuthenticated(ChatUser user) { var memberShip = await _settingsRepository.Load(user.BattleTag) ?? new ChatSettings(user.BattleTag); var ban = await _banRepository.GetBannedPlayer(user.BattleTag); var nowDate = DateTime.Now.ToString("yyyy-MM-dd"); if (ban != null && string.Compare(ban.EndDate, nowDate, StringComparison.Ordinal) > 0) { await Clients.Caller.SendAsync("PlayerBannedFromChat", ban); Context.Abort(); } else { _connections.Add(Context.ConnectionId, memberShip.DefaultChat, user); await Groups.AddToGroupAsync(Context.ConnectionId, memberShip.DefaultChat); var usersOfRoom = _connections.GetUsersOfRoom(memberShip.DefaultChat); await Clients.Group(memberShip.DefaultChat).SendAsync("UserEntered", user); await Clients.Caller.SendAsync("StartChat", usersOfRoom, _chatHistory.GetMessages(memberShip.DefaultChat), memberShip.DefaultChat); } }
public override Task OnDisconnectedAsync(Exception exception) { usersConnectedToChat.Remove(Context.ConnectionId); Context.Abort(); return(base.OnDisconnectedAsync(exception)); }
public override async Task OnConnectedAsync() { if (!Session.TryLobbyController(out var connected)) { Context.Abort(); throw new InvalidOperationException($"No lobby controller found for connection {Context.ConnectionId}"); } var connection = Context.UserIdentifier; Session.Connection(connection); var lobby = connected.Lobby; if (connected.Lobby.Host == connected) { await Clients.User(connection).SendAsync("Host"); } var names = lobby.Controllers .Select(user => user.Name); await Clients.User(connection).SendAsync("Players", names); var others = lobby.IdsExcept(connected); await Clients.Users(others).SendAsync("Join", connected.Name); var allConnections = connected.Lobby.ControllerIds(); await Clients.Users(allConnections).SendAsync("HostPlayer", connected.Lobby.Host.Name); await base.OnConnectedAsync(); }
public override async Task OnConnectedAsync() { var endpointId = Context.GetHttpContext().Request.Query["ep"]; var ownerId = Context.User.Claims.FirstOrDefault(c => c.Type == "sub")?.Value; if (string.IsNullOrEmpty(endpointId) || string.IsNullOrEmpty(ownerId)) { Context.Abort(); } var connectionReferenceCreated = await _hubConnectionService.ConnectHubConnectionReferenceAsync( Guid.Parse(endpointId), Guid.Parse(ownerId), Context.ConnectionId, Context.ConnectionAborted); if (!connectionReferenceCreated) { Context.Abort(); } await NotifySourceEnpointsOfLinkConnectedState(); await base.OnConnectedAsync(); }
public override Task OnConnectedAsync() { string jwt = this._contextAccessor.HttpContext.Request.Query["access_token"]; if (this.IsAuthorized(jwt)) { this.decodeToken(jwt, out int userId, out Role role); if (usersConnectedToChat.ContainsKey(Context.ConnectionId)) { Context.Abort(); return(Task.FromException(new Exception("A connection already exist, both are removed"))); } usersConnectedToChat.Add(Context.ConnectionId, userId); return(base.OnConnectedAsync()); } if (usersConnectedToChat.ContainsKey(Context.ConnectionId)) { usersConnectedToChat.Remove(Context.ConnectionId); // token expired and trying to reconnect } Context.Abort(); return(Task.FromException(new Exception("You are not authorized"))); }
public async Task Login(string username, string password) { var isAlreadyLoggedIn = ConnectedUsers.Any(c => c.Value == username); if (isAlreadyLoggedIn) { Context.Abort(); return; } var loginPayload = new LoginModel(username, password); var token = await GetTokenFromApi(loginPayload); if (token == null) { await OnDisconnectedAsync(new Exception("Incorrect user or password")); } var name = token?.Claims.FirstOrDefault(c => c.Type == "UserName")?.Value; ConnectedUsers[Context.ConnectionId] = username; ConnectedUserTokens[username] = token; await Clients.All.SendAsync("ReceiveMessage", DateTime.Now, username, $"{username} has logged in. Count: {ConnectedUsers.Count}"); }
/// <summary> /// Checks for access token expiration on heart beats. /// </summary> /// <exception cref="InvalidOperationException"></exception> protected virtual async Task OnHeartbeatCheckTokenExpiration() { var transportFeature = Context.Features.Get <IHttpTransportFeature>(); if (transportFeature == null) { return; } // No need for LongPolling as request are being sent over to server over and over // with Authorization header in place; similar with ServerSentEvents if (transportFeature.TransportType != HttpTransportType.WebSockets) { return; } var feature = Context.Features.Get <IConnectionHeartbeatFeature>(); if (feature == null) { return; } var context = Context.GetHttpContext(); if (context == null) { throw new InvalidOperationException("The HTTP context cannot be resolved."); } // Extract the authentication ticket from the access token. // Note: this operation should be cheap as the authentication result // was already computed when SignalR invoked the authentication handler // and automatically cached by AuthenticationHandler.AuthenticateAsync(). var result = await context.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme); if (result.Ticket == null) { Context.Abort(); return; } feature.OnHeartbeat(state => { var(exp, ctx) = ((DateTime, HubCallerContext))state; // Ensure the access token token is still valid. // If it's not, abort the connection immediately. if (exp < DateTimeOffset.UtcNow) { // TODO: uncomment to break connection after token expiration; // TODO: please note, need to add additional logic on client side to handle it properly //ctx.Abort(); } }, (result.Ticket.GetExpiration(), Context)); }
public async Task Disconnect() { if (_userConnectionIdStore.TryGetValue(Context.User.GetUserId(), out var connectionId)) { await DisconnectInternal(); Context.Abort(); } }
public async Task RegisterNewUser(string userName, string roomName) { // Tries to reconnect if (ConnectionToPlayerMapping.ContainsKey(Context.ConnectionId)) { } // Make Sure that the UserName is Unique var validatedUserName = userName; while (PlayerNameToPlayerMapping.ContainsKey(validatedUserName)) { validatedUserName += new Random().Next(0, 9); } // Get or create the room Room gameRoom; if (!RoomNameToRoomMapping.ContainsKey(roomName)) { gameRoom = new Room(roomName); RoomNameToRoomMapping.Add(roomName, gameRoom); } else { gameRoom = RoomNameToRoomMapping[roomName]; } // Update model Player player = new Player { UserName = validatedUserName }; try { gameRoom.AddPlayer(player); } catch (Exception e) { await Clients.Caller.SendAsync(WebSocketActions.DISPLAY_MESSAGE, MessageTypes.ERROR, e.Message); Context.Abort(); } // Update local mappings PlayerNameToPlayerMapping.Add(validatedUserName, player); ConnectionToPlayerMapping.Add(Context.ConnectionId, validatedUserName); // Update global groups await Groups.AddToGroupAsync(Context.ConnectionId, roomName); // Notify itself await Clients.Caller.SendAsync(WebSocketActions.CONNECTION_ACCEPTED, validatedUserName, player.Equals(gameRoom.Host)); // Update game await Clients.Group(roomName).SendAsync(WebSocketActions.UPDATE_GAME, Adapter.Convert(gameRoom)); }
public virtual IList <LocalizablePropertyValues> Map(ILanguageEntity languageEntity, IList <LocalizablePropertyValues> entityLocalizableProperties) { Type t = typeof(TCommerceEntity); var commerceEntity = Activator.CreateInstance(t) as TCommerceEntity; ILanguageEntity <TSourceEntity> l = languageEntity as ILanguageEntity <TSourceEntity>; if (l == null) { Context.Abort(Context.CommerceContext.AddMessage(Context.GetPolicy <KnownResultCodes>().Error, "LanguageEntityMissing", null, "Language entity cannot be null").Result, Context); } else { MapLocalizeValues(l.Entity, commerceEntity); if (entityLocalizableProperties == null) { entityLocalizableProperties = LocalizablePropertyListManager.GetEntityProperties(t, Context); entityLocalizableProperties = entityLocalizableProperties?.Clone(); } if (entityLocalizableProperties == null || !entityLocalizableProperties.Any()) { return(new List <LocalizablePropertyValues>()); } var properties = TypePropertyListManager.GetProperties(t); foreach (var localizablePropertyValues in entityLocalizableProperties) { if (!string.IsNullOrEmpty(localizablePropertyValues.PropertyName)) { var propertyInfo = properties.FirstOrDefault(x => x.Name.Equals(localizablePropertyValues.PropertyName, StringComparison.OrdinalIgnoreCase)); if (propertyInfo != null) { var propertyValue = propertyInfo.GetValue(commerceEntity); var parameter = localizablePropertyValues.Parameters.FirstOrDefault(x => x.Key.Equals(languageEntity.Language, StringComparison.OrdinalIgnoreCase)); if (parameter == null) { parameter = new Parameter { Key = languageEntity.Language, Value = null }; localizablePropertyValues.Parameters.Add(parameter); } parameter.Value = propertyValue; } } } } return(entityLocalizableProperties); }
public override async Task OnConnectedAsync() { try { var feature = Context.Features.Get <IConnectionHeartbeatFeature>(); if (feature == null) { await _usersService.AddUserAsync(Context.ConnectionId, Context.User.SubId(), Context.User.UserName()); await base.OnConnectedAsync(); return; } var context = Context.GetHttpContext(); if (context == null) { throw new InvalidOperationException("The HTTP context cannot be resolved."); } var result = await context.AuthenticateAsync(IdentityServerAuthenticationDefaults.AuthenticationScheme); if (result.Ticket == null) { Context.Abort(); return; } var expiresClaim = result.Ticket.Principal.FindFirst(JwtClaimTypes.Expiration); if (!long.TryParse(expiresClaim.Value, out var expiresValue)) { Context.Abort(); return; } var expires = DateTimeOffset.FromUnixTimeSeconds(expiresValue); feature.OnHeartbeat(state => { var(innerExpires, connection) = ((DateTimeOffset, HubCallerContext))state; if (innerExpires < DateTimeOffset.UtcNow) { connection.Abort(); } }, (expires, Context)); await _usersService.AddUserAsync(Context.ConnectionId, Context.User.SubId(), Context.User.UserName()); await base.OnConnectedAsync(); } catch (Exception e) { Console.WriteLine($"Add user failed. Error: {e.Message}"); } }
/// <summary> /// 关闭推送 /// </summary> /// <returns></returns> public async Task Close() { // 通知客户端退出 并 禁止重连 _queue.TryAdd(":Close"); while (_queue.Count > 0) { await Task.Delay(20); } Context.Abort(); }
public Task Broadcast(string sender, string message) { if (message == "abort") { Context.Abort(); return(Task.CompletedTask); } return(Clients.All.SendAsync("NewMessage", sender, message)); }
private async Task <bool> IsConnectionValid() { if (Context?.User?.Identity?.IsAuthenticated != true || await SignInManager.UserManager.IsLockedOutAsync(RemotelyUser)) { _ = Clients.Caller.SendAsync("LockedOut"); Context.Abort(); return(false); } return(true); }
public async Task SubscribeRawMemPoolItemsInfo(string nodeIdStr) { var valid = await CheckNodeIdValidAsync(nodeIdStr); if (!valid) { Context.Abort(); } string clientId = Context.ConnectionId; await Groups.AddToGroupAsync(clientId, RawMemPoolItemsInfo_GroupNamePrefix + nodeIdStr); }
public Task <bool> DeviceCameOnline(Device device) { try { if (ServiceConnections.Any(x => x.Value.ID == device.ID)) { DataService.WriteEvent(new EventLog() { EventType = EventType.Info, OrganizationID = device.OrganizationID, Message = $"Device connection for {device?.DeviceName} was denied because it is already connected." }); return(Task.FromResult(false)); } var ip = Context.GetHttpContext()?.Connection?.RemoteIpAddress; if (ip != null && ip.IsIPv4MappedToIPv6) { ip = ip.MapToIPv4(); } device.PublicIP = ip?.ToString(); if (DataService.AddOrUpdateDevice(device, out var updatedDevice)) { Device = updatedDevice; ServiceConnections.AddOrUpdate(Context.ConnectionId, Device, (id, d) => Device); var userIDs = BrowserHub.ConnectionIdToUserLookup.Values.Select(x => x.Id); var filteredUserIDs = DataService.FilterUsersByDevicePermission(userIDs, Device.ID); var connectionIds = BrowserHub.ConnectionIdToUserLookup .Where(x => x.Value.OrganizationID == Device.OrganizationID && filteredUserIDs.Contains(x.Value.Id)) .Select(x => x.Key) .ToList(); BrowserHubContext.Clients.Clients(connectionIds).SendAsync("DeviceCameOnline", Device); return(Task.FromResult(true)); } else { // Organization wasn't found. return(Task.FromResult(false)); } } catch (Exception ex) { DataService.WriteEvent(ex, Device?.OrganizationID); } Context.Abort(); return(Task.FromResult(false)); }
public override async Task OnDisconnectedAsync(Exception exception) { UsersCount--; string token = GetToken(Context.GetHttpContext()); await Clients.Caller.SendAsync("Disconnection"); await db.UpdateLoginStateAsync(token, false); Context.Abort(); await base.OnDisconnectedAsync(exception); }
public override async Task OnConnectedAsync() { try { ConnectionInfo.Add(this.Context); await Groups.AddToGroupAsync(this.Context.ConnectionId, GroupId); } catch { Context.Abort(); } }