Ejemplo n.º 1
0
        private void OnAuthenticationFailed(string[] data)
        {
            AuthenticationResult result = (AuthenticationResult)int.Parse(data[1]);

            AuthenticationFailed?.Invoke(result);
            Close();
        }
Ejemplo n.º 2
0
        private void BeginReceiveCallback(IAsyncResult results)
        {
            var state = (AuthenticationState)results.AsyncState;

            // Timeout, socket has been closed.
            if (state.client.Client == null)
            {
                return;
            }

            var packet = (AuthenticationPacket)PacketSerializer.Deserialize(state.buffer)[0];
            var auth   = state.auth;

            if (packet.version == auth.version &&
                packet.time == auth.time &&
                !string.IsNullOrEmpty(packet.response) &&
                Guid.Parse(packet.guid) == state.guid)
            {
                AuthenticationSuccess?.Invoke(state.client, packet);
            }
            else
            {
                AuthenticationFailed?.Invoke(state.client);
            }
        }
 private void GoToMainViewHandler(object sender, LoggedUserModel e)
 {
     if (e.IsAuthenticated)
     {
         ExitAppRequested?.Invoke(this, e);
     }
     else
     {
         AuthenticationFailed?.Invoke(this, EventArgs.Empty);
     }
 }
Ejemplo n.º 4
0
        public void CheckAuthentication()
        {
            try
            {
                _twitchService.AccessToken = _configurationService.OauthAccessToken;
            }
            catch (Exception e) when(e is InvalidCredentialException || e is AggregateException)
            {
                if (e is AggregateException exception && !exception.InnerExceptions.OfType <BadScopeException>().Any())
                {
                    throw;
                }

                AuthenticationFailed?.Invoke(e.Message);
            }
        }
        /// <summary>
        /// Handles the response to the <see cref="US.OpenServer.Protocols.WinAuth.WinAuthProtocolCommands.AUTHENTICATE"/>
        /// command packet.
        /// </summary>
        /// <remarks>
        /// <para>
        /// When an <see cref="US.OpenServer.Protocols.WinAuth.WinAuthProtocolCommands.AUTHENTICATED"/>
        /// response is received, notifies the <see cref="US.OpenServer.SessionBase"/> the
        /// client is authenticated enabling the session to allow execution of higher
        /// protocol layers. Finally, signals the <see cref="Authenticate(String, String, String)" />
        /// function to unblock the calling thread.
        /// </para>
        /// <para>
        /// When an <see cref="US.OpenServer.Protocols.WinAuth.WinAuthProtocolCommands.ACCESS_DENIED"/>
        /// response is received, logs the error then signals the <see cref="Authenticate(String, String, String)" />
        /// function to unblock the calling thread.
        /// </para>
        /// <para>
        /// When an <see cref="US.OpenServer.Protocols.WinAuth.WinAuthProtocolCommands.ERROR"/>
        /// response is received, logs the error then signals the <see cref="Authenticate(String, String, String)" />
        /// function to unblock the calling thread.
        /// </para>
        /// <para>
        /// Prior to authentication the session disallows all protocols commands.
        /// </para>
        /// </remarks>
        /// <param name="br">A BinaryReader that contains the command packet.</param>
        public override void OnPacketReceived(BinaryReader br)
        {
            lock (this)
            {
                if (Session == null)
                {
                    return;
                }

                WinAuthProtocolCommands command = (WinAuthProtocolCommands)br.ReadByte();
                switch (command)
                {
                case WinAuthProtocolCommands.AUTHENTICATED:
                    IsAuthenticated         = true;
                    Session.IsAuthenticated = true;

                    AuthenticationSuccessful?.Invoke(Session.Address, Session.UserName);

                    Log(Level.Info, "Authenticated.");
                    Monitor.PulseAll(this);
                    break;

                case WinAuthProtocolCommands.ACCESS_DENIED:

                    AuthenticationFailed?.Invoke(Session.Address, Session.UserName);

                    Log(Level.Notice, "Access denied.");
                    Monitor.PulseAll(this);
                    break;

                case WinAuthProtocolCommands.ERROR:
                {
                    string errorMessage = br.ReadString();

                    AuthenticationError?.Invoke(Session.Address, Session.UserName, errorMessage);

                    Log(Level.Notice, errorMessage);
                    Monitor.PulseAll(this);
                    break;
                }

                default:
                    Log(Level.Error, string.Format("Invalid or unsupported command.  Command: {0}", command));
                    break;
                }
            }
        }
Ejemplo n.º 6
0
        private async void LoginControl_SubmitButtonPressed(object sender, EventArgs e)
        {
            var blnLoginIsValid = await VerifyLoginCredentials.Execute(ShipService, Model.Name,
                                                                       Model.Password);

            if (!blnLoginIsValid)
            {
                Model.Name             = "";
                Model.Password         = "";
                View.LoginErrorVisible = true;
                AuthenticationFailed?.Invoke(this, new EventArgs());
                return;
            }

            Model.Name             = "";
            Model.Password         = "";
            View.LoginErrorVisible = false;
            AuthenticationPassed?.Invoke(this, Model.Name);
        }
Ejemplo n.º 7
0
        public void AuthenticationQuery(string L, string P)
        {
            myLogin    = L;
            myPassword = P;
            string s = RequestIssues.AuthenticationQuery(L, P);

            if (s == "OK")
            {
                AuthenticationPassed.Invoke();
            }
            else if (s == "Ethernet error")
            {
                NoInternetConnection.Invoke();
            }
            else
            {
                AuthenticationFailed.Invoke();
            }
        }
Ejemplo n.º 8
0
        private void BeginSendCallback(IAsyncResult results)
        {
            var state = (AuthenticationState)results.AsyncState;

            state.client.ReceiveTimeout = AuthenticationReceiveTimeout;

            var asyncResult = state.client.Client.BeginReceive(state.buffer, 0, state.buffer.Length, SocketFlags.None, BeginReceiveCallback, state);
            var success     = asyncResult.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(AuthenticationReceiveTimeout));

            if (!success)
            {
                AuthenticationFailed?.Invoke(state.client);

                state.client.Close();
            }
            else
            {
                state.client.ReceiveTimeout = 0;
            }
        }
Ejemplo n.º 9
0
 private void MeshClientAuthenticationFailure(object sender, EventArgs args)
 {
     Logger?.Invoke("[MeshClient] Server " + PeerNode.IpPort + " authentication failed");
     AuthenticationFailed?.Invoke(this, EventArgs.Empty);
 }
Ejemplo n.º 10
0
 internal void HandleAuthenticationFailed(object sender, AuthenticationFailedEventArgs args)
 {
     AuthenticationFailed?.Invoke(sender, args);
 }
Ejemplo n.º 11
0
 public void TriggerAuthenticationFail()
 {
     AuthenticationFailed?.Invoke(this, EventArgs.Empty);
 }
Ejemplo n.º 12
0
        public async Task RunAsync(string id)
        {
start:
            if (IsConnected)
            {
                return;
            }
            websocket_cts = new CancellationTokenSource();
            var Authenticator = RacetimeAPI.Instance.Authenticator;

            using (ws = new ClientWebSocket())
            {
                IsConnected = true;

                if (await Authenticator.Authorize())
                {
                    SendSystemMessage($"Authorization successful. Hello, {Authenticator.Identity?.Name}");
                    Authorized?.Invoke(this, null);
                }
                else
                {
                    SendSystemMessage(Authenticator.Error, true);
                    AuthenticationFailed?.Invoke(this, new EventArgs());
                    ConnectionError++;
                    goto cleanup;
                }
                //opening the socket
                ws.Options.SetRequestHeader("Authorization", $"Bearer {Authenticator.AccessToken}");
                try
                {
                    await ws.ConnectAsync(new Uri(FullSocketRoot + "ws/o/race/" + id), websocket_cts.Token);
                }
                catch (WebSocketException wex)
                {
                    ConnectionError++;
                    goto cleanup;
                }

                //initial command to sync LiveSplit
                if (ws.State == WebSocketState.Open)
                {
                    ChannelJoined?.Invoke(this, new EventArgs());
                    SendSystemMessage($"Joined Channel '{id}'");
                    try
                    {
                        ArraySegment <byte> bytesToSend = new ArraySegment <byte>(Encoding.UTF8.GetBytes("{ \"action\":\"getrace\" }"));
                        ws.SendAsync(bytesToSend, WebSocketMessageType.Text, true, CancellationToken.None);
                        await ReceiveAndProcess();

                        if (Race.StartedAt != DateTime.MaxValue)
                        {
                            Model.CurrentState.Run.Offset = DateTime.UtcNow - Race.StartedAt;
                        }
                        else
                        {
                            Model.CurrentState.Run.Offset = -Race.StartDelay;
                        }
                    }
                    catch (Exception ex)
                    {
                        SendSystemMessage("Unable to obtain Race information. Try reloading");
                        //Authenticator.AccessToken = null;
                        //Authenticator.RefreshToken = null;

                        goto cleanup;
                    }
                    try
                    {
                        var rf = new StandardComparisonGeneratorsFactory();

                        if (ConnectionError >= 0) //don't load after every reconnect
                        {
                            SendSystemMessage("Loading chat history...");
                            ArraySegment <byte> otherBytesToSend = new ArraySegment <byte>(Encoding.UTF8.GetBytes("{ \"action\":\"gethistory\" }"));
                            ws.SendAsync(otherBytesToSend, WebSocketMessageType.Text, true, CancellationToken.None);
                            await ReceiveAndProcess();
                        }
                    }
                    catch
                    {
                        SendSystemMessage("Unable to load chat history");
                    }
                }

                ConnectionError = -1;

                while (ws.State == WebSocketState.Open && !websocket_cts.IsCancellationRequested)
                {
                    try
                    {
                        await ReceiveAndProcess();
                    }
                    catch (Exception ex)
                    {
                    }
                }


                switch (ws.State)
                {
                case WebSocketState.CloseSent:
                case WebSocketState.CloseReceived:
                case WebSocketState.Closed:
                    ConnectionError = -1;
                    break;

                default:
                case WebSocketState.Aborted:
                    if (!websocket_cts.IsCancellationRequested)
                    {
                        ConnectionError++;
                    }

                    break;
                }
            }

cleanup:
            IsConnected = false;

            if (ConnectionError >= 0)
            {
                SendSystemMessage($"Auto-reconnect in {reconnectDelays[Math.Min(reconnectDelays.Length-1,ConnectionError)]}s...");
                await Task.Delay(reconnectDelays[Math.Min(reconnectDelays.Length - 1, ConnectionError)] * 1000);

                goto start;
            }
            else
            {
                SendSystemMessage("Disconnect");
            }

            websocket_cts.Dispose();

            Disconnected?.Invoke(this, new EventArgs());
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Raises the AuthenticationFailed event.
 /// </summary>
 protected void OnAuthenticationFailed()
 {
     AuthenticationFailed?.Invoke();
 }
Ejemplo n.º 14
0
 internal void HandleAuthenticationFailed(object sender, AuthenticationFailedEventArgs args)
 {
     WrappedEventHandler(() => AuthenticationFailed?.Invoke(sender, args), "AuthenticationFailed", sender);
 }
 private void Handle_AuthenticationFailed(object sender, ClientAuthenticationFailedEventArgs e)
 {
     _logger?.LogError(new EventStoreStreamsBindingException($"Authentication failed due to {e.Reason}"), $"AuthenticationFailed due to {e.Reason}: {e.Connection.ConnectionName}");
     AuthenticationFailed?.Invoke(sender, e);
 }