public BaseService(AuthConfig authConfig, string baseApiURI) { Config = authConfig; Client = new RestClient(baseApiURI); setClientHeaders(); }
public static void reportDownload(AuthConfig authConfig, String downCode, String localFilePath, String localFileName) { ReportDownloadService downloadService = new ReportDownloadService((IOAuth1Config)authConfig); downloadService.setDownCode(downCode); // 给私有参数赋值 Stream outs = null; try { String fullPath = localFilePath.Replace("\\", "/"); if (fullPath.LastIndexOf("/") != -1) { fullPath = localFilePath + localFileName; } else { fullPath = localFilePath + "/" + localFileName; } outs = new FileStream(fullPath, System.IO.FileMode.Create); downloadService.doService(outs); } catch (TreClientException e) { log.Error(e); throw e; } catch (Exception e) { log.Error(e); } finally { IOUtils.close(outs); } }
public SiteContext() { Auth = new AuthConfig(); LocalAuth = new LocalAuthConfig(); Stripe = new StripeConfig(); Email = new EmailConfig(); Membership = new MembershipConfig(); Paging = new PagingConfig(); ConfigurationBuilder.LoadConfiguration(this); }
public string downloadCycReportFile(AuthConfig authConfig, string localFilePath, string localFileName, string taskNo, string fileCreateTime) { ReportQueryResult queryResult = ReportExtServiceHelper.queryReport(authConfig, taskNo, fileCreateTime); String qresJson = queryResult.ResultJson; String downCode = ReportExtServiceHelper.stripDownCode(qresJson); if ("".Equals(downCode)) { throw new TreClientException(ErrorCode.EC0001, "任务报表文件生成失败"); } ReportExtServiceHelper.reportDownload(authConfig, downCode, localFilePath, localFileName); log.Debug(m => m("下载成功,存放路径为: {0}{1}", localFilePath, localFileName)); return localFilePath + localFileName; }
private void setConfig() { var config = new AuthConfig(); config.ApiKey = "dTPUgGvVPktCT8TxY74Kkt5szgzMF5UH"; config.SecretKey = "QZYmEu2VwCxxj3qj"; config.RoleName = "elektrostil"; config.RolePass = "******"; ConfigurationManager.setAuthParameters(config); }
public static ReportQueryResult queryReport(AuthConfig authConfig, String taskNo) { ReportQueryService queryService = new ReportQueryService((IOAuth1Config)authConfig); queryService.Param = "{\"taskNo\":\"" + taskNo + "\"}"; // 给私有参数赋值 return queryService.doService(); }
public static void GGtumunuListele()//ürün listesi getirme { AuthConfig config = new AuthConfig(); config.ApiKey = "7PK2PGYfWTwaS7SepH5XSUVcWCduyzC8"; config.SecretKey = "SREzBND4y7tD7pCW"; config.RoleName = "elkstor"; config.RolePass = "******"; ConfigurationManager.setAuthParameters(config); Console.WriteLine("----GittiGidiyor Seçkili Listeleme----"); Console.WriteLine("Aktif Satışlar İçin= as"); Console.WriteLine("Listelemeye Hazır İçin= lh"); Console.WriteLine("Satılanlar İçin= s"); Console.WriteLine("Satılmayanlar İçin= snot"); string pullVeri = ("A"); Console.Write("?="); pullVeri = Console.ReadLine(); string kondisyonSeckisi = ("Veri yook xd"); if (pullVeri == "as") { kondisyonSeckisi = "A"; } else if (pullVeri == "lh") { kondisyonSeckisi = "L"; } else if (pullVeri == "s") { kondisyonSeckisi = "S"; } else if (pullVeri == "snot") { kondisyonSeckisi = "U"; } else { Console.WriteLine("Yanlış Girdi Yaptınız Lütfen Tekrar Deneyiniz "); GGtumunuListele(); } string kehkeh; Console.Write("Kaç Ürün Görüntülensin :"); kehkeh = Console.ReadLine(); int kacUrun = Convert.ToInt32(kehkeh); try { ProductService productService = ServiceProvider.getProductService(); productServiceListResponse response = productService.getProducts(0, kacUrun, kondisyonSeckisi, true, "tr"); if (response != null && response.ackCode.ToString().Equals("success")) { int urunCount = 0; Console.WriteLine(response.productCount); productDetailType[] productDetail = response.products; foreach (productDetailType productDetailType in productDetail) { urunCount++; Console.WriteLine("*****************************************"); Console.Write(urunCount.ToString() + ". Ürün "); Console.Write(" id: " + productDetailType.productId); Console.WriteLine(" Fiyat:" + productDetailType.product.buyNowPrice + " tl"); // Console.WriteLine("ürün kk :" + productDetailType.product.categoryCode); Console.WriteLine("başlık: " + productDetailType.product.title); // Console.WriteLine("ürün format:" + productDetailType.product.format); Console.WriteLine(" ürün açıklama: " + productDetailType.product.description); // Console.WriteLine("resim verisi:" + productDetailType.product.photos); Console.WriteLine("*****************************************"); Console.WriteLine(""); Console.WriteLine(""); // Console.WriteLine(productDetailType.product.photos);//fotoğrafları almak başlıktan sonra en önemli detay } } else { Console.WriteLine(response.error.errorId); Console.WriteLine(response.error.errorCode); Console.WriteLine(response.error.message); Shell.shell(); } } catch (Exception ex) { Console.WriteLine("Bir Hata Oluştu ,Sistem Yöneticisine Danışın"); } Shell.shell(); }
public BasicAuth(AuthConfig authConfig) { this.authConfig = authConfig; Username = authConfig.Username; Password = authConfig.Password; }
public void CompareModule() { var auth1 = new AuthConfig { Username = "******", Password = "******", ServerAddress = "auth1" }; var auth2 = new AuthConfig { Username = "******", Password = "******", ServerAddress = "auth1" }; var auth3 = new AuthConfig { Username = "******", Password = "******", ServerAddress = "auth1" }; var auth4 = new AuthConfig { Username = "******", Password = "******", ServerAddress = "auth2" }; Dictionary <string, EnvVal> goodEnv = new Dictionary <string, EnvVal>(); Dictionary <string, EnvVal> newEnv = new Dictionary <string, EnvVal> { ["a"] = new EnvVal("B") }; IList <string> dockerEnv = new List <string> { "c=d" }; CombinedDockerConfig goodCombinedDockerConfig = new CombinedDockerConfig("image:tag", new CreateContainerParameters(), Option.None <AuthConfig>()); CombinedDockerConfig imageDifferent = new CombinedDockerConfig("image:newtag", new CreateContainerParameters(), Option.None <AuthConfig>()); CombinedDockerConfig auth1Config = new CombinedDockerConfig("image:tag", new CreateContainerParameters(), Option.Some(auth1)); CombinedDockerConfig auth2Config = new CombinedDockerConfig("image:tag", new CreateContainerParameters(), Option.Some(auth2)); CombinedDockerConfig auth3Config = new CombinedDockerConfig("image:tag", new CreateContainerParameters(), Option.Some(auth3)); CombinedDockerConfig auth4Config = new CombinedDockerConfig("image:tag", new CreateContainerParameters(), Option.Some(auth4)); CombinedDockerConfig createContainerConfigDifferent = new CombinedDockerConfig("image:tag", new CreateContainerParameters { Env = dockerEnv }, Option.None <AuthConfig>()); ConfigurationInfo goodInfo = new ConfigurationInfo(string.Empty); var m1 = new CombinedDockerModule("name1", "v1", ModuleStatus.Running, RestartPolicy.Always, goodCombinedDockerConfig, goodInfo, goodEnv); var m2 = new CombinedDockerModule("name2", "v1", ModuleStatus.Running, RestartPolicy.Always, goodCombinedDockerConfig, goodInfo, goodEnv); var m3 = new CombinedDockerModule("name1", "v1", ModuleStatus.Running, RestartPolicy.Always, goodCombinedDockerConfig, goodInfo, goodEnv); var m4 = new CombinedDockerModule("name1", "v2", ModuleStatus.Running, RestartPolicy.Always, goodCombinedDockerConfig, goodInfo, goodEnv); var m5 = new CombinedDockerModule("name1", "v1", ModuleStatus.Running, RestartPolicy.Always, goodCombinedDockerConfig, goodInfo, goodEnv); var m6 = new CombinedDockerModule("name1", "v1", ModuleStatus.Stopped, RestartPolicy.Always, goodCombinedDockerConfig, goodInfo, goodEnv); var m7 = new CombinedDockerModule("name1", "v1", ModuleStatus.Running, RestartPolicy.Always, goodCombinedDockerConfig, goodInfo, goodEnv); var m8 = new CombinedDockerModule("name1", "v1", ModuleStatus.Running, RestartPolicy.Never, goodCombinedDockerConfig, goodInfo, goodEnv); var m9 = new CombinedDockerModule("name1", "v1", ModuleStatus.Running, RestartPolicy.Always, imageDifferent, goodInfo, goodEnv); var m10 = new CombinedDockerModule("name1", "v1", ModuleStatus.Running, RestartPolicy.Always, auth1Config, goodInfo, goodEnv); var m11 = new CombinedDockerModule("name1", "v1", ModuleStatus.Running, RestartPolicy.Always, auth2Config, goodInfo, goodEnv); var m12 = new CombinedDockerModule("name1", "v1", ModuleStatus.Running, RestartPolicy.Always, auth3Config, goodInfo, goodEnv); var m13 = new CombinedDockerModule("name1", "v1", ModuleStatus.Running, RestartPolicy.Always, auth4Config, goodInfo, goodEnv); var m14 = new CombinedDockerModule("name1", "v1", ModuleStatus.Running, RestartPolicy.Always, createContainerConfigDifferent, goodInfo, goodEnv); var m15 = new CombinedDockerModule("name1", "v1", ModuleStatus.Running, RestartPolicy.Always, goodCombinedDockerConfig, goodInfo, newEnv); Assert.NotEqual(m1, m2); Assert.NotEqual(m3, m4); Assert.NotEqual(m5, m6); Assert.NotEqual(m7, m8); Assert.NotEqual(m1, m9); Assert.NotEqual(m9, m1); Assert.NotEqual(m10, m9); Assert.NotEqual(m9, m10); Assert.NotEqual(m10, m11); Assert.NotEqual(m11, m10); Assert.NotEqual(m10, m12); Assert.NotEqual(m10, m13); Assert.NotEqual(m11, m14); Assert.NotEqual(m11, m15); Assert.True(m5.IsOnlyModuleStatusChanged(m6)); Assert.False(m1.IsOnlyModuleStatusChanged(m2)); Assert.False(m1.IsOnlyModuleStatusChanged(m9)); }
public static Stream PullImage(this IImageOperations operations, ImagesPullParameters parameters, AuthConfig authConfig) { return(operations.PullImageAsync(parameters, authConfig).Result); }
/// <summary> /// 更新账户认证信息 /// </summary> protected async Task <LoginResultModel> UpdateAuthInfo(AccountEntity account, LoginModel model, AuthConfig config) { var authInfo = new AccountAuthInfoEntity { AccountId = account.Id, Platform = model.Platform, LoginTime = DateTime.Now.ToTimestamp(), LoginIP = model.IP, RefreshToken = GenerateRefreshToken(), RefreshTokenExpiredTime = DateTime.Now.AddDays(7)//默认刷新令牌有效期7天 }; //设置过期时间 if (config.Jwt.RefreshTokenExpires > 0) { authInfo.RefreshTokenExpiredTime = DateTime.Now.AddDays(config.Jwt.RefreshTokenExpires); } Task <bool> task; var entity = await _authInfoRepository.Get(account.Id, model.Platform); if (entity != null) { authInfo.Id = entity.Id; task = _authInfoRepository.UpdateAsync(authInfo); } else { task = _authInfoRepository.AddAsync(authInfo); } if (await task) { //判断是否开启验证码功能,删除验证码缓存 if (config.VerifyCode) { await _cacheHandler.RemoveAsync($"{CacheKeys.AUTH_VERIFY_CODE}:{model.VerifyCode.Id}"); } //清除账户的认证信息缓存 await _cacheHandler.RemoveAsync($"{CacheKeys.ACCOUNT_AUTH_INFO}:{account.Id}:{model.Platform.ToInt()}"); return(new LoginResultModel { Account = account, AuthInfo = authInfo }); } return(null); }
private AuthConfig GetAuthConfig(RepositoryCredentialDescription credentials, string imageName, CredentialType credentialType) { var authConfig = new AuthConfig(); string username = ""; string password = ""; if (credentialType == CredentialType.TokenCredentials) { // Docker knows to do token authentication if the user name is a GUID of all zeroes username = Guid.Empty.ToString(); if (!string.IsNullOrEmpty(cachedToken)) { password = cachedToken; } else if (!string.IsNullOrEmpty(HostingConfig.Config.ContainerRepositoryCredentialTokenEndPoint)) { if (HostingConfig.Config.ContainerRepositoryCredentialTokenEndPoint.Contains(HostingConfig.Config.DefaultMSIEndpointForTokenAuthentication)) { // They are using Azure Container Registry // get a refresh token from the azure container registry via MSI password = GetRefreshTokenMSI(imageName); } else { password = GetGenericRefreshToken(); } } else { // no container endpoint specified, try MSI password = GetRefreshTokenMSI(imageName); } } else if (credentialType == CredentialType.AppManifestCredentials) { username = credentials.AccountName; if (credentials.IsPasswordEncrypted && !string.IsNullOrEmpty(credentials.Password)) { password = Utility.GetDecryptedValue(credentials.Password); } else { password = credentials.Password; } } else if (credentialType == CredentialType.ClusterManifestDefaultCredentials) { username = HostingConfig.Config.DefaultContainerRepositoryAccountName; if (HostingConfig.Config.IsDefaultContainerRepositoryPasswordEncrypted && !string.IsNullOrEmpty(HostingConfig.Config.DefaultContainerRepositoryPassword)) { password = Utility.GetDecryptedValue(HostingConfig.Config.DefaultContainerRepositoryPassword); } else { password = HostingConfig.Config.DefaultContainerRepositoryPassword; } } if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password)) { authConfig.Username = username; authConfig.Password = password; authConfig.Email = credentials.Email; } return(authConfig); }
public AppConfig(AuthConfig authConfig, UrlsConfig urlsConfig, ConnectionStrings connectionStrings) { Urls = urlsConfig; Auth = authConfig; ConnectionStrings = connectionStrings; }
public LoginRequest(LoginDto dto, AuthConfig config) { _dto = dto; _config = config; }
/// <summary> /// Create or update the AuthConfig for a Container App. /// </summary> /// <remarks> /// Description for Create or update the AuthConfig for a Container App. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='containerAppName'> /// Name of the Container App. /// </param> /// <param name='name'> /// Name of the Container App AuthConfig. /// </param> /// <param name='authConfigEnvelope'> /// Properties used to create a Container App AuthConfig /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <AuthConfig> CreateOrUpdateAsync(this IContainerAppsAuthConfigsOperations operations, string resourceGroupName, string containerAppName, string name, AuthConfig authConfigEnvelope, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, containerAppName, name, authConfigEnvelope, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
/// <summary> /// Create or update the AuthConfig for a Container App. /// </summary> /// <remarks> /// Description for Create or update the AuthConfig for a Container App. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='containerAppName'> /// Name of the Container App. /// </param> /// <param name='name'> /// Name of the Container App AuthConfig. /// </param> /// <param name='authConfigEnvelope'> /// Properties used to create a Container App AuthConfig /// </param> public static AuthConfig CreateOrUpdate(this IContainerAppsAuthConfigsOperations operations, string resourceGroupName, string containerAppName, string name, AuthConfig authConfigEnvelope) { return(operations.CreateOrUpdateAsync(resourceGroupName, containerAppName, name, authConfigEnvelope).GetAwaiter().GetResult()); }
private async Task <HttpResponseMessage> HandleResponse(HttpResponseMessage response, HttpMethod httpMethod, Uri uri, List <KeyValuePair <string, string> > body, AuthConfig auth, bool getPdf = false) { if (!response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); if (response.StatusCode == HttpStatusCode.BadRequest) { JObject jObject = JObject.Parse(content); string error = (string)jObject["error"]; if (error == "invalid_token") { //Request new token var tokens = await GetAccessTokenByRefreshAsync(auth.ApplicationId); await _authRepository.UpdateAuthConfigAsync(auth.ApplicationId, tokens.AccessToken, tokens.RefreshToken); auth = await _authRepository.GetAuthConfigAsync(auth.ApplicationId); //Log new token _logger.LogInformation($"Get NEW ACCESS TOKEN: StatusCode: {response.StatusCode}, ACCESS TOKEN: {tokens.AccessToken}, REFRESH TOKEN: {tokens.RefreshToken}"); //Try Request Again var httpClient = CreateHttpClient(tokens.AccessToken); HttpRequestMessage request = GenerateRequest(httpMethod, uri, body, httpClient, auth, getPdf); response = await httpClient.SendAsync(request); } } } return(response); }
/// <summary> /// Create or update the AuthConfig for a Container App. /// </summary> /// <remarks> /// Description for Create or update the AuthConfig for a Container App. /// </remarks> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='containerAppName'> /// Name of the Container App. /// </param> /// <param name='name'> /// Name of the Container App AuthConfig. /// </param> /// <param name='authConfigEnvelope'> /// Properties used to create a Container App AuthConfig /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="DefaultErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse <AuthConfig> > CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string containerAppName, string name, AuthConfig authConfigEnvelope, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (containerAppName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "containerAppName"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (authConfigEnvelope == null) { throw new ValidationException(ValidationRules.CannotBeNull, "authConfigEnvelope"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("containerAppName", containerAppName); tracingParameters.Add("name", name); tracingParameters.Add("authConfigEnvelope", authConfigEnvelope); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.App/containerApps/{containerAppName}/authConfigs/{name}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{containerAppName}", System.Uri.EscapeDataString(containerAppName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); List <string> _queryParameters = new List <string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (authConfigEnvelope != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(authConfigEnvelope, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new DefaultErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); DefaultErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <DefaultErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <AuthConfig>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <AuthConfig>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public AuthService(IAuthRepository repository, IOptions <AuthConfig> authConfig) { _repository = repository; _authConfig = authConfig.Value; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { IConfigurationSection authConfigSection = Configuration.GetSection("Authentication"); IConfigurationSection corsConfigSection = Configuration.GetSection("Cors"); AuthConfig authConfig = authConfigSection.Get <AuthConfig>(); CorsConfig corsConfig = corsConfigSection.Get <CorsConfig>(); // Configure CORS based on the origins specified in our configuration services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder .WithOrigins(corsConfig.AllowedCorsOrigins) .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); }); services.AddControllers(); // Configure EF DB Context services.AddDbContext <FavoriteStationsContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); // Add Http Context to the pipeline for DI services.AddHttpContextAccessor(); // Configure a typed User object based on access token claims services.AddScoped <IUser>(s => new User(s.GetService <IHttpContextAccessor>().HttpContext.User)); services.AddScoped <IDataLayer, DataLayer>(); services.AddScoped <IBusinessLayer, BusinessLayer>(); // Auto Mapper Configurations var mappingConfig = new MapperConfiguration(mc => { mc.AddProfile(new MappingProfile()); }); services.AddSingleton(mappingConfig.CreateMapper()); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Favorite Stations API", Description = "A simple RESTful CRUD api used to persist users' favorite internet radio stations", Version = "v1" }); // Set the comments path for the Swagger JSON and UI. var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath, includeControllerXmlComments: true); }); /* Disable automatic model validation so that we can use our own custom ValidateModelAttribute. * https://stackoverflow.com/questions/51125569/net-core-2-1-override-automatic-model-validation */ services.Configure <ApiBehaviorOptions>(opts => opts.SuppressModelStateInvalidFilter = true); // Configure JWT Bearer token authentication services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.Authority = authConfig.Authority; options.Audience = authConfig.Audience; options.Events = new JwtBearerEvents() { OnChallenge = c => { c.HandleResponse(); return(c.HttpContext.WriteStatusCodeResponse(401)); } }; }); }
public ImagePullSecret(AuthConfig dockerAuth) { this.dockerAuth = dockerAuth; this.Name = $"{dockerAuth.Username.ToLower()}-{dockerAuth.ServerAddress.ToLower()}"; }
public async Task DownloadImageAsync(ContainerImageDescription imageDescription, TimeSpan timeout, bool skipCacheCheck = false) { var timeoutHelper = new TimeoutHelper(timeout); var imageTags = imageDescription.ImageName.Split(':'); bool isLatest = false; if (imageTags.Length < 2 || String.IsNullOrEmpty(imageTags[1])) { imageDescription.ImageName = String.Concat(imageDescription.ImageName, ":latest"); isLatest = true; } if (!skipCacheCheck && !isLatest) { if (this.IsImageCached(imageDescription.ImageName)) { HostingTrace.Source.WriteInfo( TraceType, "Container image download skipped as it is cached: ImageName={0}, Time={1}ms .", imageDescription.ImageName, 0); return; } if (await this.IsImagePresentLocallyAsync(imageDescription.ImageName, timeoutHelper.RemainingTime)) { HostingTrace.Source.WriteInfo( TraceType, "Container image download skipped as it is present locally: ImageName={0}, Time={1}ms .", imageDescription.ImageName, 0); this.AddImageToCache(imageDescription.ImageName); return; } } CredentialType currentCredentialAttempt; if (imageDescription.UseTokenAuthenticationCredentials) { currentCredentialAttempt = CredentialType.TokenCredentials; } else if (imageDescription.UseDefaultRepositoryCredentials) { currentCredentialAttempt = CredentialType.ClusterManifestDefaultCredentials; } else { currentCredentialAttempt = CredentialType.AppManifestCredentials; } try { AuthConfig authConfig = this.GetAuthConfig(imageDescription.RepositoryCredential, imageDescription.ImageName, currentCredentialAttempt); var downloadProgressStream = await Utility.ExecuteWithRetriesAsync( (operationTimeout) => { return(this.ImageOperation.CreateImageAsync( imageDescription.ImageName, authConfig, operationTimeout)); }, $"CreateImageAsync_{imageDescription.ImageName}", TraceType, HostingConfig.Config.DockerRequestTimeout, timeoutHelper.RemainingTime); await this.TrackDownloadProgressAsync( imageDescription.ImageName, downloadProgressStream, timeoutHelper.RemainingTime); if (!await this.IsImagePresentLocallyAsync(imageDescription.ImageName, timeoutHelper.RemainingTime)) { throw new Exception( $"Container image download failed - ImageName={imageDescription.ImageName}. " + $"Please check if container image OS is compatible with host OS or if you have sufficient disk space on the machine. " + $"Try to pull the image manually on the machine using docker CLI for further error details. "); } this.AddImageToCache(imageDescription.ImageName); } catch (ContainerApiException dex) { var errMsgBuilder = new StringBuilder(); errMsgBuilder.AppendFormat( "Container image download failed with authorization attempt type {0} for ImageName={1}. DockerRequest returned StatusCode={2} with ResponseBody={3}.", currentCredentialAttempt.ToString(), imageDescription.ImageName, dex.StatusCode, dex.ResponseBody); if (dex.StatusCode == HttpStatusCode.NotFound) { errMsgBuilder.Append( "Please check if image is present in repository or repository credentials provided are correct."); } HostingTrace.Source.WriteWarning(TraceType, errMsgBuilder.ToString()); throw new FabricException(errMsgBuilder.ToString(), FabricErrorCode.InvalidOperation); } catch (Exception ex) { var errMsgBuilder = new StringBuilder(); errMsgBuilder.AppendFormat( "Container image download failed with authorization attempt type {0} for ImageName={1} with unexpected error. Exception={2}.", currentCredentialAttempt.ToString(), imageDescription.ImageName, ex.ToString()); HostingTrace.Source.WriteWarning(TraceType, errMsgBuilder.ToString()); throw new FabricException(errMsgBuilder.ToString(), FabricErrorCode.InvalidOperation); } }
public static void Configure(IAppBuilder app) { ConfigDebugMiddleware(app); AuthConfig.Configure(app); }
void Application_Start(object sender, EventArgs e) { // Code that runs on application startup BundleConfig.RegisterBundles(BundleTable.Bundles); AuthConfig.RegisterOpenAuth(); }
public Task CreateImageAsync(ImagesCreateParameters parameters, Stream imageStream, AuthConfig authConfig, IProgress <JSONMessage> progress, CancellationToken cancellationToken = default(CancellationToken)) { return(CreateImageAsync(parameters, imageStream, authConfig, null, progress, cancellationToken)); }
public static Stream PushImage(this IImageOperations operations, string name, ImagePushParameters parameters, AuthConfig authConfig) { return(operations.PushImageAsync(name, parameters, authConfig).Result); }
public Task CreateImageAsync(ImagesCreateParameters parameters, Stream imageStream, AuthConfig authConfig, IDictionary <string, string> headers, IProgress <JSONMessage> progress, CancellationToken cancellationToken = default(CancellationToken)) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } HttpMethod httpMethod = HttpMethod.Post; BinaryRequestContent content = null; if (imageStream != null) { content = new BinaryRequestContent(imageStream, TarContentType); parameters.FromSrc = ImportFromBodySource; } IQueryString queryParameters = new QueryString <ImagesCreateParameters>(parameters); Dictionary <string, string> customHeaders = RegistryAuthHeaders(authConfig); if (headers != null) { foreach (string key in headers.Keys) { customHeaders[key] = headers[key]; } } return(StreamUtil.MonitorResponseForMessagesAsync( this._client.MakeRequestForRawResponseAsync(httpMethod, "images/create", queryParameters, content, customHeaders, cancellationToken), this._client, cancellationToken, progress)); }
private bool IsAuthCertConfigured() { AuthConfig authConfig = AuthConfig.Read(this.ConfigSession); return(authConfig == null || !string.IsNullOrEmpty(authConfig.CurrentCertificateThumbprint)); }
public Task CreateImageAsync(ImagesCreateParameters parameters, AuthConfig authConfig, IDictionary <string, string> headers, IProgress <JSONMessage> progress, CancellationToken cancellationToken = default(CancellationToken)) { return(CreateImageAsync(parameters, null, authConfig, headers, progress, cancellationToken)); }
public AccessTokenGenerator(AuthConfig authConfig) { this.authConfig = authConfig; }
public JwtBearerPostConfigurer(IOptions <AuthConfig> config) { this.config = config.Value; }
//TODO : Need add BotManager to manage all feature related to multibot, public bool ReInitSessionWithNextBot(AuthConfig bot = null, double lat = 0, double lng = 0, double att = 0) { this.CatchBlockTime = DateTime.Now; //remove any block MSniperServiceTask.BlockSnipe(); var currentAccount = this.accounts.FirstOrDefault(x => (x.AuthType == PokemonGo.RocketAPI.Enums.AuthType.Ptc && x.PtcUsername == this.Settings.PtcUsername) || (x.AuthType == PokemonGo.RocketAPI.Enums.AuthType.Google && x.GoogleUsername == this.Settings.GoogleUsername)); if (LoggedTime != DateTime.MinValue) { currentAccount.RuntimeTotal += (DateTime.Now - LoggedTime).TotalMinutes; } this.accounts = this.accounts.OrderByDescending(p => p.RuntimeTotal).ToList(); var first = this.accounts.First(); if (first.RuntimeTotal >= 100000) { first.RuntimeTotal = this.accounts.Min(p => p.RuntimeTotal); } var nextBot = bot != null ? bot : this.accounts.LastOrDefault(p => p != currentAccount && p.ReleaseBlockTime < DateTime.Now); if (nextBot != null) { Logger.Write($"Switching to {nextBot.GoogleUsername}{nextBot.PtcUsername}..."); string body = ""; File.Delete("runtime.log"); List <string> logs = new List <string>(); foreach (var item in this.Accounts) { int day = (int)item.RuntimeTotal / 1440; int hour = (int)(item.RuntimeTotal - (day * 1400)) / 60; int min = (int)(item.RuntimeTotal - (day * 1400) - hour * 60); body = body + $"{item.GoogleUsername}{item.PtcUsername} {day:00}:{hour:00}:{min:00}:00\r\n"; logs.Add($"{item.GoogleUsername}{item.PtcUsername};{item.RuntimeTotal}"); } File.AppendAllLines("runtime.log", logs); PushNotificationClient.SendNotification(this, $"Account changed to {nextBot.GoogleUsername}{nextBot.PtcUsername}", body); this.Settings.AuthType = nextBot.AuthType; this.Settings.GooglePassword = nextBot.GooglePassword; this.Settings.GoogleUsername = nextBot.GoogleUsername; this.Settings.PtcPassword = nextBot.PtcPassword; this.Settings.PtcUsername = nextBot.PtcUsername; this.Settings.DefaultAltitude = att == 0 ? this.Client.CurrentAltitude : att; this.Settings.DefaultLatitude = lat == 0 ? this.Client.CurrentLatitude : lat; this.Settings.DefaultLongitude = lng == 0 ? this.Client.CurrentLongitude : lng; this.Stats = new SessionStats(this); this.Reset(this.Settings, this.LogicSettings); //CancellationTokenSource.Cancel(); this.CancellationTokenSource = new CancellationTokenSource(); this.EventDispatcher.Send(new BotSwitchedEvent() { }); if (this.LogicSettings.MultipleBotConfig.DisplayList) { foreach (var item in this.accounts) { Logger.Write($"{item.PtcUsername}{item.GoogleUsername} \tRuntime : {item.RuntimeTotal:0.00} min "); } } } return(nextBot != null); }
public void Configuration(IAppBuilder app) { AuthConfig.RegisterAuth(app); }
public static ReportQueryResult queryReport(AuthConfig authConfig, String taskNo, String fileCreateTime) { ReportQueryService queryService = new ReportQueryService((IOAuth1Config)authConfig); queryService.Param = "{\"taskNo\":\"" + taskNo + "\",\"fileTime\":\"" + fileCreateTime + "\"}"; return queryService.doService(); }
public Task <Stream> PushImageAsync(string name, PushImageParameters parameters, AuthConfig authConfig) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (authConfig == null) { throw new ArgumentNullException("authConfig"); } string path = string.Format(CultureInfo.InvariantCulture, "images/{0}/push", name); IQueryString queryParameters = new QueryString <PushImageParameters>(parameters); return(this.Client.MakeRequestForStreamAsync(this.Client.NoErrorHandlers, HttpMethod.Post, path, queryParameters, RegistryAuthHeaders(authConfig), null, CancellationToken.None)); }
protected void Application_Start() { AuthConfig.RegisterAuth(); }
public ClientStore() { _clients = (List <Client>)AuthConfig.GetClients(); }