예제 #1
0
    def get(self):
        # this must be a client ie subclass of GDClient, since that's what
        # OAuth2TokenFromCredentials.authorize() expects, *not* a service ie
        # subclass of GDataService.
        blogger = client.BloggerClient()
        auth_token = gauth.OAuth2TokenFromCredentials(oauth.credentials)
        auth_token.authorize(blogger)

        # get the current user
        blogs = blogger.get_blogs()
        logging.debug('Got blogs: %r' % str(blogs))
        owner_name = blogs.entry[0].author[0].name.text if blogs.entry else None
        hostnames = []
        for entry in blogs.entry:
            for link in entry.link:
                if link.type == 'text/html':
                    domain = util.domain_from_link(link.href)
                    if domain:
                        hostnames.append(domain)
                        break

        # redirect so that refreshing the page doesn't try to regenerate the oauth
        # token, which won't work.
        self.redirect('/?' + urllib.urlencode(
            {
                'blogger_owner_name': owner_name,
                'blogger_hostnames': hostnames,
            }, True))
예제 #2
0
  def api_from_creds(oauth2_creds):
    """Returns a gdata.blogger.client.BloggerClient.

    Args:
      oauth2_creds: OAuth2Credentials
    """
    # this must be a client ie subclass of GDClient, since that's what
    # OAuth2TokenFromCredentials.authorize() expects, *not* a service ie
    # subclass of GDataService.
    blogger = client.BloggerClient()
    gauth.OAuth2TokenFromCredentials(oauth2_creds).authorize(blogger)
    return blogger
예제 #3
0
def init_ss_client(client_secrets_filename):
    global ss_client
    if not ss_client:
        storage = Storage('creds.dat')
        credentials = storage.get()
        if credentials is None or credentials.invalid:
              credentials = run(
                  flow_from_clientsecrets(
                      client_secrets_filename,
                      scope=['https://spreadsheets.google.com/feeds']),
                      storage)

        ss_client = ss_service.SpreadsheetsService(
            additional_headers={'Authorization': 'Bearer %s' % credentials.access_token})
        ss_client.auth_token = gauth.OAuth2TokenFromCredentials(credentials)
        ss_client.source = 'Update Script'
        ss_client.ProgrammaticLogin()
예제 #4
0
    def __init__(self, account):

        # noinspection PyUnresolvedReferences
        def delegate():
            """
            Function to access as another account using server-side credentials.
            :return: Boolean, True if successful.
            """
            try:
                self.dc = self.credentials.create_delegated(self.account)
                return True
            except Exception as e:
                logger.exception("Unexpected error when trying to get permission to access this account")
                return False

        # noinspection PyUnresolvedReferences
        def validate():
            """
            Function to validate your server-side credentials, generating an access token.
            :return: Boolean, True if successful.
            """
            is_ok = False
            self.credentials = ServiceAccountCredentials.from_json_keyfile_name(self.json, scopes=self.scopes)
            try:
                if not self.credentials:
                    logger.error('Problem when trying to validate your credentials.')
                elif self.credentials.invalid:
                    logger.error("Access denied, invalid credentials")
                else:
                    is_ok = True
                return is_ok
            except:
                logger.exception("Problem when trying to validate your credentials.")
                return is_ok

        self.credentials = None
        self.calendar_list = None
        self.dc = None
        # Load Google credentials
        self.json = 'credentials/google.json'

        # Load all the Application Scope used to handle Calendar and Contacts
        self.scopes = ['https://www.googleapis.com/auth/calendar',
                       'https://www.googleapis.com/auth/contacts',
                       'https://www.google.com/m8/feeds/',
                       'https://www.googleapis.com/auth/admin.directory.user',
                       'https://www.googleapis.com/auth/admin.directory.orgunit.readonly',
                       'https://www.googleapis.com/auth/admin.directory.orgunit',
                       'https://www.googleapis.com/auth/apps.groups.migration',
                       'https://www.googleapis.com/auth/gmail.insert',
                       'https://www.googleapis.com/auth/gmail.labels',
                       'https://mail.google.com/',
                       'https://www.googleapis.com/auth/gmail.modify']

        # Stores the User Account
        self.account = str(account)

        # ERROR CODE FOR LOGGING
        self.error_code = {'delegate': '[' + self.account + '][DELEGATE] ',
                           'validate': '[' + self.account + '][VALIDATE] ',
                           'create_cal': '[' + self.account + '][CREATE_CALENDAR] ',
                           'rem_cal': '[' + self.account + '][REMOVE_CALENDAR] ',
                           'list_cals': '[' + self.account + '][LIST_CALENDARS] ',
                           'create_evt': '[' + self.account + '][CREATE_EVENT] ',
                           'g_events': '[' + self.account + '][GET_EVENTS] ',
                           'g_cts': '[' + self.account + '][GET_CONTACTS] ',
                           'rem_ct': '[' + self.account + '][REMOVE_CONTACT] ',
                           'create_ct': '[' + self.account + '][CREATE_CONTACT] ',
                           'list_cts': '[' + self.account + '][LIST_CONTACTS] ',
                           'create_grp': '[' + self.account + '][CREATE_GROUP] ',
                           'list_grp': '[' + self.account + '][LIST_GROUPS] ',
                           'rem_grp': '[' + self.account + '][REMOVE_GROUP] ',
                           'format_ct': '[' + self.account + '][FORMAT_CONTACT] ',
                           'format_evt': '[' + self.account + '][FORMAT_EVENT] ',
                           'convert_dlist': '[' + self.account + '][CONVERT_DLIST] ',
                           'br_grps': '[' + self.account + '][BATCH_REMOVE_GROUPS] ',
                           'br_cts': '[' + self.account + '][BATCH_REMOVE_CONTACTS] ',
                           'br_cals': '[' + self.account + '][BATCH_REMOVE_CALENDARS] ',
                           'br_evts': '[' + self.account + '][BATCH_REMOVE_EVENTS] ',
                           'bi_grps': '[' + self.account + '][BATCH_INSERT_GROUPS] ',
                           'bi_cts': '[' + self.account + '][BATCH_INSERT_CONTACTS] ',
                           'bi_cals': '[' + self.account + '][BATCH_INSERT_CALENDARS] ',
                           'bi_evts': '[' + self.account + '][BATCH_INSERT_EVENTS] ',
                           'usr_update': '[' + self.account + '][USER_UPDATE] ',
                           'list_orgs': '[' + self.account + '][LIST_ORGANIZATIONS] ',
                           'user_info': '[' + self.account + '][USER_INFO] ',
                           'clean_prim': '[' + self.account + '][CLEAN_PRIMARY_CAL] ',
                           'ins_msg': '[' + self.account + '][INSERT_MESSAGE] ',
                           'gmail_info': '[' + self.account + '][GMAIL_INFO] ',
                           'gmail_conn': '[' + self.account + '][GMAIL_CONN] ',
                           'gmail_senders': '[' + self.account + '][GMAIL_SENDERS] ',
                           }

        self.is_ok = True

        # If has access to Google API
        if validate():
            # To access this account we need to delegate access using Google API
            if delegate():
                try:
                    # Calendar Token
                    self._service_calendar = build('calendar', 'v3', http=self.dc.authorize(Http()), cache_discovery=False)

                    # Contacts Token
                    self.service_contacs = ContactsClient(source='contacts_handler')
                    self.auth_token = gauth.OAuth2TokenFromCredentials(self.dc)
                    self.auth_token.authorize(self.service_contacs)
                    self.feed = ''
                except:
                    logger.exception('Problem when trying to access ' + self.account + ' account, check it in the logs later.')

            else:
                print ('Problem when trying to access ' + self.account + ' account, check it in the logs later.')
                self.is_ok = False
        else:
            print ('Problem when trying to validate your credentials, check it in the logs later.')
            self.is_ok = False