Example #1
0
        private static async Task <HttpApiTransport> GetTransportAsync(ArangoDbOptions options)
        {
            if (!string.IsNullOrWhiteSpace(options.JwtToken))
            {
                return(HttpApiTransport.UsingJwtAuth(new Uri(options.HostUri), options.Database, options.JwtToken));
            }

            if (options.IsGenerateJwtTokenBasedOnUserNameAndPassword)
            {
                if (string.IsNullOrWhiteSpace(options.UserName))
                {
                    throw new ArgumentNullException(nameof(options.UserName));
                }
                if (string.IsNullOrWhiteSpace(options.Password))
                {
                    throw new ArgumentNullException(nameof(options.Password));
                }

                var transport        = HttpApiTransport.UsingNoAuth(new Uri(options.HostUri), options.Database);
                var authClient       = new AuthApiClient(transport);
                var jwtTokenResponse = await authClient.GetJwtTokenAsync(options.UserName, options.Password);

                transport.SetJwtToken(jwtTokenResponse.Jwt);
                return(transport);
            }

            if (!string.IsNullOrWhiteSpace(options.UserName) && !string.IsNullOrWhiteSpace(options.Password))
            {
                return(HttpApiTransport.UsingBasicAuth(new Uri(options.HostUri), options.Database, options.UserName, options.Password));
            }

            return(HttpApiTransport.UsingNoAuth(new Uri(options.HostUri), options.Database));
        }
Example #2
0
        public async Task SetJwt_ShouldSucceed()
        {
            string jwtToken        = null;
            string arangodbBaseUrl = $"http://{_fixture.ArangoDbHost}:8529/";

            using (var transport = HttpApiTransport.UsingNoAuth(
                       new Uri(arangodbBaseUrl),
                       nameof(HttpApiTransportTest)))
            {
                var authClient = new AuthApiClient(transport);

                var jwtTokenResponse = await authClient.GetJwtTokenAsync(
                    new JwtTokenRequestBody
                {
                    Username = _fixture.Username,
                    Password = _fixture.Password
                });

                jwtToken = jwtTokenResponse.Jwt;

                // Use token in current transport
                transport.SetJwtToken(jwtToken);
                var databaseApi = new DatabaseApiClient(transport);

                var userDatabasesResponse = await databaseApi.GetUserDatabasesAsync();

                Assert.NotEmpty(userDatabasesResponse.Result);
            }
        }
Example #3
0
        private static void RegisterAccount()
        {
            Console.Clear();
            Console.WriteLine("-=Регистрация аккаунта=-");
            Console.Write("Введите логин: ");
            var userName = Console.ReadLine();

            Console.Write("Введите пароль: ");
            var password = Console.ReadLine();

            Console.Write("Подтвердите пароль: ");
            var confirmPassword = Console.ReadLine();

            var serverInfoUrl = ApiHelper.GetApiServerUri(_serverInfo, userName, _serverPort);

            var authApi = new AuthApiClient(new PasswordOAuthContext()
            {
                BaseUri = serverInfoUrl
            });

            try
            {
                var result = authApi.Register(new RegisterAccountModel()
                {
                    Login           = userName,
                    Password        = password,
                    ConfirmPassword = confirmPassword
                }).Result;
            }
            catch (AggregateException loginException)
            {
                ErrorCode = GameRunner.HandleClientException(loginException.InnerException as IClientException <ErrorData>);
            }
        }
Example #4
0
        private static void Main(string[] args)
        {
            GetCredentials();
            var authApiClient    = new AuthApiClient(userIdentifier, userSecret);
            var auth             = new OAuthAuthenticationStrategy(authApiClient);
            var fileApiClient    = new FileApiClient(auth, projectId, string.Empty);
            var projectApiClient = new ProjectApiClient(auth, projectId);

            fileApiClient.ApiGatewayUrl = "https://api.smartling.com";
            string fileName = "ApiSample_" + Guid.NewGuid();
            string fileUri  = "/master/" + fileName;

            Upload(fileApiClient, fileUri, fileName, "xml");
            Download(fileApiClient, fileUri);
            Submissions(auth);
            Audit(auth);
            Jobs(auth);
            Published(auth);
            GetProjectData(projectApiClient);
            List(fileApiClient);
            Status(fileApiClient, fileUri, "ru-RU");
            LastModified(fileApiClient, fileUri);
            Authorization(fileApiClient);
            Deletion(fileApiClient, fileUri);
            CloudLog();

            Console.WriteLine("All done, press any key to exit");
            Console.ReadKey();
        }
Example #5
0
        public List <Dictionary <String, String> > GetAppTokenUsingGETAsyncWithHttpInfo()
        {
            List <Dictionary <String, String> > response = new List <Dictionary <String, String> >();

            AuthApiClient authApiClient         = new AuthApiClient(this.Configuration);
            String        clientCredentialToken = authApiClient.createClientCredential(appTokenConfig.clientId, appTokenConfig.clientSecret);

            this.Configuration.AccessToken = clientCredentialToken;

            foreach (AppConfig app in appTokenConfig.appNames)
            {
                if (app.authType != null && app.authType.ToLower() == "client_credentials")
                {
                    this.Configuration.AccessToken = clientCredentialToken;
                }
                else if (app.authType != null && app.authType.ToLower() == "password_credentials")
                {
                    this.Configuration.AccessToken = appTokenConfig.userAccessToken;
                    if (appTokenConfig.isCredsPassed)
                    {
                        String passwordCredentialToken = authApiClient.createPasswordCredential(appTokenConfig.clientId, appTokenConfig.clientSecret, appTokenConfig.username, appTokenConfig.password);

                        this.Configuration.AccessToken = passwordCredentialToken;
                    }
                }

                ApiResponse <List <AppToken> > appTokenExecute = GetAppTokenUsingGETWithHttpInfo(new List <String> {
                    app.appName
                }, null);

                if (appTokenExecute != null)
                {
                    List <AppToken> appTokens         = appTokenExecute.Data;
                    String          appTokenValue     = appTokens != null && appTokens.Count > 0 ? appTokens[0]._AppToken : "";
                    String          tagValue          = app.appName.ToLower().Replace("_", "-");
                    String          fillTemplateValue = template.Replace("tag", tagValue)
                                                        .Replace("##app_token##", appTokenValue)
                                                        .Replace("##attrib_map##", getAttribMapList(appTokenConfig) != null ? string.Join(" ", getAttribMapList(appTokenConfig)) : "");

                    Dictionary <String, String> appMap = new Dictionary <String, String>();


                    if (appTokenConfig.isEmbed)
                    {
                        appMap.Add(app.appName, fillTemplateValue);
                    }
                    else
                    {
                        appMap.Add(app.appName, appTokenValue);
                    }
                    response.Add(appMap);
                }
            }
            return(response);
        }
Example #6
0
 /// <summary>
 /// Create an instance of <see cref="ArangoDBClient"/>
 /// using the provided transport and serialization layers.
 /// </summary>
 /// <param name="transport">The ArangoDB transport layer implementation.</param>
 /// <param name="serialization">The serialization layer implementation.</param>
 public ArangoDBClient(IApiClientTransport transport, IApiClientSerialization serialization)
 {
     _transport  = transport;
     Auth        = new AuthApiClient(_transport, serialization);
     Cursor      = new CursorApiClient(_transport, serialization);
     Database    = new DatabaseApiClient(_transport, serialization);
     Document    = new DocumentApiClient(_transport, serialization);
     Collection  = new CollectionApiClient(_transport, serialization);
     Transaction = new TransactionApiClient(_transport, serialization);
     Graph       = new GraphApiClient(_transport, serialization);
 }
Example #7
0
 /// <summary>
 /// Create an instance of <see cref="ArangoDBClient"/> from an existing
 /// <see cref="HttpClient"/> instance, using the default JSON serialization.
 /// </summary>
 /// <param name="client"></param>
 public ArangoDBClient(HttpClient client)
 {
     _transport  = new HttpApiTransport(client, HttpContentType.Json);
     Auth        = new AuthApiClient(_transport);
     Cursor      = new CursorApiClient(_transport);
     Database    = new DatabaseApiClient(_transport);
     Document    = new DocumentApiClient(_transport);
     Collection  = new CollectionApiClient(_transport);
     Transaction = new TransactionApiClient(_transport);
     Graph       = new GraphApiClient(_transport);
 }
 private void InitializeApis(
     IApiClientTransport transport,
     IApiClientSerialization serialization)
 {
     AqlFunction = new AqlFunctionApiClient(transport, serialization);
     Auth        = new AuthApiClient(transport, serialization);
     Cursor      = new CursorApiClient(transport, serialization);
     Database    = new DatabaseApiClient(transport, serialization);
     Document    = new DocumentApiClient(transport, serialization);
     Collection  = new CollectionApiClient(transport, serialization);
     Transaction = new TransactionApiClient(transport, serialization);
     Graph       = new GraphApiClient(transport, serialization);
     User        = new UserApiClient(transport, serialization);
 }
Example #9
0
        public static ErrorCodes?UserLogout(PasswordOAuthContext session)
        {
            var authApi = new AuthApiClient(session);

            try
            {
                var result = authApi.Logout().Result;
            }
            catch (AggregateException loginException)
            {
                return(Program.GameRunner.HandleClientException(loginException.InnerException as IClientException <ErrorData>));
            }
            return(null);
        }
        private async static Task <object> Register(PasswordOAuthContext token, int index)
        {
            var authApi = new AuthApiClient(new PasswordOAuthContext()
            {
                BaseUri = new Uri("http://localhost:9001")
            });


            return(await authApi.Register(new RegisterAccountModel()
            {
                Login = "******" + index,
                Password = "******",
                ConfirmPassword = "******"
            }));
        }
        public Task <Tuple <PerformanceCounter, object> > RegisterAccount(string login)
        {
            var serverUri = GetApiServerUri(_serviceUriList, login);
            var authApi   = new AuthApiClient(new PasswordOAuthContext()
            {
                BaseUri = serverUri
            });

            return(DoPerformanceMeasureAction(async() => await authApi.Register(new EntityFX.Gdcame.Application.WebApi.Models.RegisterAccountModel()
            {
                Login = login,
                Password = DefaultPassword,
                ConfirmPassword = DefaultPassword
            }), serverUri.ToString()));
        }
Example #12
0
        private void BuildSyncManager()
        {
            try
            {
                // Synchronizer
                var impressionsCountSender = new ImpressionsCountSender(_impressionsSdkApiClient, _impressionsCounter, _tasksManager);
                var backOff      = new BackOff(backOffBase: 10, attempt: 0, maxAllowed: 60);
                var synchronizer = new Synchronizer(_splitFetcher, _selfRefreshingSegmentFetcher, _impressionsLog, _eventsLog, impressionsCountSender, _wrapperAdapter, _statusManager, _telemetrySyncTask, _tasksManager, _splitCache, backOff, _config.OnDemandFetchMaxRetries, _config.OnDemandFetchRetryDelayMs, _segmentCache);

                // Workers
                var splitsWorker   = new SplitsWorker(_splitCache, synchronizer, _tasksManager);
                var segmentsWorker = new SegmentsWorker(synchronizer, _tasksManager);

                // NotificationProcessor
                var notificationProcessor = new NotificationProcessor(splitsWorker, segmentsWorker);

                // NotificationParser
                var notificationParser = new NotificationParser();

                // NotificationManagerKeeper
                var notificationManagerKeeper = new NotificationManagerKeeper(_telemetryRuntimeProducer);

                // EventSourceClient
                var headers = GetHeaders();
                headers.Add(Constants.Http.SplitSDKClientKey, ApiKey.Substring(ApiKey.Length - 4));
                headers.Add(Constants.Http.Accept, Constants.Http.EventStream);
                var sseHttpClient     = new SplitioHttpClient(ApiKey, _config.HttpConnectionTimeout, headers);
                var eventSourceClient = new EventSourceClient(notificationParser, _wrapperAdapter, sseHttpClient, _telemetryRuntimeProducer, _tasksManager);

                // SSEHandler
                var sseHandler = new SSEHandler(_config.StreamingServiceURL, splitsWorker, segmentsWorker, notificationProcessor, notificationManagerKeeper, eventSourceClient: eventSourceClient);

                // AuthApiClient
                var httpClient    = new SplitioHttpClient(ApiKey, _config.HttpConnectionTimeout, GetHeaders());
                var authApiClient = new AuthApiClient(_config.AuthServiceURL, ApiKey, httpClient, _telemetryRuntimeProducer);

                // PushManager
                var backoff     = new BackOff(_config.AuthRetryBackoffBase, attempt: 1);
                var pushManager = new PushManager(sseHandler, authApiClient, _wrapperAdapter, _telemetryRuntimeProducer, backoff);

                // SyncManager
                _syncManager = new SyncManager(_config.StreamingEnabled, synchronizer, pushManager, sseHandler, notificationManagerKeeper, _telemetryRuntimeProducer, _statusManager, _tasksManager, _wrapperAdapter, _telemetrySyncTask);
            }
            catch (Exception ex)
            {
                _log.Error($"BuildSyncManager: {ex.Message}");
            }
        }
Example #13
0
        public async Task UsingJwtAuth_ShouldSucceed()
        {
            string jwtToken        = null;
            string arangodbBaseUrl = $"http://{_fixture.ArangoDbHost}:8529/";

            using (var transport = HttpApiTransport.UsingNoAuth(
                       new Uri(arangodbBaseUrl),
                       nameof(HttpApiTransportTest)))
            {
                var authClient = new AuthApiClient(transport);
                authClient.ThrowErrorsAsExceptions = true;

                var jwtTokenResponse = await authClient.GetJwtTokenAsync(
                    new JwtTokenRequestBody
                {
                    Username = _fixture.Username,
                    Password = _fixture.Password
                });

                jwtToken = jwtTokenResponse.Jwt;

                DatabaseApiClient databaseApi = new DatabaseApiClient(transport)
                {
                    ThrowErrorsAsExceptions = true
                };

                // Not authorized, should throw.
                var ex = await Assert.ThrowsAsync <ApiErrorException>(async() =>
                                                                      await databaseApi.GetCurrentDatabaseInfoAsync());
            }

            // Use token in a new transport created via `UsingJwtAuth`.
            using (var transport = HttpApiTransport.UsingJwtAuth(
                       new Uri(arangodbBaseUrl),
                       nameof(HttpApiTransportTest),
                       jwtToken))
            {
                var databaseApi           = new DatabaseApiClient(transport);
                var userDatabasesResponse = await databaseApi.GetUserDatabasesAsync();

                Assert.NotEmpty(userDatabasesResponse.Results);
            }
        }
Example #14
0
        public async Task <bool> AddApiClientAsync(AuthApiClient apiClient)
        {
            AuthApiClient existingClient = Context.ApiClients.FirstOrDefault(x => x.Name == apiClient.Name);

            if (existingClient != null)
            {
                Context.ApiClients.Remove(existingClient);
                await Context.SaveChangesAsync();
            }

            Context.ApiClients.Add(apiClient);
            bool success = await Context.SaveChangesAsync() > 0;

            if (!success)
            {
                //GetLogger().Error($"Could not add ApiClient {apiClient.Name}");
            }

            return(success);
        }
Example #15
0
        private void BuildSyncManager()
        {
            try
            {
                var synchronizer              = new Synchronizer(_splitFetcher, _selfRefreshingSegmentFetcher, _impressionsLog, _eventsLog, _metricsLog, _wrapperAdapter);
                var splitsWorker              = new SplitsWorker(_splitCache, synchronizer);
                var segmentsWorker            = new SegmentsWorker(_segmentCache, synchronizer);
                var notificationProcessor     = new NotificationProcessor(splitsWorker, segmentsWorker);
                var notificationParser        = new NotificationParser();
                var eventSourceClient         = new EventSourceClient(_config.StreamingReconnectBackoffBase, notificationParser: notificationParser);
                var notificationManagerKeeper = new NotificationManagerKeeper();
                var sseHandler    = new SSEHandler(_config.StreamingServiceURL, splitsWorker, segmentsWorker, notificationProcessor, notificationManagerKeeper, eventSourceClient: eventSourceClient);
                var authApiClient = new AuthApiClient(_config.AuthServiceURL, ApiKey, _config.HttpReadTimeout);
                var pushManager   = new PushManager(_config.AuthRetryBackoffBase, sseHandler, authApiClient, _wrapperAdapter);

                _syncManager = new SyncManager(_config.StreamingEnabled, synchronizer, pushManager, sseHandler, notificationManagerKeeper);
            }
            catch (Exception ex)
            {
                _log.Error($"BuildSyncManager: {ex.Message}");
            }
        }
 public UsuarioController(AuthApiClient auth)
 {
     _auth = auth;
 }
        public Task <Tuple <PerformanceCounter, object> > Logout(ClientConnectionInfo client)
        {
            var authApi = new AuthApiClient(client.Context);

            return(DoPerformanceMeasureAction(async() => await authApi.Logout(), client.Context.BaseUri.ToString()));
        }
 public UsuarioController(AuthApiClient authApi)
 {
     _api = authApi;
 }
Example #19
0
 public UsuarioController(AuthApiClient authApiClient)
 {
     _authApiClient = authApiClient;
 }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            //NOTE: part of refresh token implementation

            string        clientId     = string.Empty;
            string        clientSecret = string.Empty;
            AuthApiClient client       = null;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                //Remove the comments from the below line context.SetError, and invalidate context
                //if you want to force sending clientId/secrets once obtain access tokens.
                context.Validated();
                //context.SetError("invalid_clientId", "ClientId should be sent.");
                return(Task.FromResult <object>(null));
            }

            using (IAuthDataAccess repo = CC.IoC.Resolve <IAuthDataAccess>())
            {
                client = repo.FindApiClient(context.ClientId);
            }

            if (client == null)
            {
                context.SetError("invalid_clientId", $"Client {context.ClientId} is not registered in the system.");
                return(Task.FromResult <object>(null));
            }

            if (client.ApplicationType == AuthApplicationTypes.NativeConfidential)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    context.SetError("invalid_clientId", "Client secret should be sent.");
                    return(Task.FromResult <object>(null));
                }
                else
                {
                    if (client.Secret != CryptoHelper.Hash(clientSecret))
                    {
                        context.SetError("invalid_clientId", "Client secret is invalid.");
                        return(Task.FromResult <object>(null));
                    }
                }
            }

            if (!client.Active)
            {
                context.SetError("invalid_clientId", "Client is inactive.");
                return(Task.FromResult <object>(null));
            }

            context.OwinContext.Set <string>("as:client_id", clientId); //make client_id available for later security checks
            context.OwinContext.Set <string>("as:clientAllowedOrigin", client.AllowedOrigin);
            context.OwinContext.Set <string>("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());

            context.Validated();
            return(Task.FromResult <object>(null));
        }