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

            AuthenticationFailed?.Invoke(result);
            Close();
        }
Exemplo 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);
            }
        }
Exemplo n.º 3
0
 private void passwordBox_TextChanged(object sender, TextChangedEventArgs e)
 {
     if (passwordBox.Text.Count() == 4 && passwordBox.Text != PASS_KEY)
     {
         AuthenticationFailed.Begin();
         passwordBox.Text = "";
     }
 }
 private void GoToMainViewHandler(object sender, LoggedUserModel e)
 {
     if (e.IsAuthenticated)
     {
         ExitAppRequested?.Invoke(this, e);
     }
     else
     {
         AuthenticationFailed?.Invoke(this, EventArgs.Empty);
     }
 }
Exemplo n.º 5
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;
                }
            }
        }
Exemplo n.º 7
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);
        }
Exemplo n.º 8
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();
            }
        }
Exemplo n.º 9
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;
            }
        }
Exemplo n.º 10
0
        public void Authenticate(string username, string password)
        {
            UserAccount _userAccount;
            var         authResult = TryAuthenticate(username, password, out _userAccount);

            switch (authResult)
            {
            case AuthenticationResult.Success:
            {
                connectToAccount(_userAccount);
                AuthenticationSuccess.Raise(CurrentUserAccount);
                break;
            }

            default:
            {
                AuthenticationFailed.Raise(authResult);
                break;
            }
            }
        }
Exemplo n.º 11
0
 private void passwordBox_TextChanged(object sender, TextChangedEventArgs e)
 {
     if (passwordBox.Text.Count() < 4)
     {
         return;
     }
     if (PASS_KEY == String.Empty)
     {
         PASS_KEY = passwordBox.Text;
         //add password added animation
     }
     if (passwordBox.Text != PASS_KEY)
     {
         AuthenticationFailed.Begin();
         passwordBox.Text = "";
         return;
     }
     //app.mainPage.PersonalStorageEnumerator();
     //app.mainPage.CloseDialog(0);
     //((Grid)(((Grid)this.Frame.Parent).Parent)).Visibility = Visibility.Collapsed;
     //this.Frame.Content = null;
 }
Exemplo n.º 12
0
        public async Task <(Data token, string baseUri)> Authenticate()
        {
            var timeToLiveElapsed = _lastUpdated.Add(_settings.AuthenticationTimeToLive) <= _dateTimeProvider();

            if (!_forceAuthenticate && _response != null && !timeToLiveElapsed)
            {
                return(_response.data, _response.api);
            }

            _forceAuthenticate = false;
            _authenticate?.Invoke();

            _lastUpdated = _dateTimeProvider();
            var payload = new
            {
                account = _settings.Username,
                pwd     = _settings.Password
            };
            var result = await _executeRequest(_settings.AuthenticationUri,
                                               payload,
                                               Data.CreateEmpty)
                         .ConfigureAwait(false);

            if (!result.IsSuccessful)
            {
                throw AuthenticationFailed.Create(result);
            }

            _response = LoginResponse.From(result.Content);

            if (_response.hasError || _response.code == authenticationErrorCode)
            {
                throw AuthenticationFailed.Create(_response);
            }

            return(_response.data, _response.api);
        }
Exemplo n.º 13
0
 public static bool IsAuthenticationFailed(Service service)
 {
     return(AuthenticationFailed.FirstOrDefault(s => s == service) != null);
 }
 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);
 }
Exemplo n.º 15
0
 private void MeshClientAuthenticationFailure(object sender, EventArgs args)
 {
     Logger?.Invoke("[MeshClient] Server " + PeerNode.IpPort + " authentication failed");
     AuthenticationFailed?.Invoke(this, EventArgs.Empty);
 }
Exemplo n.º 16
0
 internal void HandleAuthenticationFailed(object sender, AuthenticationFailedEventArgs args)
 {
     AuthenticationFailed?.Invoke(sender, args);
 }
Exemplo n.º 17
0
 public void TriggerAuthenticationFail()
 {
     AuthenticationFailed?.Invoke(this, EventArgs.Empty);
 }
Exemplo n.º 18
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());
        }
Exemplo n.º 19
0
 internal void HandleAuthenticationFailed(object sender, AuthenticationFailedEventArgs args)
 {
     WrappedEventHandler(() => AuthenticationFailed?.Invoke(sender, args), "AuthenticationFailed", sender);
 }
Exemplo n.º 20
0
 /// <summary>
 /// Raises the AuthenticationFailed event.
 /// </summary>
 protected void OnAuthenticationFailed()
 {
     AuthenticationFailed?.Invoke();
 }