private static void EnrichSalesOrder(BasicSalesOrder basicSalesOrder, string id) { var authApi = new AuthApi(SiteURL); var cookieContainer = new CookieContainer(); authApi.Configuration.ApiClient.RestClient.CookieContainer = cookieContainer; try { LogIn(authApi); var soApi = new SalesOrderApi(); List <SalesOrder> soOrders = soApi.SalesOrderGetList(filter: $"OrderNbr eq '{basicSalesOrder.OrderNbr}'"); Console.WriteLine($"Enriched SOOrder for OrderNbr {basicSalesOrder.OrderNbr}"); Console.WriteLine($"Id: {soOrders[0].Id.Value}"); Console.WriteLine($"Status: {soOrders[0].Status.Value}"); Console.WriteLine($"Order Number: {soOrders[0].OrderNbr.Value}"); Console.WriteLine($"Order Type: {soOrders[0].OrderType.Value}"); Console.WriteLine($"Order Quantity: {soOrders[0].OrderedQty.Value}"); Console.WriteLine($"Order Total: {soOrders[0].OrderTotal.Value}"); Console.WriteLine($"CustomerId: {soOrders[0].CustomerID.Value}"); Console.WriteLine($"Last Modified: {soOrders[0].LastModified.Value}"); } catch (Exception e) { Console.WriteLine(e.Message); } finally { //we use logout in finally block because we need to always logut, even if the request failed for some reason authApi.AuthLogout(); } }
public HiPOSHelper() { if (string.IsNullOrEmpty(siteSettings.HiPOSAppId)) { string siteUrl = siteSettings.SiteUrl; string str2 = string.Empty; if (siteUrl.IndexOf("http") < 0) { str2 = "http://" + siteSettings.SiteUrl + "/API/HiPOSAPI.ashx?action=auth"; } else { str2 = siteSettings.SiteUrl + "/API/HiPOSAPI.ashx?action=auth"; } AuthResult auth = AuthApi.GetAuth(siteUrl, str2); if (auth.error != null) { throw new Exception(auth.error.message); } siteSettings = SettingsManager.GetMasterSettings(); AccessTokenContainer.Register(siteSettings.HiPOSAppId, siteSettings.HiPOSAppSecret); } else { AccessTokenContainer.Register(siteSettings.HiPOSAppId, siteSettings.HiPOSAppSecret); } }
protected virtual async void DoValidate() { await Task.Run(async() => { try { var user = Email.Trim().ToLower(); var pass = Code.Trim(); IsBusy = true; var result = await AuthApi.VerifyWithCode(user, pass); IsBusy = false; if (result.Result == CognitoResult.Ok) { await AccountVerified(); } else { await BadCode(); } } catch (Exception e) { Console.WriteLine($"Exception in {this.GetType().Name} {e.GetType().Name}:{e.Message}"); } }); }
public AccountDropDownViewModel(MainWindowViewModel mainVm, DataManager cfg, AuthApi authApi, LoginManager loginMgr) { _mainVm = mainVm; _cfg = cfg; _authApi = authApi; _loginMgr = loginMgr; this.WhenAnyValue(x => x._loginMgr.ActiveAccount) .Subscribe(_ => { this.RaisePropertyChanged(nameof(LoginText)); this.RaisePropertyChanged(nameof(AccountSwitchText)); this.RaisePropertyChanged(nameof(LogoutText)); this.RaisePropertyChanged(nameof(AccountControlsVisible)); this.RaisePropertyChanged(nameof(AccountSwitchVisible)); }); _loginMgr.Logins.Connect().Subscribe(_ => { this.RaisePropertyChanged(nameof(LogoutText)); this.RaisePropertyChanged(nameof(AccountSwitchVisible)); }); var filterObservable = this.WhenAnyValue(x => x._loginMgr.ActiveAccount) .Select(MakeFilter); _loginMgr.Logins .Connect() .Filter(filterObservable) .Transform(p => new AvailableAccountViewModel(p)) .Bind(out _accounts) .Subscribe(); }
public async Task SimpleSignUp() { // ARRANGE var email = Configuration["email"]; var username = Configuration["username"]; var password = Configuration["password"]; var appId = Configuration["appid"]; var config = new Config(appId); var localData = new LocalData(new FakeLocalData(), new FakeLocalData()); var logger = new TestLogger(_output); var api = new AuthApi(config); var ws = new WsWrapper(config, api, logger, localData); var auth = new AuthMain(config, api, localData, ws, logger); var request = new SignUpRequest { Username = username, Password = password, RememberMe = "none", Email = email }; // ACT var response = await auth.SignUp(request); // ASSERT Assert.NotNull(response.UserId); Assert.NotNull(response.Username); Assert.NotNull(response.Email); }
private async void Authorize(string tokenId) { LogMsg(string.Format("GoogleAuth.Authorize called: {0}", tokenId)); var apiInstance = new AuthApi("https://auth.angusmf.com"); try { var response = await apiInstance.GoogleAsyncWithHttpInfo(new UserView(tokenId)); if (response.StatusCode == 200) { LogMsg(string.Format("Success! Token = {0}", response.Data.Token)); //MessageBroker.Default.Publish(new ClientAuthTokenReceived(response.Data.Token, null)); MessageBroker.Default.Publish(new ServerAuthTokenReceived(response.Data.Token)); } else { LogMsg(string.Format("Error: Received response code {0} during authorization", response.StatusCode)); } } catch (ApiException e) { LogMsg(string.Format("e.Data: {0} \n e.ErrorCode: {1} \n e.ErrorContent: {2} \n e.Message: {3}", e.Data, e.ErrorCode, e.ErrorContent, e.Message)); } catch (Exception e) { LogMsg("Exception when calling apiInstance.AuthenticateWithHttpInfo: " + e.Message); } }
public LoginForm() { InitializeComponent(); _storageService = StorageService.Instance; _authApi = AuthApi.Instance; }
public static async Task <bool> DoLogin <T>( T vm, AuthenticateResult resp, LoginManager loginMgr, AuthApi authApi) where T : BaseLoginViewModel, IErrorOverlayOwner { if (resp.IsSuccess) { var loginInfo = resp.LoginInfo; var oldLogin = loginMgr.Logins.Lookup(loginInfo.UserId); if (oldLogin.HasValue) { // Already had this login, apparently. // Thanks user. // // Log the OLD token out since we don't need two of them. // This also has the upside of re-available-ing the account // if the user used the main login prompt on an account we already had, but as expired. await authApi.LogoutTokenAsync(oldLogin.Value.LoginInfo.Token.Token); loginMgr.ActiveAccountId = loginInfo.UserId; loginMgr.UpdateToNewToken(loginMgr.ActiveAccount !, loginInfo.Token); return(true); } loginMgr.AddFreshLogin(loginInfo); loginMgr.ActiveAccountId = loginInfo.UserId; return(true); } vm.OverlayControl = new AuthErrorsOverlayViewModel(vm, "Unable to log in", resp.Errors); return(false); }
/// <summary> /// /// </summary> /// <param name="apiKey">An API Key from Last.fm. See http://www.last.fm/api/account </param> /// <param name="apiSecret">An API Secret from Last.fm. See http://www.last.fm/api/account </param> /// <param name="sessionKey">An authorized Last.fm Session Key. See <see cref="GetSession"/></param> /// <exception cref="ArgumentNullException"/> public Scrobbler(string apiKey, string apiSecret, string sessionKey = null) { if (string.IsNullOrEmpty(apiKey)) { throw new ArgumentNullException("apiKey"); } if (string.IsNullOrEmpty(apiSecret)) { throw new ArgumentNullException("apiSecret"); } Authentication = new Authentication { ApiKey = apiKey, ApiSecret = apiSecret }; if (!string.IsNullOrEmpty(sessionKey)) { Authentication.Session = new Session { Key = sessionKey } } ; AuthApi = new AuthApi(); TrackApi = new TrackApi(); }
protected virtual async void DoVerify() { await Task.Run(async() => { try { var user = SessionStore.UserName.Trim().ToLower(); var pass = Password.Trim(); IsBusy = true; var result = await AuthApi.UpdatePassword(user, pass, SessionStore.SessionId); IsBusy = false; if (result.Result == CognitoResult.Ok) { await PasswordUpdated(); } else { await PasswordUpdateFailed(); } } catch (Exception e) { Console.WriteLine($"Exception in {this.GetType().Name} {e.GetType().Name}:{e.Message}"); } }); }
public AuthService() { instance = this; IsLoggedIn = false; authApi = new AuthApi(); }
public AuthMain(Config config, AuthApi api, LocalData localData, WsWrapper ws, ILogger logger) { _config = config; _api = api; _localData = localData; _logger = logger; _ws = ws; }
async Task <HttpClient> InitHttpClient(HttpClient httpClient) { httpClient.DefaultRequestHeaders.Add("x-api-key", ApiKey); var token = await AuthApi.Authenticate(httpClient, BaseUrl, credentials); httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token); return(httpClient); }
public UserInfo GetUserInfo() { var apiInstance = new AuthApi(ServerUrl); var serverEnvironment = GetServerEnvironment(); var userInfo = apiInstance.GetUserInfo(ApiVersion, ServerType, OrganizationName, serverEnvironment, ServerUrl, Username, Password); return(userInfo); }
public WsWrapper(Config config, AuthApi api, ILogger logger, LocalData localData) { _config = config; _api = api; _logger = logger; _localData = localData; _clientId = Guid.NewGuid().ToString(); _pendingRequests = new Dictionary <string, WsRequest>(); }
public HttpApi(string url) { _config.BasePath = url; Default = new DefaultApi(_config); Test = new TestApi(_config); Auth = new AuthApi(_config); DBDatas = new DbDatasApi(_config); DBUsers = new DbUsersApi(_config); }
private static void LogIn(AuthApi authApi) { authApi.AuthLogin(new Credentials(Username, Password, Tenant)); Console.WriteLine("Logged In..."); Configuration.Default = new Configuration(Default._18._200._001.EndpointHelper.CombineEndpointURL(SiteURL)); //share cookie container between API clients because we use different client for authentication and interaction with endpoint Configuration.Default.ApiClient.RestClient.CookieContainer = authApi.Configuration.ApiClient.RestClient.CookieContainer; }
protected virtual void GetAuthenticationToken() { if (AuthenticationToken != null && AuthenticationToken.IsValid()) { return; } AuthenticationToken = AuthApi.GetToken(Authentication); }
public void AuthTestShouldCallCorrectEndpoint() { var requestHandlerMock = ExecRequestMock <AuthTestResponse>("/auth.test"); var subject = new AuthApi(requestHandlerMock.Object); var result = subject.Test(); requestHandlerMock.Verify(); Assert.NotNull(result); }
public void AuthTestShouldCallCorrectEndpoint() { var requestHandlerMock = ExecRequestMock<AuthTestResponse>("/auth.test"); var subject = new AuthApi(requestHandlerMock.Object); var result = subject.Test(); requestHandlerMock.Verify(); Assert.NotNull(result); }
internal override async void OnSettingsChanged(object?sender, UserSettingsEventArgs e) { if (e.ChangedKey != nameof(UserSettings.AllMaps)) { return; } HasNotifications = (await AuthApi.CurrentUserInfo()).HasNotifications; StateHasChanged(); }
public UserInfo GetDocumentsAuthToken(string username, string password) { var apiInstance = new AuthApi(ServerUrl); string serverType = "Documents"; var serverEnvironment = GetServerEnvironment(); var userInfo = apiInstance.GetUserInfo(ApiVersion, serverType, OrganizationName, serverEnvironment, ServerUrl, username, password); return(userInfo); }
protected virtual async void DoSignIn() { await Task.Run(async() => { try { var user = UserName?.Trim().ToLower(); var pass = Password?.Trim(); IsBusy = true; var result = await AuthApi.SignIn(user, pass); IsBusy = false; if (result.Result == CognitoResult.Ok) { SessionStore.UserName = user; SessionStore.AccessToken = result.AccessToken; SessionStore.IdToken = result.IdToken; SessionStore.RefreshToken = result.RefreshToken; SessionStore.SessionId = result.SessionId; SessionStore.TokenIssuedServer = result.TokenIssued; SessionStore.TokenExpiresServer = result.Expires; await OnAuthenticated(); } else if (result.Result == CognitoResult.NotAuthorized) { await OnNotAuthorized(); } else if (result.Result == CognitoResult.NotConfirmed) { await OnConfirmationRequired(); } else if (result.Result == CognitoResult.UserNotFound) { await OnNoSuchUser(); } else if (result.Result == CognitoResult.PasswordChangeRequred) { SessionStore.UserName = user; SessionStore.AccessToken = result.AccessToken; SessionStore.IdToken = result.IdToken; SessionStore.RefreshToken = result.RefreshToken; SessionStore.SessionId = result.SessionId; SessionStore.TokenIssuedServer = result.TokenIssued; SessionStore.TokenExpiresServer = result.Expires; await OnPasswordChangeRequired(); } } catch (Exception e) { Console.WriteLine($"Exception in {this.GetType().Name} {e.GetType().Name}:{e.Message}"); } }); }
public AuthApiTests(SynologyFixture synologyFixture) { _fixture = new Fixture(); _httpTest = new HttpTest(); _synologyFixture = synologyFixture; _apiInfo = _synologyFixture.ApisInfo.FileStationUploadApi; _authApi = new AuthApi( synologyFixture.SynologyHttpClient, _apiInfo); }
public void AuthServiceContructor_ShouldReturnTheObject() { // Arrange: _loggerMock = new Mock <ILogger <AuthApi> >(); var config = GetConfiguration(); // Act: _objectToTest = new AuthApi(config, _loggerMock.Object); // Assert: Assert.NotNull(_objectToTest); }
public RegisterViewModel(DataManager cfg, MainWindowLoginViewModel parentVm, AuthApi authApi, LoginManager loginMgr) { _cfg = cfg; ParentVM = parentVm; _authApi = authApi; _loginMgr = loginMgr; this.WhenAnyValue(x => x.EditingUsername, x => x.EditingPassword, x => x.EditingPasswordConfirm, x => x.EditingEmail) .Subscribe(UpdateInputValid); }
public string GetToken() { AuthApi authAPI = new AuthApi(ConnectionSettings.ServerURL); var apiResponse = authAPI.ApiV1AuthTokenPostWithHttpInfo(new LoginModel(ConnectionSettings.AgentUsername, ConnectionSettings.AgentPassword)); Configuration.AccessToken = apiResponse.Data.Token.ToString(); ConfigurationUpdatedEvent?.Invoke(this, Configuration); ConnectionSettings.AgentId = apiResponse.Data.AgentId; return(Configuration.AccessToken); }
public static void ExampleMethod(string siteURL, string username, string password, string tenant = null, string branch = null, string locale = null) { var authApi = new AuthApi(siteURL, requestInterceptor: RequestLogger.LogRequest, responseInterceptor: RequestLogger.LogResponse); try { var configuration = authApi.LogIn(username, password, tenant, branch, locale); Console.WriteLine("Reading Accounts..."); var accountApi = new AccountApi(configuration); var accounts = accountApi.GetList(top: 5); foreach (var account in accounts) { Console.WriteLine("Account Nbr: " + account.AccountCD.Value + ";"); } Console.WriteLine("Reading Sales Order by Keys..."); var salesOrderApi = new SalesOrderApi(configuration); var order = salesOrderApi.GetByKeys(new List <string>() { "SO", "SO005207" }); Console.WriteLine("Order Total: " + order.OrderTotal.Value); var shipmentApi = new ShipmentApi(configuration); var shipment = shipmentApi.GetByKeys(new List <string>() { "002805" }); Console.WriteLine("ConfirmShipment"); shipmentApi.WaitActionCompletion(shipmentApi.InvokeAction(new ConfirmShipment(shipment))); Console.WriteLine("CorrectShipment"); shipmentApi.WaitActionCompletion(shipmentApi.InvokeAction(new CorrectShipment(shipment))); } catch (Exception e) { Console.WriteLine(e.Message); } finally { //we use logout in finally block because we need to always logut, even if the request failed for some reason if (authApi.TryLogout()) { Console.WriteLine("Logged out successfully."); } else { Console.WriteLine("An error occured during loguot."); } } }
public LoginViewModel(MainWindowLoginViewModel parentVm, AuthApi authApi, LoginManager loginMgr) { BusyText = "Logging in..."; _authApi = authApi; _loginMgr = loginMgr; ParentVM = parentVm; this.WhenAnyValue(x => x.EditingUsername, x => x.EditingPassword) .Subscribe(s => { IsInputValid = !string.IsNullOrEmpty(s.Item1) && !string.IsNullOrEmpty(s.Item2); }); }
/// <summary> /// Creates new instance of Untappd API wrapper. /// </summary> /// <param name="clientId">Public API key.</param> /// <param name="clientSecret">Secret API key.</param> public Untappd(string clientId, string clientSecret) { Config.ClientId = clientId; Config.ClientSecret = clientSecret; Beer = new BeerApi(); Venue = new VenueApi(); Wishlist = new WishlistApi(); ThePub = new ThePubApi(); Brewery = new BreweryApi(); Auth = new AuthApi(); }
public async Task CompleteTest() { // ARRANGE var username = Configuration["username"]; var password = Configuration["password"]; var appId = Configuration["appid"]; var config = new Config(appId); var localData = new LocalData(new FakeLocalData(), new FakeLocalData()); var logger = new TestLogger(_output); var api = new AuthApi(config); var ws = new WsWrapper(config, api, logger, localData); var auth = new AuthMain(config, api, localData, ws, logger); var signInRequest = new SignInRequest { Username = username, Password = password, RememberMe = "none" }; var db = new Db(ws); void ChangeHandler(List <Database.Item> items) { var output = _output; output.WriteLine($"Received {items.Count} items from database."); } // ACT var response = await auth.SignIn(signInRequest); var promise = new TaskCompletionSource <int>(); #pragma warning disable 4014 Task.Factory.StartNew(async() => #pragma warning restore 4014 { var scopedWs = ws; var scopedLogger = logger; while (!scopedWs.Keys.Init) { } await scopedLogger.Log("KEYS INIT DONE"); promise.SetResult(0); }); await promise.Task; await db.OpenDatabase(new OpenDatabaseRequest { DatabaseName = "todos", ChangeHandler = ChangeHandler }); // ASSERT Assert.NotNull(response.UserId); Assert.NotNull(response.Username); Assert.NotNull(response.Email); }
/// <summary> /// 初始化上下文 /// </summary> private void Init() { if (Config == null) { Config = ConfigurationManager.GetSection("AliApplyConfig") as AliApply; } Util = new ApiUtils(this); Auth = new AuthApi(this); Company = new CompanyApi(this); Product = new ProductApi(this); CustomClassify = new CustomClassifyApi(this); Album = new AlbumApi(this); Photo = new PhotoApi(this); Url=new UrlApi(this); Platform = new PlatformApi(this); Member=new MemberApi(this); Order=new OrderApi(this); Logistics=new LogisticsApi(this); CustomerRelations= new CustomerRelApi(this); Category=new CategoryApi(this); Search = new SearchApi(this); Timeout = 15; }