public void Bind(Host host) { _host = host; if (_isClient) { host.AddHandler((short)AuthMType.ChalangeSuccess, SendPwdHash); host.AddHandler((short)AuthMType.ChalangeFailed, (m, e) => { if (OnAuthFailed != null) { OnAuthFailed.Invoke("Логин не найден"); } }); host.AddHandler((short)AuthMType.AuthFailed, (m, e) => { if (OnAuthFailed != null) { OnAuthFailed.Invoke("Пароль не подошел"); } }); host.AddHandler((short)AuthMType.AuthSuccess, (m, e) => { if (OnAuthSuccess != null) { OnAuthSuccess.Invoke(); } }); } else { host.AddHandler((short)AuthMType.Chalange, ChalangeHandler); host.AddHandler((short)AuthMType.PwdHash, CheckHash); } }
private void OnAuthReceived(object sender, Token token) { if (string.IsNullOrEmpty(token?.AccessToken)) { OnAuthFailure?.Invoke(this, new AuthFailureEventArgs("Exchange token not returned by server.")); return; } if (token.HasError()) { OnAuthFailure?.Invoke(this, new AuthFailureEventArgs(token.Error)); return; } _lastToken = token; _lastWebApi?.Dispose(); _lastWebApi = new SpotifyWebAPI() { Token = _lastToken }; _lastAuth.Stop(); OnAuthSuccess?.Invoke(this, AuthSuccessEventArgs.Empty); _authWait.Set(); }
public bool Auth(string login, string password) { _session = SendApiRequest($"login={login}&password={password}", "auth", Session.FromJson); if (_session == null) { OnAuthFailed?.Invoke(); return(false); } _session.User.Password = password; OnAuthSuccess?.Invoke(); return(true); }
/// <summary> /// Signs up a new user to Firebase /// </summary> /// <param name="email">User's email</param> /// <param name="password">User's password</param> /// <param name="callback">Executes if the user was created successfully, passes info on the newly created user</param> public static void SignUp(string email, string password, OnAuthSuccess callback) { var payload = $"{{\"email\":\"{email}\",\"password\":\"{password}\",\"returnSecureToken\":true}}"; RestClient.Post( $"https://identitytoolkit.googleapis.com/v1/accounts:signUp?key={FirebaseInitializer.FirebaseInfo.apiKey}", payload).Then( response => { var userInfo = new Dictionary <string, string>(); SerializationHandler.FromJSONToObject(response.Text, out userInfo); callback(userInfo); }).Catch(Debug.Log); }
public void InitializeChromium(object bindable, EventHandler browserIsBrowserInitializedChanged, TabControl tabControl) { try { Logger.Info("Creating Chromium instance.."); _tabControl = tabControl; // Useful: https://github.com/cefsharp/CefSharp/blob/cefsharp/79/CefSharp.Example/CefExample.cs#L208 Cef.EnableHighDPISupport(); // TODO: Read and analyze https://github.com/cefsharp/CefSharp/issues/2246 -- Is this the correct way to do things in the future? CefSharpSettings.WcfEnabled = true; BrowserControl = new ChromiumWebBrowser(GetSiteUri()); // TODO: browser.JavascriptObjectRepository.ObjectBoundInJavascript += (sender, e) => BrowserControl.JavascriptObjectRepository.Settings.LegacyBindingEnabled = true; BrowserControl.JavascriptObjectRepository.Register("core", bindable, isAsync: false, options: BindingOptions.DefaultBinder); BrowserControl.IsBrowserInitializedChanged += browserIsBrowserInitializedChanged; BrowserControl.FrameLoadEnd += (sender, args) => browserIsBrowserInitializedChanged(this, args); ; var requestHandler = new CefRequestHandler(); requestHandler.OnAuthentication += (sender, args) => OnAuthSuccess?.Invoke(sender, args); BrowserControl.RequestHandler = requestHandler; BrowserControl.LifeSpanHandler = new AzureOnClosePopupHijack(); Logger.Info("Chromium created.."); } catch (System.IO.FileNotFoundException ex) { MessageBox.Show("Error \"File Not Found\" loading Chromium, did you forget to install Visual C++ runtimes?\n\nvc_redist86 in the IA folder.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); Logger.Warn(ex.Message); Logger.Warn(ex.StackTrace); throw; } catch (IOException ex) { MessageBox.Show("Error loading Chromium, did you forget to install Visual C++ runtimes?\n\nvc_redist86 in the IA folder.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); Logger.Warn(ex.Message); Logger.Warn(ex.StackTrace); throw; } catch (Exception ex) { MessageBox.Show("Unknown error loading Chromium, please see log file for more information.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); Logger.Warn(ex.Message); Logger.Warn(ex.StackTrace); throw; } }
/// <summary> /// Refreshes the access for a SpotifyWebAPI returned by this factory. /// </summary> /// <returns></returns> public async Task RefreshAuthAsync() { Token token = await lastAuth.RefreshAuthAsync(lastToken.RefreshToken); if (token == null) { OnAuthFailure?.Invoke(this, new AuthFailureEventArgs($"Token not returned by server.")); } else if (token.HasError()) { OnAuthFailure?.Invoke(this, new AuthFailureEventArgs($"{token.Error} {token.ErrorDescription}")); } else if (string.IsNullOrEmpty(token.AccessToken)) { OnAuthFailure?.Invoke(this, new AuthFailureEventArgs("Token had no access token attached.")); } else { lastWebApi.AccessToken = token.AccessToken; OnAuthSuccess?.Invoke(this, new AuthSuccessEventArgs()); } }
/// <summary> /// Event handler to get new message from socket /// </summary> private void Transport_OnNewMessage(string mess) { try { OnNewMessage?.Invoke(mess); // check authorization var request_auth = new MessGetAuthorization(); if (request_auth.Parse(mess)) { logger.Debug(mess); if (request_auth.IsNeedAuthorize) { logger.Debug("This is authorization request"); OnAuthRequest?.Invoke(); request_auth.GenerateResponse(public_key, private_key); Send(JsonConvert.SerializeObject(request_auth)); } else { if (request_auth.IsAuthorizeOk) { logger.Info("Authorization successful"); OnAuthSuccess?.Invoke(); } else { logger.Error("Authorization is invalid"); OnAuthFail?.Invoke(); } } return; } logger.Debug(mess.Length > LogMessSize ? mess.Substring(1, LogMessSize) + "..." : mess); // parse result var request = JsonConvert.DeserializeObject <MessGet>(mess); switch (request.Key.Proc) { case ProcType.Pairs: OnDataPairs?.Invoke(JsonConvert.DeserializeObject <MessGetPairs>(mess)); break; case ProcType.PairsDetail: OnDataPairsDetail?.Invoke(JsonConvert.DeserializeObject <MessGetPairsDetail>(mess)); break; case ProcType.Orderbook: OnDataOrderbook?.Invoke(JsonConvert.DeserializeObject <MessGetOrderbook>(mess)); break; case ProcType.RecentTrades: OnDataRecentTrades?.Invoke(JsonConvert.DeserializeObject <MessGetRecentTrades>(mess)); break; case ProcType.LastPrice: OnDataLastPrice?.Invoke(JsonConvert.DeserializeObject <MessGetLastPrice>(mess)); break; case ProcType.PriceDay: case ProcType.PriceWeek: case ProcType.PriceMonth: OnDataPriceByTime?.Invoke(JsonConvert.DeserializeObject <MessGetPriceByTime>(mess)); break; case ProcType.BoxState: OnDataBoxState?.Invoke(JsonConvert.DeserializeObject <MessGetBoxState>(mess)); break; case ProcType.Balances: OnDataBalances?.Invoke(JsonConvert.DeserializeObject <MessGetBalances>(mess)); break; case ProcType.Balance: OnDataBalance?.Invoke(JsonConvert.DeserializeObject <MessGetBalance>(mess)); break; case ProcType.Orders: OnDataOrders?.Invoke(JsonConvert.DeserializeObject <MessGetOrders>(mess)); break; case ProcType.Deals: OnDataDeals?.Invoke(JsonConvert.DeserializeObject <MessGetDeals>(mess)); break; case ProcType.Messages: OnDataMessages?.Invoke(JsonConvert.DeserializeObject <MessGetMessages>(mess)); break; } } catch (Exception ex) { logger.Fatal(ex, "Exception parse new message"); } }
/// <summary> /// Gets an authorized and ready to use SpotifyWebAPI by following the SecureAuthorizationCodeAuth process with its current settings. /// </summary> /// <returns></returns> public async Task <SpotifyWebAPI> GetWebApiAsync() { return(await Task <SpotifyWebAPI> .Factory.StartNew(() => { bool currentlyAuthorizing = true; // Cancel any ongoing get web API requests CancelGetWebApiRequest(); lastAuth = new TokenSwapAuth( exchangeServerUri: ExchangeServerUri, serverUri: HostServerUri, scope: Scope, htmlResponse: HtmlResponse) { ShowDialog = ShowDialog, MaxGetTokenRetries = MaxGetTokenRetries, TimeAccessExpiry = AutoRefresh || TimeAccessExpiry }; lastAuth.AuthReceived += async(sender, response) => { if (!string.IsNullOrEmpty(response.Error) || string.IsNullOrEmpty(response.Code)) { // We only want one auth failure to be fired, if the request timed out then don't bother. if (!webApiTimeoutTimer.Enabled) { return; } OnAuthFailure?.Invoke(this, new AuthFailureEventArgs(response.Error)); currentlyAuthorizing = false; return; } lastToken = await lastAuth.ExchangeCodeAsync(response.Code); if (lastToken == null || lastToken.HasError() || string.IsNullOrEmpty(lastToken.AccessToken)) { // We only want one auth failure to be fired, if the request timed out then don't bother. if (!webApiTimeoutTimer.Enabled) { return; } OnAuthFailure?.Invoke(this, new AuthFailureEventArgs("Exchange token not returned by server.")); currentlyAuthorizing = false; return; } if (lastWebApi != null) { lastWebApi.Dispose(); } lastWebApi = new SpotifyWebAPI() { TokenType = lastToken.TokenType, AccessToken = lastToken.AccessToken }; lastAuth.Stop(); OnAuthSuccess?.Invoke(this, AuthSuccessEventArgs.Empty); currentlyAuthorizing = false; }; lastAuth.OnAccessTokenExpired += async(sender, e) => { if (TimeAccessExpiry) { OnAccessTokenExpired?.Invoke(sender, AccessTokenExpiredEventArgs.Empty); } if (AutoRefresh) { await RefreshAuthAsync(); } }; lastAuth.Start(); OnExchangeReady?.Invoke(this, new ExchangeReadyEventArgs { ExchangeUri = lastAuth.GetUri() }); if (OpenBrowser) { lastAuth.OpenBrowser(); } webApiTimeoutTimer = new System.Timers.Timer { AutoReset = false, Enabled = true, Interval = Timeout * 1000 }; while (currentlyAuthorizing && webApiTimeoutTimer.Enabled) { ; } // If a timeout occurred if (lastWebApi == null && currentlyAuthorizing) { OnAuthFailure?.Invoke(this, new AuthFailureEventArgs("Authorization request has timed out.")); } return lastWebApi; })); }