示例#1
0
        public async void AddClusterClaims()
        {
            if (FirebaseApp.DefaultInstance == null)
            {
                FirebaseApp.Create(new AppOptions()
                {
                    Credential = GoogleCredential.FromJson(privateKeyJson)
                });
            }

            // Create the custom user claim that has the role key
            var claims = new Dictionary <string, object>
            {
                { CustomClaimTypes.ClusterId, ClusterId }
            };

            // This will call the Firebase Auth server and set the custom claim for the user
            await FirebaseAuth.DefaultInstance.SetCustomUserClaimsAsync(User.UId, claims);
        }
示例#2
0
        /// <summary>
        /// Obtains credentials synchronously. Override this method in a concrete builder type if more
        /// credential mechanisms are supported.
        /// </summary>
        protected virtual IConfigurableHttpClientInitializer GetHttpClientInitializer()
        {
            if (Credential != null)
            {
                return(Credential);
            }
            GoogleCredential unscoped =
                CredentialsPath != null?GoogleCredential.FromFile(CredentialsPath) :
                    JsonCredentials != null?GoogleCredential.FromJson(JsonCredentials) :
                        null; // Use default credentials (maybe - see below)

            // While we accept any credentials that are specified even if there's an API key,
            // we don't try to load default credentials.
            if (ApiKey != null && unscoped is null)
            {
                return(null);
            }
            return(GetScopedCredentialProvider().GetCredentials(unscoped));
        }
示例#3
0
        public void FromJson_ShortDValue()
        {
            // This private key hits a rare edge case where the D value of the RSA private key only
            // requires 255 bytes to encode, but we still need to left pad it to 256 so
            // RSACryptoServiceProvider.ImportParameters does not throw CryptographicException with
            // a "Bad Data" message.
            var credential = GoogleCredential.FromJson(@"{
""private_key_id"": ""PRIVATE_KEY_ID"",
""private_key"": ""-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQC5KC4i9y2QMw5S
JrwW1Qgbxpen/PUnumAQfWUY3ZTOsXvr7vmLeDTx5a9VQ4YJFDqEEQEFPLLzSuBN
lItMJAb10AMvwBxcxs/WFAMpxoF0Aiu2U16uqLH3vf5dUJpgg+/lsmHnJk5b8jzr
CqfuEtDv7xq/HXTZtqFd144rW7mWKQyMzzlzBPgbEw5tE9Winjo9OErPrYusZ1WC
FgiuKds0CzOqQEEW6RzA0Bj4B25Q2Y1BuKPh1zd9AkoHyiyEOeOwqvd7IDn3uAuM
OfEkeL3zfs9UVq+DuGJ1bQl0N4L9JNtEdNOzWWYYBMk9pjJqNwCGUmtw9xWn2Tzp
kAnGNKntAgMBAAECggEAAM1nxccEb4eJHFoGnqK1skkeByBVf6KTH/8rHPx41Jx4
SQF0G2Kd+B5isB/myMtJpaDdPESTEfLVHgDyyZWuYgpQuTg/5zcFV4wmp1uw2+vW
fKfH1UHt44DzRTxALwLjWz92pSXJWSSnlu0o5SM3vJJwrztVckwUTu/MMevn1fq9
qqLja559YjKHoL99bB7FAGq6fqYuJv0KEDk0yzOyWX8PqSJhFE6pG3vFQ0pHg/b3
pEyUrXX/aRfgzRq8aSHzNWkDKdN5AY2a12TmouKmMy+4V9j49WXZ5DF9ZPGFrE61
Eb2UaGw8/Kzce6CY/L5pMnslwra1QxOEDLQuwuu8AQKBgQDrfdvMqgHTSX/ab0RM
8JtOXGok5s3+Or0dTfki7fOIM9eDtD6YTYFqGyKdBFovHYLzKkYdSzP3gFrvIy7d
+Pw6rRfBDHAHdsoHcc8djzjZ41fvymbiHcCCe6PdWgD3mfC5Gq/+bZrdW6erWdMX
P2QGR04ysFVNIIotAO3g2gsmLQKBgQDJSCQMx0paSKOV/psZRatf/eTDUNQDYF2N
mbqg4DiIAokt+2EEHJGwtuobckldoN/4f89kTB0OU9SFRmBAPWUDu0NfJDMNhcma
o6nlzcftObBPtAS1oLs4Rg/alcgEVHAwLpeg/QyWVb1sxgFs40EAp0TnwDWi3SSV
HoIw8R+qwQKBgCXgZ3MCwSpnvv22OckaRhCTgqsOyIEkl3hYK0M3/Jyiof5YBl1e
0frsBGQ25/5+A6ry2LYre19KsNWX1hjzzDXv00tEodxBefs6jfKWL7G0BFfYOTYT
TPxvwIqAyHkKtJJBPZ9xp6AE9vHzj6VEl+T+oRA8FmxCWJcmeBxbVcG9AoGAe8st
uNo9RYfVbKQZ2hI6U6CAuQuWSblT8Iny+YzN2ADPRAOOaIv1otzs4RKKQtZ1yY06
DXKukChI1esxuXDJFuFujy5hY9i75KryDE9ivek0IeES4G5Jl1On3oUublNMaKXP
Rgk8W53CEgs5xzGBwhgeTfauRkuCe2A3LEiwdEECgYAO80SVYrprJT6C2KcX5Hgw
M+5ST4oIu9EOOv/hBSmEs1gkASH3XEHU0iV4vg94H61Wq3RmdLZ9P2uKNq7Tjl+a
TOgrHXgWf1cxYf5cB8DfC3NoaYZ4D3Wh9Qjn3cl36CXfSKEnPK49DkrGZz1avAjV
55tKWHy105Btnc5jJT1EXg==
-----END PRIVATE KEY-----"",
""client_email"": ""CLIENT_EMAIL"",
""client_id"": ""CLIENT_ID"",
""type"": ""service_account""}");

            Assert.IsType <ServiceAccountCredential>(credential.UnderlyingCredential);
            Assert.True(credential.IsCreateScopedRequired);
        }
示例#4
0
        private GoogleCredential GetGoogleCredentials()
        {
            GoogleCredential output;

            try
            {
                output = GoogleCredential.FromJson(_options.Credential);
            }
            catch (InvalidOperationException ioe) when(ioe.InnerException is JsonSerializationException)
            {
                throw;
            }
            // ReSharper disable once RedundantCatchClause
            catch (Exception)
            {
                throw;
            }
            return(output);
        }
示例#5
0
        public DirectoryService GetDirectoryService()
        {
            GoogleCredential credential = GoogleCredential.FromJson(secretsJson)
                                          .CreateScoped(new[] {
                DirectoryService.Scope.AdminDirectoryUser
            })
                                          .CreateWithUser(delegateAdmin);


            JsonElement secrets = JsonSerializer.Deserialize <JsonElement>(secretsJson);

            var service = new DirectoryService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = secrets.GetProperty("project_id").GetString()
            });

            return(service);
        }
示例#6
0
        public GmailService GetGmailService(string userEmail)
        {
            GoogleCredential credential = GoogleCredential.FromJson(secretsJson)
                                          .CreateScoped(new[] {
                GmailService.Scope.GmailSettingsBasic,
                GmailService.Scope.GmailSettingsSharing
            })
                                          .CreateWithUser(userEmail);

            JsonElement secrets = JsonSerializer.Deserialize <JsonElement>(secretsJson);

            var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = secrets.GetProperty("project_id").GetString()
            });

            return(service);
        }
        public static void ConfigureFirebase(this IServiceCollection services, IConfiguration configuration)
        {
            Dictionary <string, string> firebaseConfigs = new Dictionary <string, string>();

            configuration.GetSection("Firebase").Bind(firebaseConfigs);
            var credential = GoogleCredential.FromJson(JsonConvert.SerializeObject(firebaseConfigs));

            try
            {
                FirebaseApp.Create(new AppOptions()
                {
                    Credential = credential
                });
            }
            catch (System.ArgumentException)
            {
                Console.WriteLine("Firebase app already configured");
            }
        }
示例#8
0
        public static string Start(string AccountGA, string privateKeyGA, string projectId, string metrics, TraceWriter log)
        {
            string t       = string.Empty;
            string storage = string.Empty;

            try
            {
                string[] scopes            = new string[] { AnalyticsService.Scope.Analytics };
                var      credential_google = GoogleCredential.FromJson(privateKeyGA).CreateScoped(scopes);
                var      service           = new AnalyticsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential_google,
                    ApplicationName       = projectId,
                });

                var request = service.Data.Ga.Get(projectId, "30daysAgo", "yesterday", metrics);
                request.MaxResults = 1000;
                var result = request.Execute();
                foreach (var headers in result.ColumnHeaders)
                {
                    t += String.Format("{0} - {1} - {2}", headers.Name, headers.ColumnType, headers.DataType);
                    log.Info(String.Format("{0} - {1} - {2}", headers.Name, headers.ColumnType, headers.DataType));
                }

                foreach (List <string> row in result.Rows)
                {
                    foreach (string col in row)
                    {
                        t += col + " ";
                        log.Info(col + " ");
                    }
                    t += "\r\n";
                    log.Info(t);
                }
            }
            catch (Exception e)
            {
                log.Error("erreur  Stack : " + e.StackTrace + "___" + e.Message);
                t = t + "..." + e.Message;
            }

            return(t);
        }
示例#9
0
        /// <summary>
        /// Obtains credentials asynchronously. Override this method in a concrete builder type if more
        /// credential mechanisms are supported.
        /// </summary>
        protected async virtual Task <IConfigurableHttpClientInitializer> GetHttpClientInitializerAsync(CancellationToken cancellationToken)
        {
            if (Credential != null)
            {
                return(Credential);
            }
            GoogleCredential unscoped =
                CredentialsPath != null?GoogleCredential.FromFile(CredentialsPath) : // TODO: Use an async method when one is available
                    JsonCredentials != null?GoogleCredential.FromJson(JsonCredentials) :
                        null;                                                        // Use default credentials (maybe - see below)

            // While we accept any credentials that are specified even if there's an API key,
            // we don't try to load default credentials.
            if (ApiKey != null && unscoped is null)
            {
                return(null);
            }
            return(await GetScopedCredentialProvider().GetCredentialsAsync(unscoped).ConfigureAwait(false));
        }
示例#10
0
        public RavenGoogleCloudClient(GoogleCloudSettings settings, Config.Categories.BackupConfiguration configuration, Progress progress = null, CancellationToken?cancellationToken = null)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            if (string.IsNullOrWhiteSpace(settings.BucketName))
            {
                throw new ArgumentException("Google Cloud Bucket name cannot be null or empty");
            }

            if (string.IsNullOrWhiteSpace(settings.GoogleCredentialsJson))
            {
                throw new ArgumentException("Google Credentials JSON cannot be null or empty");
            }
            try
            {
                _client = StorageClient.Create(GoogleCredential.FromJson(settings.GoogleCredentialsJson));
                _client.Service.HttpClient.Timeout = configuration.CloudStorageOperationTimeout.AsTimeSpan;
            }
            catch (Exception e)
            {
                throw new ArgumentException("Wrong format for Google Credentials.", e);
            }

            var credentialJsonType = JObject.Parse(settings.GoogleCredentialsJson);

            if (credentialJsonType.TryGetValue(ProjectIdPropertyName, StringComparison.OrdinalIgnoreCase, out var value))
            {
                _projectId = value.Value <string>();
            }

            _bucketName       = settings.BucketName;
            CancellationToken = cancellationToken ?? CancellationToken.None;

            _progress = progress;
        }
示例#11
0
        private GAResults CallAPIGetResults()
        {
            string[] scopes = new string[] { AnalyticsService.Scope.Analytics };
            var      cred   = GoogleCredential.FromJson(_config["Google.API.ServiceAccount.Key"]).CreateScoped(scopes);

            var service = new Google.Apis.Analytics.v3.AnalyticsService(new BaseClientService.Initializer
            {
                ApplicationName       = "mtgdm",
                HttpClientInitializer = cred
            });

            var request = service.Data.Ga.Get(_config["Google.Analytics.ProfileID"],
                                              new DateTime(2020, 10, 01).ToString("yyy-MM-dd"),
                                              DateTime.Now.ToString("yyy-MM-dd"),
                                              "ga:visitors,ga:uniquePageviews");

            request.Dimensions = "ga:pagePath";
            var result = request.Execute();

            var results = new GAResults()
            {
                Columns = new List <string>(),
                Rows    = new List <GAPageViewResults>()
            };

            foreach (var column in result.ColumnHeaders)
            {
                results.Columns.Add(column.Name);
            }

            foreach (var row in result.Rows)
            {
                results.Rows.Add(new GAPageViewResults()
                {
                    PagePath  = row[0],
                    Vistitors = long.Parse(row[1]),
                    PageViews = long.Parse(row[2])
                });
            }

            return(results);
        }
        public GoogleCloudLoggingSink(GoogleCloudLoggingSinkOptions sinkOptions, MessageTemplateTextFormatter messageTemplateTextFormatter, int batchSizeLimit, TimeSpan period)
            : base(batchSizeLimit, period)
        {
            _sinkOptions = sinkOptions;

            // logging client for google cloud apis
            // requires extra setup if credentials are passed as raw json text
            if (sinkOptions.GoogleCredentialJson == null)
            {
                _client = LoggingServiceV2Client.Create();
            }
            else
            {
                var googleCredential = GoogleCredential.FromJson(sinkOptions.GoogleCredentialJson);
                var channel          = new Grpc.Core.Channel(LoggingServiceV2Client.DefaultEndpoint.Host, googleCredential.ToChannelCredentials());
                _client = LoggingServiceV2Client.Create(channel);
            }

            // retrieve current environment details (gke/gce/appengine) from google libraries automatically
            // or fallback to "Global" resource
            var platform = Platform.Instance();

            _resource = platform.Type == PlatformType.Unknown
                ? MonitoredResourceBuilder.GlobalResource
                : MonitoredResourceBuilder.FromPlatform(platform);

            foreach (var kvp in _sinkOptions.ResourceLabels)
            {
                _resource.Labels[kvp.Key] = kvp.Value;
            }

            // use explicit ResourceType if set
            _resource.Type = sinkOptions.ResourceType ?? _resource.Type;

            // use explicit project ID or fallback to project ID found in platform environment details above
            var projectId = _sinkOptions.ProjectId ?? _resource.Labels["project_id"];

            _logName = LogFormatter.CreateLogName(projectId, sinkOptions.LogName);

            _serviceNameAvailable = !String.IsNullOrWhiteSpace(_sinkOptions.ServiceName);
            _logFormatter         = new LogFormatter(projectId, _sinkOptions.UseSourceContextAsLogName, messageTemplateTextFormatter);
        }
        private async Task <SessionsClient> GetSessionClientAsync(CancellationToken cancellationToken)
        {
            if (this.sessionsClient != null)
            {
                return(this.sessionsClient);
            }

            var keyPath          = this.GetConfigurationValue(DialogflowClientKeyPathConfigurationKey, true);
            var googleCredential = keyPath != null
                ? GoogleCredential.FromFile(keyPath)
                : GoogleCredential.FromJson(
                this.GetConfigurationValue(DialogflowClientKeyJsonConfigurationKey));

            var builder = new SessionsClientBuilder
            {
                ChannelCredentials = googleCredential.ToChannelCredentials(),
            };

            return(this.sessionsClient = await builder.BuildAsync(cancellationToken).ConfigureAwait(false));
        }
示例#14
0
        private async Task SendMessageAsync(string token)
        {
            // google-credentials.json is downloaded from FCM clould messaging console
            string credentials = ReadManifestData("google-credentials.json");

            var app = FirebaseApp.Create(new AppOptions()
            {
                Credential = GoogleCredential.FromJson(credentials)
                             .CreateScoped("https://www.googleapis.com/auth/firebase.messaging")
            });

            var messaging = FirebaseMessaging.GetMessaging(app);

            var message = new Message()
            {
                Token = token,
            };

            await messaging.SendAsync(message);
        }
        /// <summary>
        /// Adds an Firebase implementation of identity stores.
        /// </summary>
        /// <param name="builder">The <see cref="IdentityBuilder"/> instance this method extends.</param>
        /// <param name="configure">Action to configure AuthTokenOptions</param>
        /// <returns>The <see cref="IdentityBuilder"/> instance this method extends.</returns>
        public static IdentityBuilder AddFirestoreStores(this IdentityBuilder builder, Action <OAuthServiceAccountKey> configure)
        {
            var services = builder.Services;

            services.Configure(configure)
            .AddScoped(provider =>
            {
                var authOptions = provider.GetRequiredService <IOptions <OAuthServiceAccountKey> >();
                var json        = JsonConvert.SerializeObject(authOptions.Value);
                var credentials = GoogleCredential.FromJson(json)
                                  .CreateScoped("https://www.googleapis.com/auth/datastore");
                var channel = new Grpc.Core.Channel(
                    FirestoreClient.DefaultEndpoint.ToString(),
                    credentials.ToChannelCredentials());
                var client = FirestoreClient.Create(channel);
                return(FirestoreDb.Create(authOptions.Value.project_id, client: client));
            });
            AddStores(services, builder.UserType, builder.RoleType);
            return(builder);
        }
        public static void AddGoogleStorage(this IServiceCollection services, GoogleCloudAuthenticationSettings settings = null)
        {
            services.AddScoped(svcProvider =>
            {
                settings = settings ?? svcProvider.GetService <GoogleCloudAuthenticationSettings>();

                var contractResolver = new DefaultContractResolver {
                    NamingStrategy = new SnakeCaseNamingStrategy()
                };
                var serializeSettins = new JsonSerializerSettings {
                    ContractResolver = contractResolver
                };
                var jsonSettings = JsonConvert.SerializeObject(settings, serializeSettins);
                var credential   = GoogleCredential.FromJson(jsonSettings).CreateScoped(new[] { StorageService.Scope.DevstorageReadWrite });

                return(StorageClient.Create(credential));
            });

            services.AddScoped <IFileUploader, GoogleCloudFileUploader>();
        }
示例#17
0
        /// <summary>
        /// Initializes Drive Service with Json File
        /// </summary>
        /// <param name="keyFilePath"></param>
        public static void InitializeCredentials(string keyFilePath)
        {
            if (!File.Exists(keyFilePath))
            {
                throw new KeyNotFoundException("No Google Drive Key File found @ designated path: " + keyFilePath);
            }

            GoogleCredential cred;

            using (var reader = new StreamReader(keyFilePath))
            {
                cred = GoogleCredential.FromJson(reader.ReadToEnd());
            }
            // Create the service
            _service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = cred,
                ApplicationName       = "Subdivision Application System"
            });
        }
示例#18
0
        public AuthService(IConfiguration configuration, IUserService userService, ILogger <AuthService> logger)
        {
            _configuration = configuration;
            _userService   = userService;
            _logger        = logger;

            var firebaseCredentials = _configuration["Firebase:Credentials"];

            if (firebaseCredentials == string.Empty)
            {
                throw new Exception("Firebase cedentials missing");
            }

            var fb = FirebaseApp.Create(new AppOptions
            {
                Credential = GoogleCredential.FromJson(firebaseCredentials)
            });

            _firebase = FirebaseAuth.GetAuth(fb);
        }
示例#19
0
    public List <Google.Apis.Storage.v1.Data.Object> GetFileList()
    {
        List <Google.Apis.Storage.v1.Data.Object> filesInCloud = new List <Google.Apis.Storage.v1.Data.Object>();

        string currLocalDir = Directory.GetCurrentDirectory();

        string projectId = "stately-mote-267221";

        bucketName = "vmod_bucket";

        string credentialsJson = @"{
                          'type': 'service_account',
                          'project_id': 'stately-mote-267221',
                          'private_key_id': '0b07ba79bf7ac0e0cb2e224958dc260817056302',
                          'private_key': '-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCb6ol5BGiy20Ag\n2nqaeYBhgEVfFUqZ1jW8wM+merA5bm98nZRbvxoH9ZsZ7J2HM4TcuB8vXZLsoOoR\nbPpqRLlAzhBvRrdlG5g3+SKKrV0IIkofrS8hWI5OAwzNcPi/1BpzzguAiU4On+N2\n03gjq3ZyuvwF55/2Y60EE7XSbR6w5KKvaeIXSIsbbKF6Y3vFipFfvnr9ZMQ73Zxp\nil6Lc/UB/thuvMw4vRrCqxjqv1S8LuzGJhriUGytxjg7z9RbO/F+vEM2mhZ6G5ZE\nSbNSACA0VhWUwHterE0XQ+hm0GDoiYKzSZrVKAZ5F6NtfHz1hT4fD9eeXTcyuEgb\nCiwadMWfAgMBAAECggEADnal1Q+XJMxY+RM7X1wZEDJlfQoNFxM7feyG9sMX2OQJ\nPI6jphUmtYlPn4qHHHUnhJAh+HNeP0w4GnC5FCWW58+Vz7TIK31xU/PtA99MK4Z+\nyMx4fEfqP4th4ybxNF5ZK9f30i8qignEAJBiazCrNr5oxaV0fddGRAQOEFymBbOy\nuKCBj/7qBAksKrJLnlwOO+CETZc7UygxEdTdhRJWaKDzBq97LdFgbgyx/n+RFNwW\nk5SFWNtrt+Ah0/nHvgdGi+nJnYAdk/zi7gRaqjbOzm8BpSqSM0Xz7vdBuBfoEjY2\nOWauVOiRErjqskd+Ny0m6QfQABX4Jwk+2FsyLKXO/QKBgQDbAiNepZOVwBfop3Cw\nFfZmjeHgF75PmkefA7kJNMiFAoU97ksOLWXYVwgi+hnbIrZLC6FG70c/KIMF0j1x\nNuIeBflqcNlQs+b/8srTBMwMiYNY11N34Osn3aHMCphwtBOs15wQCyh3troGwhJD\nNsiq/aZGtHtyPb+NJ3cLYsy4cwKBgQC2QE8+N6PR1xSfu5RlSr36L+FFhGCp93Hk\nowaF3xujE8cDjq0/aSghHZUwdodM/Qe4SrHt74Isj4Wy9z34nW8LszGnmTE4eVvF\n15QyU5WD+21bcMH+olyPXRSuS1lCq31gI29moovy7HmN9yO2+CLqlSjtiTj80FzD\nuhLSO7svJQKBgQCISjxYmhHOD0zRq+GkswYzq/f0zNHSF+CaRGbSI9blbzwb3j83\nA2ltyDt4CMwuYtuut/4VdrKPy1Y+OSejXNQ6et1MMA4M+ue2QBGYYFPbOXhTwSxg\nXcf5dyNJJw7WlDnqRgMIuOjmFwCNVBipW15lipP/TDHGVkbuQLEElOdxoQKBgG+J\nM/Xzv0IwyuJmvg6vi0yN+OO+fBoI4Z73VoqfXB6Vf/phWw2voWuC20bpgyxOvma+\n792Z8qSqwTwhq793OfqDFCRp0IGrY8rUgFG8bYh0WxzXCSJ44wSqBnoUivAOW5B2\nnzrEx7lHl6yWTzku6s99saqNjF7MdbkjK1mWTJwxAoGBAIrMqozIdOoAfKxFIDMT\nqoYzamo2q1YMhVbZl++n0tmllv4xQnUv3VUgOlrCR3I6XO/qOHbIiEm3oOuzWDvX\n+uMmbI+7pxUq5M+9MSzvNlVwcVJtBO2UMwdluSBXOtw7lqNp5MZcsdSiNerk6YvQ\n30N+djRrGFeVyre1mGbJCigo\n-----END PRIVATE KEY-----\n',
                          'client_email': '*****@*****.**',
                          'client_id': '101714657942361325319',
                          'auth_uri': 'https://accounts.google.com/o/oauth2/auth',
                          'token_uri': 'https://oauth2.googleapis.com/token',
                          'auth_provider_x509_cert_url': 'https://www.googleapis.com/oauth2/v1/certs',
                          'client_x509_cert_url': 'https://www.googleapis.com/robot/v1/metadata/x509/conu-vmod%40stately-mote-267221.iam.gserviceaccount.com'
                        }";

        GoogleCredential cred = GoogleCredential.FromJson(credentialsJson);

        storage = StorageClient.Create(cred);

        Debug.Log(storage.Service);

        ServicePointManager.ServerCertificateValidationCallback += (System.Object sender, X509Certificate x509Certificate, X509Chain x509Chain, SslPolicyErrors sslPolicyErrors) => true;

        var storageObject = storage.ListObjects(bucketName, "");

        foreach (var stObj in storageObject)
        {
            filesInCloud.Add(stObj);
            //Debug.Log($"found {stObj.Name}");
        }

        return(filesInCloud);
    }
示例#20
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T">What kind of object are you sending me</typeparam>
        /// <param name="collection">Top folder</param>
        /// <param name="obj">The data</param>
        /// <param name="id">The collection in the document</param>
        /// <returns></returns>
        public async Task AddData <T>(string collection, T obj, string id)
        {
            try
            {
                var     serviceAcct = GoogleCredential.FromJson(_config.GetValue <string>("jsonCreds"));
                Channel channel     = new Channel(
                    FirestoreClient.DefaultEndpoint.Host, FirestoreClient.DefaultEndpoint.Port,
                    serviceAcct.ToChannelCredentials());
                FirestoreClient client = FirestoreClient.Create(channel);

                FirestoreDb db = FirestoreDb.Create(_config.GetValue <string>("projectId"), client);

                CollectionReference docRef = db.Collection(collection);

                await docRef.AddAsync(obj);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#21
0
        public GoogleTranslationOptionsRetriever(ILogger <GoogleTranslationOptionsRetriever> logger,
                                                 IOptions <GoogleCredentialOptions> googleCredentialOptions)
        {
            if (logger == null)
            {
                throw new ArgumentNullException(nameof(logger));
            }
            if (googleCredentialOptions == null)
            {
                throw new ArgumentNullException(nameof(googleCredentialOptions));
            }

            var credentials = GoogleCredential.FromJson(JsonConvert.SerializeObject(googleCredentialOptions.Value));

            var builder = new TextToSpeechClientBuilder();

            builder.ChannelCredentials = credentials.ToChannelCredentials();

            _logger = logger;
            _client = builder.Build();
        }
示例#22
0
文件: Video.cs 项目: tikz/VideoUpload
        public Video(Form1 form1, string path, string title, decimal[] from, decimal[] to, int codec, bool upscaleFlag, bool cut)
        {
            form         = form1;
            filePath     = path;
            titleText    = title;
            fromTime     = from;
            toTime       = to;
            codecIndex   = codec;
            dashTitle    = DashString(titleText);
            upscale1440p = upscaleFlag;
            cutVideo     = cut;

            credential = GoogleCredential.FromJson(File.ReadAllText(authFile));
            storage    = StorageClient.Create(credential);

            switch (codecIndex)
            {
            case 0:
                batchPath = "bin/vp9.bat";
                outputExt = ".webm";
                break;

            case 1:
                batchPath = "bin/x264.bat";
                outputExt = ".mp4";
                break;

            case 3:
                batchPath = "bin/overkill.bat";
                outputExt = ".webm";
                break;

            default:
                batchPath = "bin/vp9.bat";
                outputExt = ".webm";
                break;
            }

            outputFile = dashTitle + outputExt;
        }
示例#23
0
        public static QvxDataTable DownloadObject(QvxTable downloadObjectTable, IDictionary <string, string> fields, string jsonCredentials)
        {
            var credential = GoogleCredential.FromJson(jsonCredentials);
            var storage    = StorageClient.Create(credential);

            fields.TryGetValue("bucketname", out string bucketName);
            fields.TryGetValue("objectname", out string objectName);
            fields.TryGetValue("localpath", out string localPath);

            if (String.IsNullOrEmpty(bucketName))
            {
                throw new QvxPleaseSendReplyException(QvxResult.QVX_UNKNOWN_COMMAND, String.Format("Missing required param: {0}", "BucketName"));
            }

            if (String.IsNullOrEmpty(objectName))
            {
                throw new QvxPleaseSendReplyException(QvxResult.QVX_UNKNOWN_COMMAND, String.Format("Missing required param: {0}", "ObjectName"));
            }

            if (String.IsNullOrEmpty(localPath))
            {
                throw new QvxPleaseSendReplyException(QvxResult.QVX_UNKNOWN_COMMAND, String.Format("Missing required param: {0}", "LocalPath"));
            }


            try
            {
                localPath = localPath ?? Path.GetFileName(objectName);
                using (var outputFile = File.OpenWrite(localPath))
                {
                    storage.DownloadObject(bucketName, objectName, outputFile);
                }
                downloadObjectTable.GetRows = DownloadObjectRows(downloadObjectTable);
            } catch (Exception ex)
            {
                QvxLog.Log(QvxLogFacility.Application, QvxLogSeverity.Error, ex.Message);
                throw new QvxPleaseSendReplyException(QvxResult.QVX_UNKNOWN_COMMAND, "Error downloading object from Google Storage");
            }
            return(new QvxDataTable(downloadObjectTable));
        }
示例#24
0
        public ApiGoogleSheets()
        {
            try
            {
                GoogleCredential credential;

                credential = GoogleCredential.FromJson(CallURL("https://fmattiolidossantos2020.000webhostapp.com/credentials.json"))
                             .CreateScoped(Scopes);

                // Create Google Sheets API service.
                service = new SheetsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = ApplicationName,
                });

                // Define request parameters.
                spreadsheetId = "10ZdIxL3kaIRzhO4b_SjPhRA-WpIkXwJG_aXguYbPoQs";
                String range = "DadosPessoais!A1:B2";
                SpreadsheetsResource.ValuesResource.GetRequest request =
                    service.Spreadsheets.Values.Get(spreadsheetId, range);
                ValueRange response = request.Execute();
                var        values   = response.Values;
                //if (values != null && values.Count > 0)
                //{
                //    foreach (var row in values)
                //    {
                //        // Print columns A and E, which correspond to indices 0 and 4.
                //        Console.WriteLine("{0}, {1}", row[0], row[1]);
                //    }
                //}
                //else
                //{
                //    Console.WriteLine("No data found.");
                //}
            }
            catch (Exception erro)
            {
            }
        }
        private void InitGoogleAPI()
        {
            ResourceManager RM = new ResourceManager("GoogleAPI.Properties.Resources", Assembly.GetExecutingAssembly());

            byte[] credentialsFile = (byte[])RM.GetObject("credentials");
            string json            = Encoding.UTF8.GetString(credentialsFile);

            GoogleCredential credential = GoogleCredential.FromJson(json);

            Storage = StorageClient.Create(credential);

            string path = System.IO.Path.GetTempPath() + "credentials.json";

            File.WriteAllBytes(path, Properties.Resources.credentials);

            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", path);
            ImageAnnotator = ImageAnnotatorClient.Create();

            ServiceAccountCredential serviceAccountCredential = ServiceAccountCredential.FromServiceAccountData(new MemoryStream(credentialsFile));

            UrlSigner = UrlSigner.FromServiceAccountCredential(serviceAccountCredential);
        }
示例#26
0
        public AnalyticService(IHostingEnvironment env,
                               IServiceProvider serviceProvider)
        {
            _env             = env;
            _serviceProvider = serviceProvider;


            // Initialize google analytics
            string[] reportingServiceScopes = { AnalyticsReportingService.Scope.AnalyticsReadonly };
            _reportingService = new AnalyticsReportingService(
                new BaseClientService.Initializer
            {
                HttpClientInitializer = GoogleCredential.FromJson(CPLConstant.Analytic.Credential).CreateScoped(reportingServiceScopes)
            });

            string[] analyticsServiceScope = { AnalyticsService.Scope.AnalyticsEdit };
            _analyticsService = new AnalyticsService(
                new BaseClientService.Initializer
            {
                HttpClientInitializer = GoogleCredential.FromJson(CPLConstant.Analytic.Credential).CreateScoped(analyticsServiceScope)
            });
        }
示例#27
0
        protected override void AddUserStore(IServiceCollection services, object context = null)
        {
            services.Configure <OAuthServiceAccountKey>(options =>
            {
                _fixture.Configuration.GetSection("AuthTokenOptions").Bind(options);
            });

            services.AddFirebaseClient(_fixture.Configuration["FirebaseOptions:DatabaseUrl"], provider =>
            {
                var options = provider.GetRequiredService <IOptions <OAuthServiceAccountKey> >();
                var json    = JsonConvert.SerializeObject(options?.Value ?? throw new ArgumentNullException(nameof(options)));
                return(GoogleCredential.FromJson(json)
                       .CreateScoped("https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/firebase.database")
                       .UnderlyingCredential);
            });

            var userType      = typeof(TestUser);
            var userStoreType = typeof(UserStore <,>).MakeGenericType(userType, typeof(TestRole));

            services.TryAddSingleton(typeof(UserOnlyStore <>).MakeGenericType(userType), provider => new UserOnlyStoreStub(_fixture.TestDb, provider.GetRequiredService <IFirebaseClient>(), provider.GetService <IdentityErrorDescriber>()));
            services.TryAddSingleton(typeof(IUserStore <>).MakeGenericType(userType), provider => new UserStoreStub(_fixture.TestDb, provider.GetRequiredService <IFirebaseClient>(), provider.GetRequiredService <UserOnlyStore <TestUser> >(), provider.GetService <IdentityErrorDescriber>()));
        }
示例#28
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            string currentDirectory = Directory.GetCurrentDirectory();
            string path             = Path.Combine(currentDirectory, "etutorapp-25808-firebase-adminsdk-exwmv-656a0fd3f9.json");

            Console.WriteLine(path);
            Console.WriteLine("\n");

            string json = File.ReadAllText(path, Encoding.UTF8);

            var firebase = FirebaseApp.Create(new AppOptions
            {
                Credential = GoogleCredential.FromJson(json)
            });

            Console.WriteLine(firebase.Name);

            FirebaseMessaging messaging = FirebaseMessaging.DefaultInstance;

            Message message = new Message
            {
                Notification = new Notification
                {
                    Title = "Simple Notification",
                    Body  = "Part of the body"
                },
                Token =
                    "crhm711-RDw:APA91bFtsuksmqhOzzGe7efmkRJIG7kknhZb31XsUJZszB1mkd3suKggOiTU6UShSUMKD4PT_SXz4E7VMeZDsk_kZbj1uUx005chJlcIe1dXINroX_T7tJmjNPiKuEfyVGZwCnLw2jAE"
            };

            var result = messaging.SendAsync(message);

            Task.WaitAll();

            Console.WriteLine($"RESULT MESSAGE: {result.Result}");
        }
示例#29
0
        public RavenGoogleCloudClient(GoogleCloudSettings settings, CancellationToken?cancellationToken = null, Progress progress = null)
        {
            try
            {
                _client = StorageClient.Create(GoogleCredential.FromJson(settings.GoogleCredentialsJson));
            }
            catch (Exception e)
            {
                throw new ArgumentException("Wrong format for account key.", e);
            }

            var credentialJsonType = JObject.Parse(settings.GoogleCredentialsJson);

            if (credentialJsonType.TryGetValue(ProjectIdPropertyName, StringComparison.OrdinalIgnoreCase, out var value))
            {
                _projectId = value.Value <string>();
            }

            _bucketName       = settings.BucketName;
            CancellationToken = cancellationToken ?? CancellationToken.None;

            _progress = progress;
        }
示例#30
0
        private GoogleCredential GetCredentialFromConfiguration()
        {
            var nullLogEvent   = LogEventInfo.CreateNullEvent();
            var credentialFile = CredentialFile?.Render(nullLogEvent);
            var credentialJson = CredentialJson?.Render(nullLogEvent);

            GaxPreconditions.CheckState(string.IsNullOrWhiteSpace(credentialFile) || string.IsNullOrWhiteSpace(credentialJson),
                                        $"{nameof(CredentialFile)} and {nameof(CredentialJson)} must not both be set.");
            var credential =
                !string.IsNullOrWhiteSpace(credentialFile) ? GoogleCredential.FromFile(credentialFile) :
                !string.IsNullOrWhiteSpace(credentialJson) ? GoogleCredential.FromJson(credentialJson) :
                null;

            if (credential == null)
            {
                return(null);
            }
            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(s_oAuthScopes);
            }
            return(credential);
        }