Exemplo n.º 1
0
        public void GetCollectionGetsObjectsOfType()
        {
            var index   = new IndexStore("GetAll");
            var fs      = new FileDataStore("GetAll", index);
            var journal = new FileJournal("GetAll", fs);
            var store   = new InMemoryDataStore(fs, journal.DirectoryPath);

            try
            {
                var sword  = new Sword("Lego Sword", 13);
                var katana = new Sword("Lego Katana", 27);

                store.PutObject(sword, 1);
                store.PutObject(katana, 2);
                store.PutObject(new Car("Kia", "Aieeee", "Black"), 3);

                var actual = store.GetCollection <Sword>();
                Assert.AreEqual(2, actual.Count);
                Assert.AreEqual(sword, actual.ElementAt(0));
                Assert.AreEqual(katana, actual.ElementAt(1));
            }
            finally
            {
                Directory.Delete("GetAll", true);
            }
        }
Exemplo n.º 2
0
    /// <summary>
    /// This function is used to create a new instance of Drive client service
    /// </summary>
    /// <returns></returns>
    public async Task <DriveService> CreateDriveClientAsync()
    {
        var driveAuth = _googleCloudConfig.DriveAuth;
        var credPath  = Path.Combine("Storage", "Common", "gdrive-auth-token-store").SanitizeSlash().EnsureDirectory();
        var secrets   = await GoogleClientSecrets.FromFileAsync(driveAuth);

        var fileDataStore = new FileDataStore(credPath, true);
        var credential    = await GoogleWebAuthorizationBroker.AuthorizeAsync(
            secrets.Secrets,
            new[]
        {
            DriveService.Scope.Drive,
            DriveService.Scope.DriveFile
        },
            "user",
            CancellationToken.None,
            fileDataStore);

        Log.Debug("Credential saved to {CredPath}", credPath);

        Log.Debug("Initializing Drive service");
        var service = new DriveService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName       = "ZiziBot"
        });

        return(service);
    }
Exemplo n.º 3
0
        public static async Task <ODConnection> SignInToMicrosoftAccount(System.Windows.Forms.IWin32Window parentWindow, string userid, string path)
        {
            FileDataStore  datastore       = new FileDataStore(path);
            AppTokenResult oldRefreshToken = await LoadToken(datastore, userid, CancellationToken.None).ConfigureAwait(false);

            AppTokenResult appToken = null;

            if (oldRefreshToken != null)
            {
                appToken = await MicrosoftAccountOAuth.RedeemRefreshTokenAsync(msa_client_id, msa_client_secret, oldRefreshToken.RefreshToken);
            }

            if (null == appToken)
            {
                appToken = await MicrosoftAccountOAuth.LoginAuthorizationCodeFlowAsync(msa_client_id,
                                                                                       msa_client_secret,
                                                                                       new[] { "wl.offline_access", "wl.basic", "wl.signin", "onedrive.readwrite" });
            }

            if (null != appToken)
            {
                SaveRefreshToken(appToken.RefreshToken, datastore, userid);

                return(new ODConnection("https://api.onedrive.com/v1.0", new OAuthTicket(appToken)));
            }

            return(null);
        }
Exemplo n.º 4
0
        public static async Task <ODConnection> SignInToMicrosoftAccount(string userid, string path)
        {
            FileDataStore  datastore       = new FileDataStore(path);
            AppTokenResult oldRefreshToken = await LoadToken(datastore, userid, CancellationToken.None).ConfigureAwait(false);

            AppTokenResult appToken = null;

            if (oldRefreshToken != null)
            {
                appToken = await MicrosoftAccountOAuth.RedeemRefreshTokenAsync(msa_client_id, msa_client_secret, oldRefreshToken.RefreshToken);
            }

            if (null == appToken)
            {
                string code = await loginform.GetAuthenticationToken(msa_client_id, new[] { "wl.offline_access", "wl.basic", "wl.signin", "onedrive.readwrite" }, userid, "https://login.live.com/oauth20_authorize.srf", "https://login.live.com/oauth20_desktop.srf", LoginOption.OneDrive);

                appToken = await OneDriveWebAuthorization.RedeemAuthorizationCodeAsync(msa_client_id, "https://login.live.com/oauth20_desktop.srf", msa_client_secret, code);
            }

            if (null != appToken)
            {
                SaveRefreshToken(appToken, datastore, userid);

                return(new ODConnection("https://api.onedrive.com/v1.0", new OAuthTicket(appToken)));
            }

            return(null);
        }
        public async Task DefaultLocation()
        {
            const string key1  = "testkey1";
            const string key2  = "testkey2";
            var          store = new FileDataStore("IntegrationTesting");
            // Clear
            await store.ClearAsync();

            // Check it's empty
            Assert.Null(await store.GetAsync <string>(key1));
            Assert.Equal(0, await store.GetAsync <int>(key2));
            // Add data
            await store.StoreAsync(key1, "1");

            await store.StoreAsync(key2, 2);

            // Check data still there
            Assert.Equal("1", await store.GetAsync <string>(key1));
            Assert.Equal(2, await store.GetAsync <int>(key2));
            // Delete one item
            await store.DeleteAsync <string>(key1);

            // Check only that one item has gone
            Assert.Null(await store.GetAsync <string>(key1));
            Assert.Equal(2, await store.GetAsync <int>(key2));
            // Clear
            await store.ClearAsync();

            // Check alldata has gone
            Assert.Null(await store.GetAsync <string>(key1));
            Assert.Equal(0, await store.GetAsync <int>(key2));
        }
        /// <summary>
        /// Retrive Google OAuth user credentials, using credentials.json
        /// Token is stored in filesystem for further useh
        /// <returns></returns>
        private async Task GetCredentials()
        {
            if (!File.Exists(_credentialsFilename))
            {
                throw new Exception(String.Format("Google credentials file = '{0}' doesn't exists", _credentialsFilename));
            }

            var json = File.ReadAllText(_credentialsFilename);

            GoogleClientSecrets clientSecrets;

            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                clientSecrets = GoogleClientSecrets.Load(stream);
            }

            var dataStore = new FileDataStore(_tokenStoreDir, true);


            //using (var stream = new FileStream(_credentialsFilename, FileMode.Open, FileAccess.Read))
            //{
            var credentials = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                clientSecrets?.Secrets,
                //GoogleClientSecrets.Load(stream).Secrets,
                _scopes,
                _userName,
                CancellationToken.None,
                dataStore);

            _credentials = credentials;
            //}
        }
Exemplo n.º 7
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            WebhookRequest data = JsonConvert.DeserializeObject <WebhookRequest>(requestBody);

            var           token = new FileDataStore("Google.Apis.Auth").GetAsync <TokenResponse>("user");
            IntentsClient clnt  = IntentsClient.Create();

            var gcred = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS");


            var dayOfWeek = data.queryResult.parameters.dayofweek;
            var leerling  = data.queryResult.parameters.leerling;
            var action    = data.queryResult.parameters.tijd;

            return(name != null
                ? (ActionResult) new OkObjectResult($"Hello, {name}")
                : new BadRequestObjectResult("Please pass a name on the query string or in the request body"));
        }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            // The problem:
            // Some operations on a file are needed before reading from and writing to the file.
            // Without the decorator pattern, a new subclass of FileDataStore would be needed for each
            // new operation. This causes a problem when a combination of two or more operations are needed.

            // The solution:
            // Creating wrappers around FileDataStore that implements the same interface as FileDataStore itself.
            // This way, the wrappers can call the methods of FileDataStore after adding their additional
            // functionalities in those same methods.

            IDataStore dataStore = new FileDataStore("file1");

            dataStore = new FileCompressionDecorator(dataStore);
            dataStore = new FileEncryptionDecorator(dataStore);

            // In some other part of the code, a client is using the dataStore to read and write data
            // without caring about the underlying operations that take place before reading and writing.
            // This way, we can add a new decorator that extends those operations without changing the
            // client code.

            dataStore.WriteData("data");
            dataStore.ReadData();

            // Consequences:
            // Ordering the wrappers is important.
            // Removing a wrapper from the wrappers stack is difficult.
        }
Exemplo n.º 9
0
 public static FileDataStore GetFileDataStore()
 {
     var path = HttpContext.Current.Server.MapPath("~/App_Data/Drive.Api.Auth.Store");
     FileDataStore fileDataStore=new FileDataStore(path);
     fileDataStore.ClearAsync();
     return fileDataStore;
 }
Exemplo n.º 10
0
        public static UserCredential getCredentials(string forUser)
        {
            if (forUser == null)
            {
                throw new ArgumentNullException();
            }
            if (forUser.Trim().Length == 0)
            {
                throw new ArgumentException();
            }
            if (forUser.Equals(username))
            {
                return(credentials);
            }
            if (credentials == null)
            {
                username = forUser;
            }

            ClientSecrets secrets;

            using (var stream = new FileStream(Path.Combine(Directory.GetCurrentDirectory(), "client_secret.json"), FileMode.Open, FileAccess.Read)) {
                secrets = GoogleClientSecrets.Load(stream).Secrets;
            }

            FileDataStore store = new FileDataStore("PersonalVideoOrganizer");

            credentials = GoogleWebAuthorizationBroker.AuthorizeAsync(secrets, new[] { YouTubeService.Scope.YoutubeReadonly }, username, CancellationToken.None, store).Result;

            return(credentials);
        }
Exemplo n.º 11
0
            public static async Task<ODConnection> SignInToMicrosoftAccount(string userid, string path)
            {
                FileDataStore datastore = new FileDataStore(path);
                AppTokenResult oldRefreshToken = await LoadToken(datastore, userid, CancellationToken.None).ConfigureAwait(false);
                AppTokenResult appToken = null;
                if (oldRefreshToken != null)
                {
                    appToken = await MicrosoftAccountOAuth.RedeemRefreshTokenAsync(msa_client_id, msa_client_secret, oldRefreshToken.RefreshToken);
                }

                if (null == appToken)
                {
                    string code = await loginform.GetAuthenticationToken(msa_client_id, new[] { "wl.offline_access", "wl.basic", "wl.signin", "onedrive.readwrite" }, userid, "https://login.live.com/oauth20_authorize.srf", "https://login.live.com/oauth20_desktop.srf", LoginOption.OneDrive);

                    appToken = await OneDriveWebAuthorization.RedeemAuthorizationCodeAsync(msa_client_id, "https://login.live.com/oauth20_desktop.srf", msa_client_secret, code);
                }

                if (null != appToken)
                {
                    SaveRefreshToken(appToken, datastore, userid);

                    return new ODConnection("https://api.onedrive.com/v1.0", new OAuthTicket(appToken));
                }

                return null;
            }
        private async Task <bool> Authenticate(string clientId, string clientSecret)
        {
            Log.Info("Authenticating to google");
            var res = true;

            try
            {
                DataStore  = new FileDataStore(DataStorePath);
                Credential = await
                             GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
                {
                    ClientId     = clientId,
                    ClientSecret = clientSecret
                },
                                                                         new[] { CalendarService.Scope.Calendar },
                                                                         "user",
                                                                         CancellationToken.None,
                                                                         DataStore);

                //
                Service = new CalendarService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = Credential,
                    ApplicationName       = _settings.ApplicationName
                });
            }
            catch (Exception ex)
            {
                Log.Error("Exception", ex);
                res = false;
            }
            return(res);
        }
Exemplo n.º 13
0
        private void ObtainCredentialToken(bool updateCalendarList)
        {
            try
            {
                using (FileStream fs = new FileStream(SecretFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    ClientSecrets Secrets = GoogleClientSecrets.Load(fs).Secrets;
                    FileDataStore Store   = new FileDataStore(CredentialFile, true);
                    string[]      Scopes  = { CalendarService.Scope.Calendar };

                    CredentialToken = GoogleWebAuthorizationBroker.AuthorizeAsync(Secrets, Scopes, "user", CancellationToken.None, Store).Result;

                    NotifyPropertyChanged(nameof(IsCredentialConfirmed));
                }
            }
            catch
            {
                return;
            }

            if (updateCalendarList)
            {
                StartUpdatingCalendarList();
            }
        }
Exemplo n.º 14
0
        public BuddySheets(string sheetID, string sheetName, int columnStart, int rowStart)
        {
            this.SheetID        = sheetID;
            this.StartingRow    = rowStart;
            this.StartingColumn = columnStart;
            this.SheetName      = sheetName;
            // 'Prime Stuff (flat)'!A3:B226
            this.ItemRange = string.Format("'{0}'!{1}:{2}", sheetName, A1(columnStart, rowStart), A1(columnStart + 1, rowStart + ITEM_AMOUNT));

            using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                path = Path.Combine(path, ".buddy/creds.json");

                ClientSecrets secrets = GoogleClientSecrets.Load(stream).Secrets;
                FileDataStore store   = new FileDataStore(path, true);

                Credentials = GoogleWebAuthorizationBroker.AuthorizeAsync(secrets, Scopes, "BuddyUser", CancellationToken.None, store).Result;
            }

            Service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = Credentials,
                ApplicationName       = ApplicationName,
            });
        }
Exemplo n.º 15
0
        /// <summary>
        /// Get OAUTH2 token needed to Authenticate SMTP client
        /// </summary>
        /// <PARAM name="userAccount"></PARAM>
        /// <PARAM name="clientSecrets"></PARAM>
        /// <PARAM name="accessScopes"></PARAM>
        /// <returns></returns>
        public static SaslMechanism GetAuth2Token(string userAccount, ClientSecrets clientSecrets, string[] accessScopes)
        {
            var AppFileDataStore = new FileDataStore("CredentialCacheFolder", false);

            var codeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                DataStore     = AppFileDataStore,
                Scopes        = accessScopes,
                ClientSecrets = clientSecrets
            });

            var codeReceiver = new LocalServerCodeReceiver();
            var authCode     = new AuthorizationCodeInstalledApp(codeFlow, codeReceiver);

            UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                clientSecrets
                , accessScopes
                , userAccount
                , CancellationToken.None
                , AppFileDataStore).Result;

            if (credential.Token.IsExpired(SystemClock.Default))
            {
                credential.RefreshTokenAsync(CancellationToken.None);
            }

            // Note: We use credential.UserId here instead of GMail account because the user *may* have chosen a
            // different GMail account when presented with the browser window during the authentication process.
            SaslMechanism oauth2;

            oauth2 = new SaslMechanismOAuth2(credential.UserId, credential.Token.AccessToken);
            return(oauth2);
        }
        // log in to all servers
        public async Task Login(DiscordServer server)
        {
            var credentialPath = $@"{_credentialPathPrefix}/{server.ServerId}";

            using (var stream = new FileStream(_filePath, FileMode.Open, FileAccess.Read))
            {
                // build code flow manager to authenticate token
                var flowManager = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = GoogleClientSecrets.Load(stream).Secrets,
                    Scopes        = _scopes,
                    DataStore     = new FileDataStore(credentialPath, true)
                });

                var fileDataStore = new FileDataStore(credentialPath, true);
                var token         = await fileDataStore.GetAsync <TokenResponse>("token");

                // load token from file
                // var token = await flowManager.LoadTokenAsync(_userId, CancellationToken.None).ConfigureAwait(false);

                // check if we need to get a new token
                if (flowManager.ShouldForceTokenRetrieval() || token == null ||
                    token.RefreshToken == null && token.IsExpired(flowManager.Clock))
                {
                    return;
                }

                // set credentials to use for syncing
                server.GoogleUserCredential = new UserCredential(flowManager, _userId, token);
            }
        }
Exemplo n.º 17
0
        static FileDataStore GetFileDataStore()
        {
            var path  = HttpContext.Current.Server.MapPath("~/App_Data/Drive.Api.Auth.Store");
            var store = new FileDataStore(path, fullPath: true);

            return(store);
        }
 /// <summary>
 /// Deletes the user from our datastore
 /// </summary>
 /// <param name="smartMirrorUsername">The custom username id to verify which user it is in our application</param>
 /// <returns></returns>
 public async Task LogoutGoogle(string smartMirrorUsername)
 {
     _currentUser = new GoogleUserModel();
     var dataStore = new FileDataStore(DataStoreLocation);
     await dataStore.DeleteAsync<TokenResponse>(smartMirrorUsername);
     DeleteSpecificUserFromDb(smartMirrorUsername);
 }
Exemplo n.º 19
0
        public FileJournal(string databaseName, FileDataStore fileStore)
        {
            this.databaseName  = databaseName;
            this.directoryName = databaseName.SantizeForDatabaseName();

            this.journalDir = string.Format(@"{0}\Journal", directoryName);
            if (!Directory.Exists(journalDir))
            {
                Directory.CreateDirectory(journalDir);
            }

            this.fileStore = fileStore;
            this.LoadUncommittedEntries();

            queueTimer.Elapsed += (sender, eventArgs) =>
            {
                if (this.isRunning)
                {
                    this.ProcessRecords();
                }
            };
            queueTimer.Start();

            this.isRunning = true;
        }
Exemplo n.º 20
0
 /// <summary>
 /// The default constructor for GoogleSync. This should never be called directly. You should always use GoogleSync.Syncer
 /// </summary>
 public GoogleSync()
 {
     m_currentCalendar = "primary";
     m_lastUpdate      = DateTime.MinValue;
     m_calendarList    = null;
     m_fileDataStore   = new FileDataStore(m_workingDirectory, true);
 }
Exemplo n.º 21
0
 public bool HasStoredTokens()
 {
     var store = new FileDataStore("GoogleCalendar.Test");
     var t = store.GetAsync<TokenResponse>(StoreKey);
     t.Wait(TimeSpan.FromMilliseconds(100));
     return t.Result != null;
 }
Exemplo n.º 22
0
        public void GetCollectionWithIdReturnsObjectsByType()
        {
            var index = new IndexStore("GetByType");
            var fs    = new FileDataStore("GetByType", index);

            try
            {
                fs.PutObject(fit, 1);
                index.IndexObject(fit, 1);

                fs.PutObject(rat, 2);
                index.IndexObject(rat, 2);

                fs.PutObject(prius, 3);
                index.IndexObject(prius, 3);

                var actual = fs.GetCollectionWithId <Car>();
                Assert.AreEqual(2, actual.Count);
                var first = actual.ElementAt(0);
                Assert.AreEqual(1, first.Key);
                Assert.AreEqual(fit, first.Value);
                var second = actual.ElementAt(1);
                Assert.AreEqual(3, second.Key);
                Assert.AreEqual(prius, second.Value);
            }
            finally
            {
                fs.DeleteDatabase();
            }
        }
        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";
            // Get the tokens from the FileDataStore
            var token = new FileDataStore("Google.Apis.Auth")
                        .GetAsync <TokenResponse>("user");


            //UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            //    new ClientSecrets
            //    {
            //        ClientId = "68942521982-f9h411ncn58sg54s75jctuckes2ibevo.apps.googleusercontent.com",
            //        ClientSecret = "9wyNRGLHjm_Iv_8oUtz0Eojk",
            //    },
            //    new[] { CalendarService.Scope.Calendar, "https://www.google.com/m8/feeds/" }, // This will ask the client for concent on calendar and contatcs
            //    "user",
            //    CancellationToken.None).Result;
            //// Create the calendar service.
            //CalendarService cal_service = new CalendarService(new BaseClientService.Initializer()
            //{
            //    HttpClientInitializer = credential,
            //    ApplicationName = "EventManagement",
            //});

            // How do I use the found credential to create a ContactsService????
            ContactsService service = new ContactsService("EventManagement");

            OAuth2Parameters parameters = new OAuth2Parameters()
            {
                ClientId     = "68942521982-f9h411ncn58sg54s75jctuckes2ibevo.apps.googleusercontent.com",
                ClientSecret = "9wyNRGLHjm_Iv_8oUtz0Eojk",
                RedirectUri  = "https://localhost:44300/signin-google",
                Scope        = "https://docs.google.com/feeds/ ",
                State        = "documents",
                AccessType   = "offline"
            };

            parameters.AccessCode = Request.QueryString["code"];
            // it gets accesstoken from google
            Google.GData.Client.OAuthUtil.GetAccessToken(parameters);
            GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, "EventManagement", parameters);

            service.RequestFactory = requestFactory;
            //OAuth2Parameters parameters = new OAuth2Parameters
            //{
            //    ClientId = "68942521982-f9h411ncn58sg54s75jctuckes2ibevo.apps.googleusercontent.com",
            //    ClientSecret = "9wyNRGLHjm_Iv_8oUtz0Eojk",
            //    // Note: AccessToken is valid only for 60 minutes
            //   // AccessToken = token.Result.AccessToken,
            //   // RefreshToken = token.Result.RefreshToken
            //};
            RequestSettings settings = new RequestSettings("EventManagement", parameters);

            ContactsRequest cr    = new ContactsRequest(settings);
            GContactData    gdata = new GContactData();

            gdata.PrintDateMinQueryResults(cr);
            return(View());
        }
Exemplo n.º 24
0
 public static async Task SaveToken(FileDataStore datastore, string userid, TokenResult token, CancellationToken cancellation)
 {
     cancellation.ThrowIfCancellationRequested();
     if (datastore != null)
     {
         await datastore.StoreAsync <TokenResult>(userid, token);
     }
 }
Exemplo n.º 25
0
 public void SetUp()
 {
     if (!Directory.Exists(testDirectory))
     {
         Directory.CreateDirectory(testDirectory);
     }
     store = new FileDataStore(testDirectory, ".bin");
 }
        public async Task <ActionResult> Clear(CancellationToken cancellationToken)
        {
            var fileDataStore = new FileDataStore(AppDomain.CurrentDomain.BaseDirectory + "/App_Data/People.Api.Auth.Store", true);

            await fileDataStore.ClearAsync();

            return(View("~/Views/Admin/GoogleAuth/Index.cshtml", null));
        }
Exemplo n.º 27
0
        private string GetGoogleAccountCredentialsFolder()
        {
            var fullFolderPath = new FileDataStore(Program.AppName, false);

            var credPath = fullFolderPath.FolderPath;

            return(credPath);
        }
Exemplo n.º 28
0
 private static async void SaveRefreshToken(AppTokenResult AppToken, FileDataStore datastore, string userid)
 {
     if (AppToken != null)
     {
         AppTokenResult settings = AppToken;
         await SaveToken(datastore, userid, settings, CancellationToken.None);
     }
 }
Exemplo n.º 29
0
 public static async Task DeleteToken(FileDataStore datastore, string userid, CancellationToken cancellation)
 {
     cancellation.ThrowIfCancellationRequested();
     if (datastore != null)
     {
         await datastore.DeleteAsync <AppTokenResult>(userid);
     }
 }
Exemplo n.º 30
0
        public async Task <bool> RefreshAccessTokenAsync(string userid, FileDataStore datastore)
        {
            var newTicket = await OneDriveLogin.RenewAccessTokenAsync(this, datastore, userid);

            PopulateOAuthTicket(newTicket);

            return(newTicket != null);
        }
Exemplo n.º 31
0
 public static async Task ClearToken(FileDataStore datastore, CancellationToken cancellation)
 {
     cancellation.ThrowIfCancellationRequested();
     if (datastore != null)
     {
         await datastore.ClearAsync();
     }
 }
Exemplo n.º 32
0
        /// <summary>
        /// If modifying these scopes, delete your previously saved credentials.
        /// </summary>
        /// <param name="clientSecretJson"></param>
        /// <param name="userName"></param>
        /// <param name="appName"></param>
        /// <param name="scopes"></param>
        /// <param name="authenticationFile">If it is null, the constructor create one into its own folder.</param>
        public GDConnection(string clientSecretJson, string userName, string appName, string[] scopes, FileDataStore authenticationFile = null)
        {
            try
            {
                if (string.IsNullOrEmpty(clientSecretJson))
                {
                    throw new ArgumentNullException("clientSecretJson");
                }
                if (string.IsNullOrEmpty(userName))
                {
                    throw new ArgumentNullException("userName");
                }
                if (string.IsNullOrEmpty(appName))
                {
                    throw new ArgumentNullException("appName");
                }
                if (scopes == null || scopes.Length == 0)
                {
                    throw new ArgumentNullException("scopes");
                }

                UserCredential credential;

                using (MemoryStream stream = new MemoryStream())
                {
                    StreamWriter writer = new StreamWriter(stream);
                    writer.Write(clientSecretJson);
                    writer.Flush();
                    stream.Position = 0;

                    if (authenticationFile == null)
                    {
                        string credPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "//Credentials";
                        authenticationFile = new FileDataStore(credPath, true);
                    }

                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
                                                                             scopes,
                                                                             userName,
                                                                             CancellationToken.None,
                                                                             authenticationFile).Result;
                }

                Service = new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = appName
                });

                folderIds = new Dictionary <string, string>();
                folderIds.Add("root", "root");
                Init();
            }
            catch (Exception ex)
            {
                throw new Exception("CreateDriveServiceFailed", ex);
            }
        }
Exemplo n.º 33
0
        public void LoginToGoogle(string username)
        {
            UserName = username;

            //OAuth2 for all services
            List <String> scopes = new List <string>();

            //Contacts-Scope
            scopes.Add("https://www.google.com/m8/feeds");

            ////Notes-Scope
            //scopes.Add("https://docs.google.com/feeds/");
            ////scopes.Add("https://docs.googleusercontent.com/");
            ////scopes.Add("https://spreadsheets.google.com/feeds/");

            ////Calendar-Scope
            ////scopes.Add("https://www.googleapis.com/auth/calendar");
            //scopes.Add(CalendarService.Scope.Calendar);

            //take user credentials
            UserCredential credential;

            //load client secret from ressources
            byte[] jsonSecrets = Properties.Resources.client_secrets;

            using (var stream = new MemoryStream(jsonSecrets))
            {
                var fDs = new FileDataStore(Folder + "\\Authen\\" + UserName, true);

                var clientSecrets = GoogleClientSecrets.Load(stream);

                credential = GCSMOAuth2WebAuthorizationBroker.AuthorizeAsync(
                    clientSecrets.Secrets,
                    scopes.ToArray(),
                    username,
                    CancellationToken.None,
                    fDs).
                             Result;

                var initializer = new Google.Apis.Services.BaseClientService.Initializer();
                initializer.HttpClientInitializer = credential;

                OAuth2Parameters parameters = new OAuth2Parameters
                {
                    ClientId     = clientSecrets.Secrets.ClientId,
                    ClientSecret = clientSecrets.Secrets.ClientSecret,

                    // Note: AccessToken is valid only for 60 minutes
                    AccessToken  = credential.Token.AccessToken,
                    RefreshToken = credential.Token.RefreshToken
                };

                RequestSettings settings = new RequestSettings("Google Contact Sync - Seta International", parameters);

                ContactsRequest = new ContactsRequest(settings);
            }
        }
Exemplo n.º 34
0
 public static async Task <AppTokenResult> LoadToken(FileDataStore datastore, string userid, CancellationToken cancellation)
 {
     cancellation.ThrowIfCancellationRequested();
     if (datastore != null)
     {
         return(await datastore.GetAsync <AppTokenResult>(userid).ConfigureAwait(false));
     }
     return(null);
 }
Exemplo n.º 35
0
 public static UserCredential createCredential(ClientSecrets cs, FileDataStore fds)
 {
     UserCredential uc = GoogleWebAuthorizationBroker.AuthorizeAsync(
         cs,
         new[] { BloggerService.Scope.Blogger },
         "user",
         CancellationToken.None,
         fds
         ).Result;
     return uc;
 }
Exemplo n.º 36
0
        public BloggerManager(string clientId, string clientSec, string appName)
        {
            _csAppSec = new ClientSecrets
            {
                ClientId = clientId,
                ClientSecret = clientSec
            };

            _fdsStore = new FileDataStore(appName);
            _strAppName = appName;
        }
Exemplo n.º 37
0
        public bool Start(Simian simian)
        {
            m_simian = simian;
            m_userClient = m_simian.GetAppModule<IUserClient>();

            // Library user and inventory creation
            string libraryOwnerName = "Library Owner";
            IConfig config = simian.Config.Configs["StandaloneInventoryClient"];
            if (config != null)
            {
                libraryOwnerName = config.GetString("LibraryOwnerName", "Library Owner");
            }
            CreateLibrary(libraryOwnerName);

            // Deserialize inventories from disk
            m_fileDataStore = m_simian.GetAppModule<FileDataStore>();
            if (m_fileDataStore != null)
            {
                IList<SerializedData> inventories = m_fileDataStore.Deserialize(UUID.Zero, "Inventory");
                for (int i = 0; i < inventories.Count; i++)
                {
                    string name = inventories[i].Name;

                    UUID ownerID;
                    if (UUID.TryParse(name, out ownerID))
                    {
                        OSDMap map = null;
                        try { map = OSDParser.Deserialize(inventories[i].Data) as OSDMap; }
                        catch (Exception) { }

                        if (map != null)
                            DeserializeInventory(ownerID, map);
                        else
                            m_log.Warn("Failed to deserialize inventory file " + name);
                    }
                }
            }

            return true;
        }
Exemplo n.º 38
0
        private void SetCalendar()
        {
            scopes.Add(CalendarService.Scope.Calendar);
            UserCredential credential = default(UserCredential);
            FileDataStore _fdsToken = new FileDataStore("CT");
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
              new ClientSecrets
              {
                  ClientId = "466513012782-ubgcnh2c3f25iprbhbmisb2l4i8965lf.apps.googleusercontent.com",
                  ClientSecret = "JQT2RdjIoMjHuevYwfyFnefx",

              }, scopes,
              "ZZZZZZZZZZZZZZZZZZZ",
            CancellationToken.None, _fdsToken).Result;
            credential.Token.ExpiresInSeconds = 500000;
            String token = credential.Token.RefreshToken;
            credential.Token.RefreshToken = "1/wU76ItFh-n64iqZLjIiXER0Vx4u-MxEnHtHFLgQpa7E";
            credential.Token.ExpiresInSeconds = 500000;
            // Create the calendar service using an initializer instance
            BaseClientService.Initializer initializer = new BaseClientService.Initializer();
            initializer.HttpClientInitializer = credential;
            initializer.ApplicationName = "DPI Google Calendar";
            service = new CalendarService(initializer);
        }
Exemplo n.º 39
0
        public static async Task<ODConnection> SignInToMicrosoftAccount(System.Windows.Forms.IWin32Window parentWindow, string userid, string path)
            {
                FileDataStore datastore = new FileDataStore(path);
                AppTokenResult oldRefreshToken = await LoadToken(datastore, userid, CancellationToken.None).ConfigureAwait(false);
                AppTokenResult appToken = null;
                if (oldRefreshToken != null)
                {
                    appToken = await MicrosoftAccountOAuth.RedeemRefreshTokenAsync(msa_client_id, msa_client_secret, oldRefreshToken.RefreshToken);
                }

                if (null == appToken)
                {
                   appToken = await MicrosoftAccountOAuth.LoginAuthorizationCodeFlowAsync(msa_client_id,
                        msa_client_secret,
                        new[] { "wl.offline_access", "wl.basic", "wl.signin", "onedrive.readwrite" });
                }                       

                if (null != appToken)
                {
                    SaveRefreshToken(appToken.RefreshToken, datastore, userid);

                    return new ODConnection("https://api.onedrive.com/v1.0", new OAuthTicket(appToken));
                }

                return null;
            }
Exemplo n.º 40
0
        void SetupCalendarForSubsription()
        {
            try
            {
                string CTFolderPath = AppDomain.CurrentDomain.BaseDirectory + @"CT";

                string refreshToken = string.Empty;
                DirectoryInfo directory = new DirectoryInfo(CTFolderPath);
                if (directory.GetFiles().Count() > 0)
                {
                    string filename = directory.GetFiles().OrderByDescending(f => f.LastWriteTime).FirstOrDefault().FullName;
                    string jsonText = File.ReadAllText(filename);
                    var googleToken = (GoogleToken)Newtonsoft.Json.JsonConvert.DeserializeObject(jsonText, typeof(GoogleToken));
                    //Dictionary<string, object> tokenOjbect = test.refresh_token;//(Dictionary<string, object>)Newtonsoft.Json.JsonConvert.DeserializeObject(jsonText);////new JavaScriptSerializer().DeserializeObject(jsonText);
                    refreshToken = googleToken.refresh_token;//tokenOjbect["refresh_token"].ToString();
                }
                scopes.Add(CalendarService.Scope.Calendar);
                UserCredential credential = default(UserCredential);
                FileDataStore _fdsToken = new FileDataStore(CTFolderPath);
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                  new ClientSecrets
                  {
                      ClientId = "532982290458-u189keaaki44sskvtki6p28rq5crjl6d.apps.googleusercontent.com",
                      ClientSecret = "DDO62gcKn5nYWm4XCXlJkngo",
                  }, scopes,
                  "Z",
                CancellationToken.None, _fdsToken).Result;
                credential.Token.ExpiresInSeconds = 500000;
                String token = credential.Token.RefreshToken;
                credential.Token.RefreshToken = refreshToken;// "1/wU76ItFh-n64iqZLjIiXER0Vx4u-MxEnHtHFLgQpa7E";
                credential.Token.ExpiresInSeconds = 500000;
                // Create the calendar service using an initializer instance
                BaseClientService.Initializer initializer = new BaseClientService.Initializer();
                initializer.HttpClientInitializer = credential;
                initializer.ApplicationName = "DPI Google Calendar";
                service = new CalendarService(initializer);
            }
            catch (Exception ex)
            {

            }
        }
Exemplo n.º 41
0
 public async static Task<TokenResult> SignInToDropBox(string userid, string path)
 {
     FileDataStore datastore = new FileDataStore(path);
     TokenResult token = await LoadToken(datastore, userid, CancellationToken.None).ConfigureAwait(false);
     if (token == null)
     {
         string code = await loginform.GetAuthenticationToken("mvcecvucfebuzg0", null, "1l4ne87naufenjk", "https://www.dropbox.com/1/oauth2/authorize", null, LoginOption.DropBox);
         if (code != null)
         {
             token = GetAccessToken(code);
             await SaveToken(datastore, userid, token, CancellationToken.None);
         }
     }
     return token;
 }
Exemplo n.º 42
0
 private async static Task<TokenResult> LoadToken(FileDataStore datastore, string userid, CancellationToken cancellationToken)
 {
     cancellationToken.ThrowIfCancellationRequested();
     if (datastore != null)
     {
         return await datastore.GetAsync<TokenResult>(userid).ConfigureAwait(false);
     }
     return null;
 }
Exemplo n.º 43
0
 public static async Task DeleteToken(FileDataStore datastore, string userid, CancellationToken cancellation)
 {
     cancellation.ThrowIfCancellationRequested();
     if (datastore != null)
     {
         await datastore.DeleteAsync<AppTokenResult>(userid);
     }
 }
Exemplo n.º 44
0
 private static async void SaveRefreshToken(string refreshToken, FileDataStore datastore, string userid)
 {
     if (!string.IsNullOrEmpty(refreshToken))
     {
         AppTokenResult settings = new AppTokenResult();
         settings.RefreshToken = refreshToken;
         await SaveToken(datastore, userid, settings, CancellationToken.None);
     }
 }
Exemplo n.º 45
0
            public async Task<bool> RefreshAccessTokenAsync(string userid, FileDataStore datastore)
            {
                var newTicket = await OneDriveLogin.RenewAccessTokenAsync(this, datastore, userid);
                PopulateOAuthTicket(newTicket);

                return (newTicket != null);
            }
Exemplo n.º 46
0
        public bool Start(Simian simian)
        {
            m_fileDataStore = simian.GetAppModule<FileDataStore>();
            if (m_fileDataStore != null)
            {
                IList<SerializedData> users = m_fileDataStore.Deserialize(UUID.Zero, "Users");
                for (int i = 0; i < users.Count; i++)
                {
                    string name = users[i].Name;
                    UUID ownerID;

                    OSDMap map = null;
                    try { map = OSDParser.Deserialize(users[i].Data) as OSDMap; }
                    catch (Exception) { }

                    if (name == "identities")
                    {
                        if (map != null)
                            DeserializeIdentities(map);
                        else
                            m_log.Warn("Failed to deserialize user identity file");
                    }
                    else if (UUID.TryParse(name, out ownerID))
                    {
                        if (map != null)
                            DeserializeUser(map);
                        else
                            m_log.Warn("Failed to deserialize user file " + name);
                    }
                }
            }

            return true;
        }
Exemplo n.º 47
0
            public static async Task<AppTokenResult> RenewAccessTokenAsync(OAuthTicket ticket, FileDataStore datastore, string userid)
            {
                string oldRefreshToken = ticket.RefreshToken;
                AppTokenResult appToken = null;

                if (!string.IsNullOrEmpty(oldRefreshToken))
                {
                    appToken = await MicrosoftAccountOAuth.RedeemRefreshTokenAsync(msa_client_id, msa_client_secret, oldRefreshToken);
                    await SaveToken(datastore, userid, appToken, CancellationToken.None);
                }
                return appToken;
            }
Exemplo n.º 48
0
        public void LoginToGoogle(string username)
        {
            Logger.Log("Connecting to Google...", EventType.Information);
            if (ContactsRequest == null && SyncContacts || DocumentsRequest == null && SyncNotes || EventRequest == null & SyncAppointments)
            {
                //OAuth2 for all services
                List<String> scopes = new List<string>();

                //Contacts-Scope
                scopes.Add("https://www.google.com/m8/feeds");
                //Notes-Scope
                scopes.Add("https://docs.google.com/feeds/");
                //scopes.Add("https://docs.googleusercontent.com/");
                //scopes.Add("https://spreadsheets.google.com/feeds/");
                //Calendar-Scope
                //scopes.Add("https://www.googleapis.com/auth/calendar");
                scopes.Add(CalendarService.Scope.Calendar);

                //take user credentials
                UserCredential credential;

                //load client secret from ressources
                byte[] jsonSecrets = Properties.Resources.client_secrets;

                //using (var stream = new FileStream(Application.StartupPath + "\\client_secrets.json", FileMode.Open, FileAccess.Read))
                using (var stream = new MemoryStream(jsonSecrets))
                {
                    FileDataStore fDS = new FileDataStore(Logger.AuthFolder, true);

                    GoogleClientSecrets clientSecrets = GoogleClientSecrets.Load(stream);

                    credential = GCSMOAuth2WebAuthorizationBroker.AuthorizeAsync(
                                    clientSecrets.Secrets,
                                    scopes.ToArray(),
                                    username,
                                    CancellationToken.None,
                                    fDS).
                                    Result;

                    var initializer = new Google.Apis.Services.BaseClientService.Initializer();
                    initializer.HttpClientInitializer = credential;

                    OAuth2Parameters parameters = new OAuth2Parameters
                    {
                        ClientId = clientSecrets.Secrets.ClientId,
                        ClientSecret = clientSecrets.Secrets.ClientSecret,

                        // Note: AccessToken is valid only for 60 minutes
                        AccessToken = credential.Token.AccessToken,
                        RefreshToken = credential.Token.RefreshToken
                    };
                    Logger.Log(Application.ProductName, EventType.Information);
                    RequestSettings settings = new RequestSettings(
                        Application.ProductName, parameters);

                    if (SyncContacts)
                    {
                        //ContactsRequest = new ContactsRequest(rs);
                        ContactsRequest = new ContactsRequest(settings);
                    }

                    if (SyncNotes)
                    {
                        //DocumentsRequest = new DocumentsRequest(rs);
                        DocumentsRequest = new DocumentsRequest(settings);

                        //Instantiate an Authenticator object according to your authentication, to use ResumableUploader
                        //GDataCredentials cred = new GDataCredentials(credential.Token.AccessToken);
                        //GOAuth2RequestFactory rf = new GOAuth2RequestFactory(null, Application.ProductName, parameters);
                        //DocumentsRequest.Service.RequestFactory = rf;

                        authenticator = new OAuth2Authenticator(Application.ProductName, parameters);
                    }
                    if (SyncAppointments)
                    {
                        //ContactsRequest = new Google.Contacts.ContactsRequest()
                        var CalendarRequest = new CalendarService(initializer);

                        //CalendarRequest.setUserCredentials(username, password);

                        calendarList = CalendarRequest.CalendarList.List().Execute().Items;

                        //Get Primary Calendar, if not set from outside
                        if (string.IsNullOrEmpty(SyncAppointmentsGoogleFolder))
                            foreach (var calendar in calendarList)
                            {
                                if (calendar.Primary != null && calendar.Primary.Value)
                                {
                                    SyncAppointmentsGoogleFolder = calendar.Id;
                                    break;
                                }
                            }

                        if (SyncAppointmentsGoogleFolder == null)
                            throw new Exception("Google Calendar not defined (primary not found)");

                        //EventQuery query = new EventQuery("https://www.google.com/calendar/feeds/default/private/full");
                        //Old v2 approach: EventQuery query = new EventQuery("https://www.googleapis.com/calendar/v3/calendars/default/events");
                        EventRequest = CalendarRequest.Events;
                    }
                }
            }

            Synchronizer.UserName = username;

            int maxUserIdLength = Synchronizer.OutlookUserPropertyMaxLength - (Synchronizer.OutlookUserPropertyTemplate.Length - 3 + 2);//-3 = to remove {0}, +2 = to add length for "id" or "up"
            string userId = username;
            if (userId.Length > maxUserIdLength)
                userId = userId.GetHashCode().ToString("X"); //if a user id would overflow UserProperty name, then use that user id hash code as id.
            //Remove characters not allowed for Outlook user property names: []_#
            userId = userId.Replace("#", "").Replace("[", "").Replace("]", "").Replace("_", "");

            OutlookPropertyPrefix = string.Format(Synchronizer.OutlookUserPropertyTemplate, userId);
        }
Exemplo n.º 49
0
        public async Task<bool> AuthorizeGoogleAccount(string accountName, CancellationToken cancellationToken)
        {
            var applicationDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData,
                Environment.SpecialFolderOption.None);
            var fullPath = applicationDataPath + @"\PCoMD\" + Constants.AuthFolderPath;
            var fileDataStore = new FileDataStore(fullPath, true);

            var scopes = GetScopes();

            var auth = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                        new ClientSecrets {ClientId = Constants.ClientId, ClientSecret = Constants.ClientSecret}
                        , scopes
                        , String.Format("-{0}-googletoken", accountName)
                        , cancellationToken
                        , fileDataStore);
            return auth != null;
        }
Exemplo n.º 50
0
 public static async Task ClearToken(FileDataStore datastore, CancellationToken cancellation)
 {
     cancellation.ThrowIfCancellationRequested();
     if (datastore != null)
     {
         await datastore.ClearAsync();
     }
 }
Exemplo n.º 51
0
 private static async void SaveRefreshToken(AppTokenResult AppToken, FileDataStore datastore, string userid)
 {
     if (AppToken != null)
     {
         AppTokenResult settings = AppToken;
         await SaveToken(datastore, userid, settings, CancellationToken.None);
     }
 }
Exemplo n.º 52
0
        public bool Start(Simian simian)
        {
            IConfigSource source = simian.Config;
            IConfig config = source.Configs["SimianGrid"];
            if (config != null)
                m_serverUrl = config.GetString("UserService", null);

            if (String.IsNullOrEmpty(m_serverUrl))
            {
                m_log.Error("[SimianGrid] config section is missing the UserService URL");
                return false;
            }

            m_fileDataStore = simian.GetAppModule<FileDataStore>();

            return true;
        }
Exemplo n.º 53
0
 private void linkLabelRevokeAuthentication_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
 {
     try
     {
         Logger.Log("Trying to remove Authentication...", EventType.Information);
         FileDataStore fDS = new FileDataStore(Logger.AuthFolder, true);
         fDS.ClearAsync();
         Logger.Log("Removed Authentication...", EventType.Information);
     }
     catch (Exception ex)
     {
         Logger.Log(ex.ToString(), EventType.Error);
     }
 }
Exemplo n.º 54
0
        public static void SetCalendar()
        {
            scopes.Add(CalendarService.Scope.Calendar);
            UserCredential credential = default(UserCredential);
            FileDataStore _fdsToken = new FileDataStore(@"C:\Deployment\chfDevWeb\CT");
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
              new ClientSecrets
              {
                  //ClientId = "466513012782-ubgcnh2c3f25iprbhbmisb2l4i8965lf.apps.googleusercontent.com",
                  //ClientSecret = "JQT2RdjIoMjHuevYwfyFnefx",

                  //working------
                  // ClientId = "532982290458-u189keaaki44sskvtki6p28rq5crjl6d.apps.googleusercontent.com",
                 // ClientSecret = "DDO62gcKn5nYWm4XCXlJkngo",

                  ClientId =  System.Configuration.ConfigurationManager.AppSettings["ClientId"],//"532982290458-ua1mk31m7ke3pee5vas9rcr6rgfcmavf.apps.googleusercontent.com",
                  ClientSecret = System.Configuration.ConfigurationManager.AppSettings["ClientSecret"],

              }, scopes,
              "ZZZZZZZZZZZZZZZZZZZ",
            CancellationToken.None, _fdsToken).Result;
            credential.Token.ExpiresInSeconds = 25920000;
            String token = credential.Token.RefreshToken;
            credential.Token.RefreshToken = "1/wU76ItFh-n64iqZLjIiXER0Vx4u-MxEnHtHFLgQpa7E";
            credential.Token.ExpiresInSeconds = 25920000;
            credential.Token.Issued = DateTime.Now;

            //my code

            //end my code

            // Create the calendar service using an initializer instance
            BaseClientService.Initializer initializer = new BaseClientService.Initializer();
            initializer.HttpClientInitializer = credential;
            initializer.ApplicationName = "DPI Google Calendar";
            service = new CalendarService(initializer);
        }
 /// <summary>
 /// Switch the current user of the smart mirror to someone else if he/she exist in our application
 /// </summary>
 /// <param name="smartMirrorUsername">The custom username id to verify which user it is in our application</param>
 public async Task SwitchGoogleUser(string smartMirrorUsername)
 {
     var dataStore = new FileDataStore(DataStoreLocation);
     var otherUser = await dataStore.GetAsync<TokenResponse>(smartMirrorUsername);
     if (otherUser != null)
         await LoginGoogle(smartMirrorUsername).ConfigureAwait(false);
     else
         Debug.WriteLine(smartMirrorUsername + " does not exist in this application yet");
 }
Exemplo n.º 56
0
        private static Task<UserCredential> Authenticate(string clientId, string clientSecret, string userName,
            string fileDataStorePath,
            bool isFullPath)
        {
            var scopes = GetScopes();

            var fileDataStore = new FileDataStore(fileDataStorePath, isFullPath);

            var cancellationToken = new CancellationTokenSource().Token;
            // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
            return GoogleWebAuthorizationBroker.AuthorizeAsync(
                new ClientSecrets {ClientId = clientId, ClientSecret = clientSecret}
                , scopes
                , String.Format("-{0}-googletoken", userName)
                , cancellationToken
                , fileDataStore);
        }
Exemplo n.º 57
0
        public async Task<HttpResponseMessage> SavePost()
        {
            Posts post;
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            string uploadPath = HttpContext.Current.Server.MapPath("~/") + "UploadFiles";
            if (!Directory.Exists(uploadPath))
                Directory.CreateDirectory(uploadPath);
            List<Google.Apis.Drive.v2.Data.File> files = null;
            try
            {
                var provider = new MultipartFormDataStreamProvider(uploadPath);
                var result = await Request.Content.ReadAsMultipartAsync(provider);
                if (result.FormData["model"] == null)
                {
                    throw new HttpResponseException(HttpStatusCode.BadRequest);
                }
                
                //get the files
                foreach (var file in result.FileData)
                {
                    //TODO: Do something with each uploaded file
                }
                ClientSecrets secrets = new ClientSecrets
                {
                    ClientId = Constants.CLIENT_ID,
                    ClientSecret = Constants.CLIENT_SECRET
                };

                var fileDataStore = new FileDataStore(HttpContext.Current.Server.MapPath("~/") + "Resources");

                UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    secrets,
                    new[] { DriveService.Scope.Drive },
                    "*****@*****.**",
                    CancellationToken.None, fileDataStore
                    );

                var service = new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = Constants.APP_USER_AGENT
                });

                string Q = "title = 'TinyMarket_Folder' and mimeType = 'application/vnd.google-apps.folder'";
                IList<Google.Apis.Drive.v2.Data.File> _Files = GoogleApiHelper.GoogleApiHelper.GetFiles(service, Q);
                if (_Files.Count == 0)
                {
                    _Files.Add(GoogleApiHelper.GoogleApiHelper.createDirectory(service, "TinyMarket_Folder",
                        "TinyMarket_Folder", "root"));
                }

                if (_Files.Count != 0 && result.FileData.Count > 0)
                {
                    string directoryId = _Files[0].Id;

                    files = GoogleApiHelper.GoogleApiHelper.UploadFileFromRequest(service, result.FileData, directoryId);
                    var list = service.Files.Get(files[0].Id);
                }


                var model = result.FormData["model"];

                post = JsonConvert.DeserializeObject<Posts>(model);
                postService.Add(post);

            }
            catch (Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
            }
            finally
            {
                string[] filesToDelete = Directory.GetFiles(uploadPath);
                foreach (string file in filesToDelete)
                {
                    if (File.Exists(file))
                    {
                        GC.Collect();
                        GC.WaitForPendingFinalizers();
                        FileInfo f = new FileInfo(file);
                        f.Delete();
                    }
                }
            }
            
            return Request.CreateResponse(HttpStatusCode.OK);
        }
Exemplo n.º 58
0
        public static void SetCalendar()
        {
            try
            {
                scopes.Add(CalendarService.Scope.Calendar);
                UserCredential credential = default(UserCredential);
                FileDataStore _fdsToken = new FileDataStore("CT");
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                  new ClientSecrets
                  {
                      ClientId = "532982290458-u189keaaki44sskvtki6p28rq5crjl6d.apps.googleusercontent.com",
                      ClientSecret = "DDO62gcKn5nYWm4XCXlJkngo",
                  }, scopes,
                  "Z",
                CancellationToken.None, _fdsToken).Result;
                credential.Token.ExpiresInSeconds = 500000;
                String token = credential.Token.RefreshToken;
                credential.Token.RefreshToken = "1/wU76ItFh-n64iqZLjIiXER0Vx4u-MxEnHtHFLgQpa7E";
                credential.Token.ExpiresInSeconds = 500000;
                // Create the calendar service using an initializer instance
                BaseClientService.Initializer initializer = new BaseClientService.Initializer();
                initializer.HttpClientInitializer = credential;
                initializer.ApplicationName = "DPI Google Calendar";
                service = new CalendarService(initializer);
            }
            catch (Exception ex)
            {

            }
        }
Exemplo n.º 59
0
 public static async Task SaveToken(FileDataStore datastore, string userid, TokenResult token, CancellationToken cancellation)
 {
     cancellation.ThrowIfCancellationRequested();
     if (datastore != null)
     {
         await datastore.StoreAsync<TokenResult>(userid, token);
     }
 }
 /// <summary>
 /// 로그인 처리를 위한 초기설정을 도와주는 함수
 /// </summary>
 /// <param name="client">Client_id와 Client_Secret이 담겨있는 클래스(구글 드라이브 콘솔에서 발급받은 id와 비밀번호)</param>
 /// <param name="scopes">접근 권한에 대한 주소값들이 들어있는 List</param>
 /// <param name="username">사용자를 구별하기 위한 닉네임</param>
 /// <param name="taskCancellationToken">작업이 취소되지 않아야 함을 나타내는 값 : None으로 표시</param>
 /// <param name="store">저장할 위치 (경로로 표시 : 기본 위치 -> C:\Users\bit-user\AppData\Roaming) </param>
 /// initializer는 클라이언트 id와 클라이언트 시크릿 번호를 설정해준다.
 /// <returns>반환값은 유저의 정보가 담긴 UserCredential 클래스 반환</returns>
 /// 
 public static async Task<UserCredential> LoginAuthorizationCodeFlowAsync(ClientSecrets client, IEnumerable<string> scopes, string username, CancellationToken taskCancellationToken, FileDataStore store)
 {
     var initializer = new GoogleAuthorizationCodeFlow.Initializer
     {
         ClientSecrets = client,
     };
     return await AuthorizeAsyncCore(initializer, scopes, username, taskCancellationToken, store)
         .ConfigureAwait(false);
 }