Exemple #1
0
        private void frmJunoSistema_Load(object sender, EventArgs e)
        {
            timer1.Enabled = true;

            if (JunoSystem.Properties.Settings.Default.GoogleDriveOption != "")
            {
                LGoogleDriveOption = JunoSystem.Properties.Settings.Default.GoogleDriveOption.ToString();
            }

            if (LGoogleDriveOption != "0")
            {
                ServiceDriveAPI objDriveApi = new ServiceDriveAPI();

                //Seach Credenciais
                LCredenciais = objDriveApi.Autenticar();

                //OpenService
                LServico = objDriveApi.AbrirServico(LCredenciais);

                if (LCredenciais == null || LServico == null)
                {
                    lblStatus.Text = "Connected";
                }
            }
        }
Exemple #2
0
        private void frmInicio_Load(object sender, EventArgs e)
        {
            try
            {
                //Buscar Credenciais
                LCredenciais = objNegocioBackup.Autenticar();

                //AbreServiço
                LServico = objNegocioBackup.AbrirServico(LCredenciais);



                if (LCredenciais == null)
                {
                    lblStatus.Text = "Close";
                    return;
                }

                if (LServico == null)
                {
                    lblStatus.Text = "Close";
                    return;
                }

                lblStatus.Text = "Open";
            }
            catch (Exception)
            {
                MessageBox.Show("Erro ao conectar a api do Google Drive", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                lblStatus.Text = "Close";
                return;
            }
        }
        /// <summary>
        /// Loads the calendars from the google account.
        /// </summary>
        /// <returns>A list of calendars</returns>
        public async Task <IEnumerable <Entity.Calendar> > LoadCalendars()
        {
            this.logger.LogInformation("Load google calendars");
            Google.Apis.Auth.OAuth2.UserCredential credential = await this.googleRepository.Authorize();

            return(this.googleRepository.RetrieveCalendars(credential));
        }
 private static Google.Apis.Drive.v3.DriveService OpenService(Google.Apis.Auth.OAuth2.UserCredential credential)
 {
     return(new Google.Apis.Drive.v3.DriveService(new Google.Apis.Services.BaseClientService.Initializer()
     {
         HttpClientInitializer = credential
     }));
 }
        private async Task RevokeToken(string userId)
        {
            var typeName = typeof(TokenResponse).FullName;

            var context = this.DbContext;
            var tokens = await context.GoogleAuthData
                .Where(o => o.UserId == userId && o.Type == typeName)
                .ToArrayAsync();

            foreach (var item in tokens)
            {
                try
                {
                    var token = JsonConvert.DeserializeObject<TokenResponse>(item.Value);
                    var flow = GmailApiComponent.CreateFlow(userId);
                    var userCredential = new Google.Apis.Auth.OAuth2.UserCredential(flow, userId, token);

                    //Refresh the access token so we can promptly destroy it.
                    await userCredential.RefreshTokenAsync(CancellationToken.None);
                    await userCredential.RevokeTokenAsync(CancellationToken.None);
                }
                catch
                {
                    //TODO: Logging!
                }
            }
        }
        private async Task RevokeToken(string userId)
        {
            var typeName = typeof(TokenResponse).FullName;

            var context = this.DbContext;
            var tokens  = await context.GoogleAuthData
                          .Where(o => o.UserId == userId && o.Type == typeName)
                          .ToArrayAsync();

            foreach (var item in tokens)
            {
                try
                {
                    var token          = JsonConvert.DeserializeObject <TokenResponse>(item.Value);
                    var flow           = GmailApiComponent.CreateFlow(userId);
                    var userCredential = new Google.Apis.Auth.OAuth2.UserCredential(flow, userId, token);

                    //Refresh the access token so we can promptly destroy it.
                    await userCredential.RefreshTokenAsync(CancellationToken.None);

                    await userCredential.RevokeTokenAsync(CancellationToken.None);
                }
                catch
                {
                    //TODO: Logging!
                }
            }
        }
Exemple #7
0
 /// <summary>
 /// Abre serviço para comunicação com API google Drive
 /// </summary>
 /// <param name="credenciais"></param>
 /// <returns></returns>
 public Google.Apis.Drive.v3.DriveService AbrirServico(Google.Apis.Auth.OAuth2.UserCredential credenciais)
 {
     msgErro = "";
     return(new Google.Apis.Drive.v3.DriveService(new Google.Apis.Services.BaseClientService.Initializer()
     {
         HttpClientInitializer = credenciais
     }));
 }
        public bool InitCalendarService(string user)
        {
            try
            {
                // obtain the user's credentials
                Google.Apis.Auth.OAuth2.UserCredential user_credential =
                    Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.AuthorizeAsync(
                        new Google.Apis.Auth.OAuth2.ClientSecrets
                {
                    ClientId     = "857287834886-tau9nuakoamjctkm3plbqeojjrlmn140.apps.googleusercontent.com",
                    ClientSecret = "Gb5q1srU74At1erFyLQBKxXm"
                },
                        new [] { Google.Apis.Calendar.v3.CalendarService.Scope.Calendar },
                        user,
                        System.Threading.CancellationToken.None).Result;

                if (user_credential != null)
                {
                    // init the calendar service
                    service =
                        new Google.Apis.Calendar.v3.CalendarService(
                            new Google.Apis.Services.BaseClientService.Initializer()
                    {
                        HttpClientInitializer = user_credential,
                        ApplicationName       = "GoogleOutlookCalendarSync"
                    });

                    // save the refresh token
                    // this is not needed anymore, as the optional data store is a file store located
                    // at Google.Apis.Auth under the user's Environment.SpecialFolder.ApplicationData
                    // keep this for backwards compatibility, as it may be needed in the future
                    Settings.Instance.RefreshToken = user_credential.Token.RefreshToken;

                    // export the settings to keep backwards compatibility
                    XMLManager.export(Settings.Instance, MainForm.FILENAME);
                }
            }
            catch (System.Exception)
            {
                // something went very wrong so the service is dead
                service = null;
            }

            // indicate if the service was initialized
            return(service != null ? true : false);
        }
 public void ClearRefreshToken()
 {
     try
     {
       //Delete Browser cookies
       DeleteDirectoryContents(Environment.GetFolderPath(Environment.SpecialFolder.Cookies));
       //Delete Token
       DeleteDirectoryContents(_fileDataStore.FolderPath);
       //Clean User Credentials
       _userCredential = null;
       //Clean LoggedUser
       Settings.LoggedUser = String.Empty;
     }
     catch (Exception exception)
     {
       Log.Error(exception, false, false);
     }
 }
 public void ClearRefreshToken()
 {
     try
     {
         //Delete Browser cookies
         DeleteDirectoryContents(Environment.GetFolderPath(Environment.SpecialFolder.Cookies));
         //Delete Token
         DeleteDirectoryContents(_fileDataStore.FolderPath);
         //Clean User Credentials
         _userCredential = null;
         //Clean LoggedUser
         Settings.LoggedUser = String.Empty;
     }
     catch (Exception exception)
     {
         Log.Error(exception, false, false);
     }
 }
        public bool ValidateCredential()
        {
            var res = true;

            try
            {
                Google.Apis.Auth.OAuth2.UserCredential credential =
                    Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.AuthorizeAsync(
                        new Google.Apis.Auth.OAuth2.ClientSecrets
                {
                    ClientId     = googleDriverParam.ClientId,
                    ClientSecret = googleDriverParam.ClientSecret,
                },
                        new[] { Google.Apis.Drive.v3.DriveService.Scope.Drive },
                        "user",
                        System.Threading.CancellationToken.None).Result;

                userCredential = credential;

                var service = new Google.Apis.Drive.v3.DriveService(new Google.Apis.Services.BaseClientService.Initializer()
                {
                    HttpClientInitializer = userCredential,
                    ApplicationName       = googleDriverParam.ApplicationName
                });

                driveService = service;
                Validated    = true;
            }
            catch (Exception e)
            {
                Validated         = false;
                ValidationMessage = e.Message;
                res = false;
            }
            finally
            {
            }

            return(res);
        }
Exemple #12
0
        private async void RunAuthentication()
        {
            try
            {
                Google.Apis.Auth.OAuth2.UserCredential credential = await Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.AuthorizeAsync(new Google.Apis.Auth.OAuth2.ClientSecrets
                {
                    ClientId     = "957928808020-pa0lopl3crh565k6jd4djaj36rm1d9i5.apps.googleusercontent.com",
                    ClientSecret = "oB9U6yWFndnBqLKIRSA0nYGm"
                }, new[] { Google.Apis.YouTube.v3.YouTubeService.Scope.Youtube, Google.Apis.Oauth2.v2.Oauth2Service.Scope.UserinfoProfile }, "user", System.Threading.CancellationToken.None);
            }
            catch (Exception ex)
            {
                Log.Error("Authentication did not complete successfully.");
                Log.Error(ex.Message);
            }

            if (await YoutubeItemMethodsStatic.IsUserAuthenticated())
            {
                btnLogin.Visibility    = Visibility.Collapsed;
                btnContinue.Visibility = Visibility.Visible;
            }
        }
            public Google.Apis.Drive.v2.DriveService Init(string applicationName,
                                                    string clientIdentifier,
                                                    string clientSecret,
                                                    string[] scope,
                                                    bool logout,
                                                    string refreshTokenFolder)
            {
                StatusForm.ShowDialog();

                try
                {
                  _refreshTokenFilePath = refreshTokenFolder;

                  string fileDataStorePath = _refreshTokenFilePath;
                  if (FileExists(fileDataStorePath))
                  {
                DateTime lastFileWriteTime = GetFileLastWriteTime(fileDataStorePath);

                if (lastFileWriteTime < new DateTime(2014, 8, 22))
                {
                  DeleteFile(fileDataStorePath);
                }
                  }

                  if (logout)
                  {
                try
                {
                  if (DirectoryExists(fileDataStorePath))
                  {
                string[] fileDataStoreFiles = System.IO.Directory.GetFiles(fileDataStorePath,
                                                                           "Google.Apis.Auth.OAuth2.Responses.*");

                foreach (string fileDataStoreFile in fileDataStoreFiles)
                {
                  DeleteFile(fileDataStoreFile);
                }
                  }

                  LoginForm.Logout();
                }
                catch (Exception exception)
                {
                  Log.Error(String.Format("Authenticator.Logout - Deleting token file. {0}",exception.Message));
                }
                  }

                  var clientSecrets = new Google.Apis.Auth.OAuth2.ClientSecrets
                  {
                ClientId = clientIdentifier,
                ClientSecret = clientSecret
                  };

                  _fileDataStore = new EncryptedFileDataStore(refreshTokenFolder);

                  System.Threading.Tasks.Task<Google.Apis.Auth.OAuth2.UserCredential> task = null;

                  try
                  {
                task = Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.AuthorizeAsync(
                                                                                       clientSecrets,
                                                                                       scope,
                                                                                       System.Environment.UserName,
                                                                                       System.Threading.CancellationToken.None,
                                                                                       _fileDataStore);

                task.Wait();
                  }
                  catch (Exception exception)
                  {
                throw new LogException("GoogleWebAuthorizationBroker.AuthorizeAsync - " + exception.Message, false, false);
                  }

                  _userCredential = task.Result;

                  var initializer = new BaseClientService.Initializer
                  {
                HttpClientInitializer = _userCredential,
                ApplicationName = applicationName
                  };

                  _driveService = new Google.Apis.Drive.v2.DriveService(initializer);

                  UpdateAboutData(_driveService);

                  return _driveService;
                }
                catch (Exception exception)
                {
                  Log.Error(exception);

                  return null;
                }
                finally
                {
                  StatusForm.CloseDialog();
                }
            }
 public frmVisualizarArquivos(Google.Apis.Auth.OAuth2.UserCredential inCredenciais, Google.Apis.Drive.v3.DriveService inServico)
 {
     InitializeComponent();
     LCredenciais = inCredenciais;
     LServico     = inServico;
 }
            public Google.Apis.Drive.v2.DriveService Init(string applicationName,
                                                          string clientIdentifier,
                                                          string clientSecret,
                                                          string[] scope,
                                                          bool logout,
                                                          string refreshTokenFolder)
            {
                StatusForm.ShowDialog();

                try
                {
                    _refreshTokenFilePath = refreshTokenFolder;

                    string fileDataStorePath = _refreshTokenFilePath;
                    if (FileExists(fileDataStorePath))
                    {
                        DateTime lastFileWriteTime = GetFileLastWriteTime(fileDataStorePath);

                        if (lastFileWriteTime < new DateTime(2014, 8, 22))
                        {
                            DeleteFile(fileDataStorePath);
                        }
                    }

                    if (logout)
                    {
                        try
                        {
                            if (DirectoryExists(fileDataStorePath))
                            {
                                string[] fileDataStoreFiles = System.IO.Directory.GetFiles(fileDataStorePath,
                                                                                           "Google.Apis.Auth.OAuth2.Responses.*");

                                foreach (string fileDataStoreFile in fileDataStoreFiles)
                                {
                                    DeleteFile(fileDataStoreFile);
                                }
                            }

                            LoginForm.Logout();
                        }
                        catch (Exception exception)
                        {
                            Log.Error(String.Format("Authenticator.Logout - Deleting token file. {0}", exception.Message));
                        }
                    }

                    var clientSecrets = new Google.Apis.Auth.OAuth2.ClientSecrets
                    {
                        ClientId     = clientIdentifier,
                        ClientSecret = clientSecret
                    };

                    _fileDataStore = new EncryptedFileDataStore(refreshTokenFolder);

                    System.Threading.Tasks.Task <Google.Apis.Auth.OAuth2.UserCredential> task = null;

                    try
                    {
                        task = Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.AuthorizeAsync(
                            clientSecrets,
                            scope,
                            System.Environment.UserName,
                            System.Threading.CancellationToken.None,
                            _fileDataStore);

                        task.Wait();
                    }
                    catch (Exception exception)
                    {
                        throw new LogException("GoogleWebAuthorizationBroker.AuthorizeAsync - " + exception.Message, false, false);
                    }

                    _userCredential = task.Result;

                    var initializer = new BaseClientService.Initializer
                    {
                        HttpClientInitializer = _userCredential,
                        ApplicationName       = applicationName
                    };

                    _driveService = new Google.Apis.Drive.v2.DriveService(initializer);

                    UpdateAboutData(_driveService);

                    return(_driveService);
                }
                catch (Exception exception)
                {
                    Log.Error(exception);

                    return(null);
                }
                finally
                {
                    StatusForm.CloseDialog();
                }
            }