예제 #1
0
        /// <summary>
        /// Event: on new connection.
        /// </summary>
        /// <returns></returns>
        public async override Task OnConnectedAsync()
        {
            log.Information($"{ClassName} OnConnectedAsync() called");

            // Get the auth key token.
            var    test          = Context.GetHttpContext();
            string accessAuthKey = test.Request.Query["access_token"];

            // Check banned auth keys.
            if (BannedAuthKeys.Count(x => x.Key == accessAuthKey) == 1 && BannedAuthKeys[accessAuthKey] >= BaseHubHandler <T> .MaxAuthKeyAttempts)
            {
                Context.GetHttpContext().Abort();
                return;
            }

            // Check auth token.
            AuthenticationResponse auth = Authentication.AuthenticateSession(accessAuthKey);

            if (auth.Success)
            {
                try {
                    // Add user into connection pool.
                    BaseHubHandler <T> .AddUserConnectionId(auth, Context.ConnectionId);
                }
                catch (Exception e) {
                    log.Error($"{ClassName} Error referencing User in connection pool. Exception = [{e.Message}] - StackTrace = {e.StackTrace}.");

                    Context.GetHttpContext().Abort();
                    return;
                }
            }
            else
            {
                log.Information($"{ClassName} Connection failed, bad auth for authKey = [{accessAuthKey}]");

                // Add to banned auth keys to avoid potential flood.
                if (BannedAuthKeys.Count(x => x.Key == accessAuthKey) == 0)
                {
                    BannedAuthKeys.Add(accessAuthKey, 1);
                }
                else
                {
                    BannedAuthKeys[accessAuthKey] += 1;

                    if (BannedAuthKeys[accessAuthKey] >= BaseHubHandler <T> .MaxAuthKeyAttempts)
                    {
                        log.Warning($"{ClassName} - BANNED authKey because too many attemps ({BaseHubHandler<T>.MaxAuthKeyAttempts}) = [{accessAuthKey}]");
                    }
                }

                Context.GetHttpContext().Abort();
                return;
            }

            log.Information($"{ClassName} User = [{auth.User._id}, {auth.User.Login}] successfully connected.");

            await base.OnConnectedAsync();
        }