import sys
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run
import httplib2

FLOW = OAuth2WebServerFlow(client_id='xxxxxxx.apps.googleusercontent.com',
                           client_secret='shhhhhhhhhhhh',
                           scope='https://www.googleapis.com/auth/bigquery',
                           user_agent='my-program-name/1.0')


def exportTable(http, service):
    projectId = raw_input("Choose your project ID: ")
    datasetId = raw_input("Choose a dataset ID: ")
    tableId = raw_input("Choose a table name to copy: ")

    jobCollection = service.jobs()
    # [START job_data]
    jobData = {
        'projectId': projectId,
        'configuration': {
            'extract': {
                'sourceTable': {
                    'projectId': projectId,
                    'datasetId': datasetId,
                    'tableId': tableId
                },
                'destinationUris': ['gs://<bucket>/<file>'],
            }
Example #2
0
from oauth2client.file import Storage
from oauth2client.client import AccessTokenRefreshError
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run

# For this example, the client id and client secret are command-line arguments.
client_id = sys.argv[1]
client_secret = sys.argv[2]

# The scope URL for read/write access to a user's calendar data
scope = 'https://www.googleapis.com/auth/calendar'

# Create a flow object. This object holds the client_id, client_secret, and
# scope. It assists with OAuth 2.0 steps to get user authorization and
# credentials.
flow = OAuth2WebServerFlow(client_id, client_secret, scope)


def main():

    # Create a Storage object. This object holds the credentials that your
    # application needs to authorize access to the user's data. The name of the
    # credentials file is provided. If the file does not exist, it is
    # created. This object can only hold credentials for a single user, so
    # as-written, this script can only handle a single user.
    storage = Storage('credentials.dat')

    # The get() function returns the credentials for the Storage object. If no
    # credentials were found, None is returned.
    credentials = storage.get()
Example #3
0
def gconnect():
    # Validate state token
    if request.args.get('state') != login_session['state']:
        response = make_response(json.dumps('Invalid state parameter.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response
    # Obtain authorization code
    request.get_data()
    code = request.data.decode('utf-8')

    try:
        # Upgrade the authorization code into a credentials object
        oauth_flow = OAuth2WebServerFlow(redirect_uri='postmessage',
                                         **google_web)
        credentials = oauth_flow.step2_exchange(code)
    except FlowExchangeError:
        response = make_response(
            json.dumps('Failed to upgrade the authorization code.'), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Check that the access token is valid.
    access_token = credentials.access_token
    url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s' %
           access_token)
    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])
    # If there was an error in the access token info, abort.
    if result.get('error') is not None:
        response = make_response(json.dumps(result.get('error')), 500)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is used for the intended user.
    gplus_id = credentials.id_token['sub']
    if result['user_id'] != gplus_id:
        response = make_response(
            json.dumps("Token's user ID doesn't match given user ID."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Verify that the access token is valid for this app.
    if result['issued_to'] != GOOGLE_CLIENT_ID:
        response = make_response(
            json.dumps("Token's client ID does not match app's."), 401)
        response.headers['Content-Type'] = 'application/json'
        return response

    # Store the access token in the session for later use.
    login_session['access_token'] = credentials.access_token
    login_session['gplus_id'] = gplus_id

    # Get user info
    userinfo_url = "https://www.googleapis.com/oauth2/v1/userinfo"
    params = {'access_token': credentials.access_token, 'alt': 'json'}
    answer = requests.get(userinfo_url, params=params)

    data = answer.json()

    login_session['username'] = data['name']
    login_session['picture'] = data['picture']
    login_session['email'] = data['email']
    # ADD PROVIDER TO LOGIN SESSION
    login_session['provider'] = 'google'

    # see if user exists, if it doesn't make a new one
    user_id = get_user_id(data["email"])
    if not user_id:
        user_id = create_user(login_session)
    login_session['user_id'] = user_id

    output = ''
    output += '<h1>Welcome, '
    output += login_session['username']
    output += '!</h1>'
    output += '<img src="'
    output += login_session['picture']
    output += ' " style = "width: 300px; height: 300px;border-radius: 150px;' \
              '-webkit-border-radius: 150px;-moz-border-radius: 150px;"> '
    flash("you are now logged in as %s" % login_session['username'])
    return output
Example #4
0
def handle(text, mic, speaker, profile, visionProcess):
    """
        Responds to user-input, typically speech text, by relaying the
        meaning of life.

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone
                   number)
    """
    # Set up a Flow object to be used if we need to authenticate. This
    # sample uses OAuth 2.0, and we set up the OAuth2WebServerFlow with
    # the information it needs to authenticate. Note that it is called
    # the Web Server Flow, but it can also handle the flow for
    # installed applications.
    #
    # Go to the Google API Console, open your application's
    # credentials page, and copy the client ID and client secret.
    # Then paste them into the following code.
    FLOW = OAuth2WebServerFlow(
        client_id='689072684284-jd32gjce45doer1vhrm049he4iqllmcr.apps.googleusercontent.com',
        client_secret='jY0GDTn9sUf1Ml8VynpWz1TR',
        scope='https://www.googleapis.com/auth/contacts.readonly',
        user_agent='Jasper-Mac')

    # If the Credentials don't exist or are invalid, run through the
    # installed application flow. The Storage object will ensure that,
    # if successful, the good Credentials will get written back to a
    # file.

    storage = Storage(
        jasperpath.USER_CREDENTIALS_PATH +
        '/contacts-permissions.dat')

    credentials = storage.get()
    if credentials is None or credentials.invalid:
        flags = tools.argparser.parse_args(args=[])
        credentials = tools.run_flow(FLOW, storage, flags)

    # Create an httplib2.Http object to handle our HTTP requests and
    # authorize it with our good Credentials.
    http = httplib2.Http()
    http = credentials.authorize(http)

    # Build a service object for interacting with the API. To get an API key for
    # your application, visit the Google API Console
    # and look at your application's credentials page.

    people_service = build(serviceName='people', version='v1', http=http)
    if bool(re.search(r'\bupdate contacts', text, re.IGNORECASE)):
        results = people_service.people().connections().list(
            resourceName='people/me',
            pageSize=500,
            requestMask_includeField='person.names,person.genders,person.emailAddresses,person.phoneNumbers,person.birthdays,person.addresses,person.urls,person.photos',
            sortOrder='FIRST_NAME_ASCENDING').execute()
        connection_list = results.get('connections', [])
        my_connections = []
        for person in connection_list:
            names = person.get('names', [])
            genders = person.get('genders', [])
            phone_numbers = person.get('phoneNumbers', [])
            email_addresses = person.get('emailAddresses', [])
            birthday = person.get('birthdays', [])
            addresses = person.get('addresses', [])
            urls = person.get('urls', [])
            photos = person.get('photos', [])

            contact = {}
            numbers = []
            emails = []
            address = {}
            birthdate = ''
            url = ''

            if len(names) > 0:
                name = names[0].get('displayName')
                contact['name'] = name

            if len(genders) > 0:
                gender = genders[0].get('value')
                contact['gender'] = gender

            if len(urls) > 0:
                url = urls[0].get('value')
                contact['url'] = url

            if len(birthday) > 0:
                birthdate = birthday[0].get('date')
                contact['birthdate'] = birthdate

            if len(addresses) > 0:
                address['formattedValue'] = addresses[0].get('formattedValue')
                address['country'] = addresses[0].get('country')
                address['city'] = addresses[0].get('city')
                address['streetAddress'] = addresses[0].get('streetAddress')
                address['postalCode'] = addresses[0].get('postalCode')
                contact['address'] = address

            for i in range(len(phone_numbers)):
                numbers.append(phone_numbers[i].get('value'))
            contact['numbers'] = numbers

            for i in range(len(email_addresses)):
                emails.append(email_addresses[i].get('value'))
            contact['emails'] = emails

            my_connections.append(contact)

        if my_connections is not None:
            rethinkdb_connector.insert_into_contacts(my_connections)
Example #5
0
from runtime_import.libs.GoogleAnalytics.util import GoogleAnalyticsDataYielder

# End of import statements
OAUTH_SAVE_URL = 'http://localhost:6346/sandbox?integration_key=GoogleAnalytics'
TOKEN_REQUEST_URL = 'https://accounts.google.com/o/oauth2/token'
SCOPE = ['https://www.googleapis.com/auth/analytics.readonly',
         'https://www.googleapis.com/auth/userinfo.profile',
         'https://www.googleapis.com/auth/userinfo.email']


         #'https://www.googleapis.com/auth/userinfo.email'+
         #'https://www.googleapis.com/auth/userinfo.profile')

flow = OAuth2WebServerFlow(
            client_id='768649915969-6gqqnebt6iq4cpnlq7i8hu9evph2fmq4.apps.googleusercontent.com',
            client_secret='BqLLypXr0lN5Pd_r_k25U9_k',
            scope=SCOPE,
            redirect_uri='https://redirect.mammoth.io/redirect/oauth2')

flow.params['access_type'] = const.ACCESS_TYPE
flow.params['prompt'] = const.PROMPT_TYPE



class GoogleAnalyticsManager(ThreePBase):
    """
    This is main class using which Mammoth framework interacts with third party API
    plugin (referred as API hereinafter). Various responsibilities of this class
    is to manage/update identities, ds_configs and few more interfaces to handle API logic

    """
def start(request):
    flow = OAuth2WebServerFlow(redirect_uri=request.build_absolute_uri(
        reverse("admin:admin_sso_assignment_end")),
                               **flow_kwargs)

    return HttpResponseRedirect(flow.step1_get_authorize_url())
CLIENT_SECRET = '93hZNZCHFlHHEjofB4KM-vZE'

OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'

# Redireccion de la app instalada.

REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'

# Ruta de los archivos a subir.

FILENAME = 'tweet_by_lang'
FILENAME1 = 'tweet_by_prg_language_1'

# Realiza el login accediendo a la URL que proporciona y comprobando el codigo de autorizacion introducido posteriormente.
flow = OAuth2WebServerFlow(CLIENT_ID,
                           CLIENT_SECRET,
                           OAUTH_SCOPE,
                           redirect_uri=REDIRECT_URI)
authorize_url = flow.step1_get_authorize_url()
print 'Go to the following link in your browser: ' + authorize_url
code = raw_input('Enter verification code: ').strip()
credentials = flow.step2_exchange(code)

# Crea un objeto "httplib2.Http" y lo autoriza con nuestras credenciales.

http = httplib2.Http()
http = credentials.authorize(http)

drive_service = build('drive', 'v2', http=http)

# Subida de archivos.
Example #8
0
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run

FLAGS = gflags.FLAGS

# Set up a Flow object to be used if we need to authenticate. This
# sample uses OAuth 2.0, and we set up the OAuth2WebServerFlow with
# the information it needs to authenticate. Note that it is called
# the Web Server Flow, but it can also handle the flow for native
# applications
# The client_id and client_secret can be found in Google Developers Console
FLOW = OAuth2WebServerFlow(
    client_id=
    '286518689990-houk6epk8mmpottb3o5ns6c7jfv4iqpq.apps.googleusercontent.com',
    client_secret='MMqETfGzjBk5bPWl7_74E8sK',
    scope='https://www.googleapis.com/auth/calendar',
    user_agent='SMART_ALARM_CLOCK/VER_1.0')

# To disable the local server feature, uncomment the following line:
FLAGS.auth_local_webserver = False

# If the Credentials don't exist or are invalid, run through the native client
# flow. The Storage object will ensure that if successful the good
# Credentials will get written back to a file.

# storage = Storage('calendar.dat')
# credentials = storage.get()
# if credentials is None or credentials.invalid == True:
# 	credentials = run(FLOW, storage)
Example #9
0
        r'https://www.google.com/calendar.*?src=(?P<cID>[0-9a-zA-Z].*?((%40)|@).*?\.com)'
    )

    try:
        calendarId = google_calendar_pattern.search(
            html).groupdict()['cID'].replace("%40", "@")
    except Exception, e:
        lib.print_error("fail to get calendar ID")
        print e
        lib.finish(args.name, args.url)

print "~~~~~~~calendarID:%s ~~~~~~~~~~" % calendarId

FLOW = OAuth2WebServerFlow(
    client_id=
    '154781234816-h5nmu0iuq3do0tsga33km22g2t0al0ru.apps.googleusercontent.com',
    client_secret='JRwb4_2ZXMe8iTf6t6GazJbD',
    scope='https://www.googleapis.com/auth/calendar.readonly',
    user_agent='test/0.1')

storage = Storage('../calendar.dat')
credentials = storage.get()
if credentials is None or credentials.invalid == True:
    credentials = run(FLOW, storage)

# Create an httplib2.Http object to handle our HTTP requests and authorize it
# with our good Credentials.
http = httplib2.Http()
http = credentials.authorize(http)

# Build a service object for interacting with the API. Visit
# the Google Developers Console
Example #10
0
def handle_bdate(token):
    spl = token.split(".")
    if len(spl) != 3:
        raise Exception("Wrong date format")
    else:
        day = spl[2] + "-" + spl[1] + "-" + spl[0]
        # todo: better date handling
        return day + "T00:00:00.000", day + "T23:59:00.000"


if __name__ == '__main__':

    FLOW = OAuth2WebServerFlow(
        client_id=client_id,
        client_secret=client_secret,
        scope='https://www.googleapis.com/auth/calendar',
        user_agent='calendar/v3')

    # If the Credentials don't exist or are invalid, run through the native client
    # flow. The Storage object will ensure that if successful the good
    # Credentials will get written back to a file.
    storage = Storage('calendar.dat')
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = run(FLOW, storage)

    http = httplib2.Http()
    http = credentials.authorize(http)

    # Visit the Google Developers Console
Example #11
0
def index():
    ####

    global lastCode
    global ignoreMistake

    #check whether logged in
    s = bottle.request.environ.get('beaker.session')
    #print s
    logInStatus = s.get('logInStatus', 0)
    LogInOffHtml = ''
    changePhotoHtml = ''
    userInfoHtml = '<div class="userInfo"><li style="font-size: 20px; font-weight: bold;" class="lang" key="hiStranger"> Hi Stranger!</li></div>'
    userImage = "static/images/anonymous.png"
    #s['']

    #if not logged in

    if logInStatus != 'loggedIn':
        accountName = '<span class="lang" key="signIn">Sign In</span>'
        mode = 'Anonymous'
        s['mode'] = mode
        LogInOffHtml = '<li class="divider"></li><li><a href="/account" class="lang btn-default btn btn-default" key="account"> Log In With Google </a></li>'
        s.save()
    else:
        user_document = s['userDocument']
        accountName = user_document['name']
        accountEmail = user_document['email']
        userImage = user_document['picture']
        changePhotoHtml = '<input id="file-input"  name="profilePhoto" type="file" style="display:none" onchange="javascript:this.form.submit()" accept="image/*" >'
        userInfoHtml = '<li style="font-size: 20px; font-weight: bold;">' + accountName + '</li>' + '<li>' + accountEmail + '</li> <li class="divider"></li>'
        LogInOffHtml = '<li><a href="/signOut" class="lang btn btn-default" key="signOut" > Sign Out </a></li>'

#process google login in
    code = request.query.get('code', '')
    if code and code != lastCode:
        lastCode = code
        flow = OAuth2WebServerFlow(
            client_id=
            '768721561947-cda1s6rph24pem3t6h4pa3e4016ua9rk.apps.googleusercontent.com',
            client_secret='PTU6hiaZ7CdOdthZurcYLVk6',
            scope=
            'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email',
            redirect_uri='http://localhost:8080/')
        credentials = flow.step2_exchange(code)
        token = credentials.id_token['sub']
        http = httplib2.Http()
        http = credentials.authorize(http)
        # Get user email
        users_service = build('oauth2', 'v2', http=http)
        user_document = users_service.userinfo().get().execute()
        #user_email = user_document['email']
        #print user_emailss
        accountName = user_document['name']
        accountEmail = user_document['email']
        logInStatus = 'loggedIn'
        s['logInStatus'] = logInStatus
        mode = 'Signed-In'
        s['mode'] = mode
        s['userDocument'] = user_document
        userImage = user_document['picture']
        changePhotoHtml = '<input id="file-input"  name="profilePhoto" type="file" style="display:none" onchange="javascript:this.form.submit()" accept="image/*" >'
        LogInOffHtml = '<li><a href="/signOut" class="lang btn btn-default" key="signOut" > Sign Out </a></li>'
        userInfoHtml = '<li style="font-size: 20px; font-weight: bold;">' + accountName + '</li>' + '<li>' + accountEmail + '</li> <li class="divider"></li>'
        s.save()

    #dictionary used to record keywordsS and number of appearance
    #first sort current history
    historyLen = len(fullSearchHistory)
    firstSortedHistory = OrderedDict(
        sorted(fullSearchHistory.iteritems(),
               key=operator.itemgetter(1),
               reverse=True)[:historyLen])
    dictionary = OrderedDict()
    inputString = request.query.get('keywords')
    pageString = request.query.get('page')
    tempIgnoreMistake = request.query.get('ignoreMistake')
    historyBarHtml = '<label for="imagenet-upload"> <li style="font-size: 19px; text-align:left;margin-left:4%" class="lang" key="searchImage">Search with Image </li></label>'
    resultHistoryBarHtml = '<label for="imagenet-upload"> <li style="font-size:13px; text-align:left;margin-left:4%" class="lang" key="searchImage">Search with Image </li></label>'
    if not pageString:
        page = 1
    else:
        page = int(pageString)
    if not tempIgnoreMistake and not pageString:
        ignoreMistake = 0
    if tempIgnoreMistake and not pageString:
        ignoreMistake = 1
    if not inputString:
        return template('index.tpl',
                        accountText=accountName,
                        LogInOffHtml=LogInOffHtml,
                        userInfoHtml=userInfoHtml,
                        userImage=userImage,
                        changePhotoHtml=changePhotoHtml,
                        historyBarHtml=historyBarHtml)

    tempString = inputString.lower()
    #get rid of space
    splitString = tempString.split()
    #if splitString is empty (i.e. input string only consists of space or is empty), redirect route to root
    if not splitString:
        return template('index.tpl',
                        accountText=accountName,
                        LogInOffHtml=LogInOffHtml,
                        userInfoHtml=userInfoHtml,
                        userImage=userImage,
                        changePhotoHtml=changePhotoHtml,
                        historyBarHtml=historyBarHtml)

    #parse query string
    firstKeyWord = inputString.split()[0]
    if not page or page == 1:
        pageStart = 0
        page = 1
    else:
        pageStart = (page - 1) * 5
    urlHtml, resultNumber = sh.searchKeyWord(firstKeyWord, inputString,
                                             pageStart, ignoreMistake)
    navUrl = sh.createPageNavs(resultNumber, page, inputString)
    if inputString in fullSearchHistory:
        fullSearchHistory[inputString] += 1
    else:
        fullSearchHistory[inputString] = 1

    for word in splitString:
        if logInStatus == 'loggedIn':
            recentSearchList.append(word)
        #if word already exits in dictionary, add one to its appearance
        if word in dictionary:
            dictionary[word] += 1
        else:
            #if word doesn't exist in dictionary, set one as its appearance
            dictionary[word] = 1
    for row in dictionary:
        if row in searchHistory:
            searchHistory[row] += dictionary[row]
        else:
            searchHistory[row] = 1
#store keywords in search history
#if logInStatus == 'loggedIn':
#for row in dictionary:
#      if row in searchHistory:
#          searchHistory[row] += dictionary[row]
#      else:
#          searchHistory[row] = 1


#get length of history
    historyLen = len(searchHistory)
    #if history length is less than 20, display all result in greatest first order
    if (historyLen < 20):
        sortedHistory = OrderedDict(
            sorted(searchHistory.iteritems(),
                   key=operator.itemgetter(1),
                   reverse=True)[:historyLen])
    else:
        #else display top 20 keywords in greatest first order
        sortedHistory = OrderedDict(
            sorted(searchHistory.iteritems(),
                   key=operator.itemgetter(1),
                   reverse=True)[:20])
    #now for recent search keywords
    reversedRecentSearch = recentSearchList[::-1]
    if len(reversedRecentSearch) < 15:
        mostRecentSearch = reversedRecentSearch
    else:
        mostRecentSearch = reversedRecentSearch[:15]
    return template('searchResultAnonymous.tpl',
                    dictionary=dictionary,
                    keywords=inputString,
                    history=sortedHistory,
                    accountText=accountName,
                    LogInOffHtml=LogInOffHtml,
                    userInfoHtml=userInfoHtml,
                    userImage=userImage,
                    changePhotoHtml=changePhotoHtml,
                    urlHtml=urlHtml,
                    resultNumber=resultNumber,
                    navUrl=navUrl,
                    historyBarHtml=resultHistoryBarHtml)
    if s['mode'] == 'Signed-In':
        return template('searchResultLoggedIn.tpl',
                        dictionary=dictionary,
                        keywords=inputString,
                        history=sortedHistory,
                        accountText=accountName,
                        LogInOffHtml=LogInOffHtml,
                        userInfoHtml=userInfoHtml,
                        userImage=userImage,
                        changePhotoHtml=changePhotoHtml,
                        mostRecentSearch=mostRecentSearch,
                        navUrl=navUrl)
    else:
        return template('searchResultAnonymous.tpl',
                        dictionary=dictionary,
                        keywords=inputString,
                        history=sortedHistory,
                        accountText=accountName,
                        LogInOffHtml=LogInOffHtml,
                        userInfoHtml=userInfoHtml,
                        userImage=userImage,
                        changePhotoHtml=changePhotoHtml,
                        urlHtml=urlHtml,
                        resultNumber=resultNumber,
                        navUrl=navUrl,
                        historyBarHtml=resultHistoryBarHtml)
Example #12
0
def get_flow(redirect_url=None):
  return OAuth2WebServerFlow(client_id=settings.GOOGLE_CLIENT_ID,
            client_secret=settings.GOOGLE_CLIENT_SECRET,
            scope='profile email',
            redirect_uri=redirect_url)
Example #13
0
from oauth2client.tools import run_flow, argparser
from config import client_id, client_secret, scope, user_agent, developerKey

FLAGS = gflags.FLAGS

logging.basicConfig()
#Auth section
# Set up a Flow object to be used if we need to authenticate. This
# sample uses OAuth 2.0, and we set up the OAuth2WebServerFlow with
# the information it needs to authenticate. Note that it is called
# the Web Server Flow, but it can also handle the flow for native
# applications
# The client_id and client_secret are copied from the API Access tab on
# the Google APIs Console
FLOW = OAuth2WebServerFlow(client_id=client_id,
                           client_secret=client_secret,
                           scope=scope,
                           user_agent=user_agent)

# To disable the local server feature, uncomment the following line:
# FLAGS.auth_local_webserver = False

# If the Credentials don't exist or are invalid, run through the native client
# flow. The Storage object will ensure that if successful the good
# Credentials will get written back to a file.
storage = Storage('calendar.dat')
credentials = storage.get()
if credentials is None or credentials.invalid == True:
    credentials = run_flow(FLOW, storage, argparser.parse_args([]))

# Create an httplib2.Http object to handle our HTTP requests and authorize it
# with our good Credentials.
Example #14
0
def event_post(request):
    REDIRECT_URI = "https://%s%s" % (request.get_host(),
                                     reverse("scheduler:post_event_return"))
    # FLOW = flow_from_clientsecrets(
    # 		CLIENT_SECRETS,
    # 		scope=SCOPES,
    # 		redirect_uri=REDIRECT_URI
    # 	)
    FLOW = OAuth2WebServerFlow(
        client_id=
        '323423619559-orlpuuiaalb7sp3ooblt4mjmp32ffq1t.apps.googleusercontent.com',
        client_secret=os.environ['CLIENT_SECRET'],
        scope=SCOPES,
        redirect_uri=REDIRECT_URI)
    user = request.user
    storage = Storage(CredentialsModel, 'id', user, 'credential')
    # credential = request.
    credential = storage.get()
    if credential is None or credential.invalid is True:
        FLOW.params['state'] = xsrfutil.generate_token(settings.SECRET_KEY,
                                                       user)
        authorize_url = FLOW.step1_get_authorize_url()
        f = FlowModel(id=user, flow=FLOW)
        f.save()
        return HttpResponseRedirect(authorize_url)
    else:

        http = httplib2.Http()
        http = credential.authorize(http)
        service = build('calendar', 'v3', http=http)
        data = request.data
        event = {
            'location': '5127 Sheridan Blvd, Broomfield, CO 80020',
            'start': {
                'timeZone': 'America/Denver',
            },
            'end': {
                'timeZone': 'America/Denver',
            },
        }
        if 'event_id' in data:
            event['summary'] = 'Event' + data['event_id']
        else:
            event['summary'] = 'Event w/o ID'
        if 'description' in data:
            event['description'] = data['description']
        else:
            event['summary'] = 'Test for event w/o ID'

        #MANDATORY ARGUMENT
        if 'start_datetime' in data:
            event['start']['dateTime'] = data['start_datetime']
        else:
            event['start']['dateTime'] = '2016-05-28T20:00:00-07:00'
        #MANDATORY ARGUMENT
        if 'end_datetime' in data:
            event['end']['dateTime'] = data['end_datetime']
        else:
            event['end'][
                'dateTime'] = '2016-05-28T21:00:00-07:00'  #str(datetime.datetime.now() + datetime.timedelta(hours=1))#str(timezone.now() +timezone.timedelta(hours=1))#'2016-05-28T14:00:00-07:00'

        if 'recurrence' in data:
            event['recurrence'] = data['recurrence']
        else:
            event['recurrence'] = 'RRULE:FREQ=DAILY;COUNT=2'

        if 'reminders' in data:
            event['reminders'] = data['reminders']
        else:
            event['reminders'] = {
                'useDefault':
                False,
                'overrides': [
                    {
                        'method': 'email',
                        'minutes': 24 * 60
                    },
                    {
                        'method': 'popup',
                        'minutes': 10
                    },
                ],
            }

        e = service.events().insert(calendarId='primary', body=event).execute()
Example #15
0
        'Prints the outgoing HTTP request along with headers and body.')
flags.DEFINE_string(
        'credentials_file',
        'taskqueue.dat',
        'File where you want to store the auth credentails for later user')

# Set up a Flow object to be used if we need to authenticate. This
# sample uses OAuth 2.0, and we set up the OAuth2WebServerFlow with
# the information it needs to authenticate. Note that it is called
# the Web Server Flow, but it can also handle the flow for native
# applications <http://code.google.com/apis/accounts/docs/OAuth2.html#IA>
# The client_id client_secret are copied from the Identity tab on
# the Google APIs Console <http://code.google.com/apis/console>
FLOW = OAuth2WebServerFlow(
    client_id='157776985798.apps.googleusercontent.com',
    client_secret='tlpVCmaS6yLjxnnPu0ARIhNw',
    scope='https://www.googleapis.com/auth/taskqueue',
    user_agent='taskqueue-cmdline-sample/1.0')

class GoogleTaskQueueCommandBase(appcommands.Cmd):
    """Base class for all the Google TaskQueue client commands."""

    DEFAULT_PROJECT_PATH = 'projects/default'

    def __init__(self, name, flag_values):
        super(GoogleTaskQueueCommandBase, self).__init__(name, flag_values)

    def _dump_request_wrapper(self, http):
        """Dumps the outgoing HTTP request if requested.

        Args:
Example #16
0
    def start_push_notification(self, request):
        from django.core.urlresolvers import reverse
        approval_force = False
        try:
            credentials = CredentialsModel.objects.get(
                id=request.user).credentials
            if credentials:
                if not credentials.refresh_token:
                    approval_force = True
                    raise CredentialsModel.DoesNotExist
                elif credentials.access_token_expired:
                    import httplib2
                    credentials.refresh(httplib2.Http())
        except CredentialsModel.DoesNotExist:
            from django.conf import settings
            from django.http import HttpResponseRedirect
            FlowModel.objects.filter(id=request.user).delete()
            kwargs = {}
            if approval_force:
                kwargs['approval_prompt'] = 'force'
            defaultflow = OAuth2WebServerFlow(
                client_id=settings.GOOGLE_CLIENT_ID,
                client_secret=settings.GOOGLE_CLIENT_SECRET,
                scope='https://www.googleapis.com/auth/drive.metadata.readonly',
                redirect_uri=request.build_absolute_uri(
                    reverse('admin:google_flow')).replace(
                        '/cutler5:', '/cutler5.example.com:'),
                access_type='offline',
                **kwargs)
            flow = FlowModel(id=request.user, flow=defaultflow)
            flow.save()
            url = flow.flow.step1_get_authorize_url()
            return HttpResponseRedirect(url)
        from apiclient.discovery import build
        import httplib2
        import uuid
        import time
        drive = build('drive', 'v2', credentials.authorize(httplib2.Http()))
        body = {
            'kind':
            'api#channel',
            'resourceId':
            self.scheduleid,
            'id':
            unicode(uuid.uuid4()),
            'token':
            u'%s:%s' % (self.id, unicode(request.user)),
            'type':
            'web_hook',
            'address':
            request.build_absolute_uri(
                reverse('tracker.views.refresh_schedule')),
            'expiration':
            int(time.time() + 24 * 60 * 60) * 1000  # approx one day
        }
        try:
            drive.files().watch(fileId=self.scheduleid, body=body).execute()
        except Exception as e:
            from django.contrib import messages

            messages.error(request,
                           u'Could not start push notification: %s' % e)
            return False
        return True
Example #17
0
from oauth2client.client import OAuth2WebServerFlow

# List the scopes your app requires:
SCOPES = ['https://www.googleapis.com/auth/plus.me',
          'https://www.googleapis.com/auth/plus.stream.write']

# The following redirect URI causes Google to return a code to the user's
# browser that they then manually provide to your app to complete the
# OAuth flow.
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'

# For a breakdown of OAuth for Python, see
# https://developers.google.com/api-client-library/python/guide/aaa_oauth
# CLIENT_ID and CLIENT_SECRET come from your Developers Console project
flow = OAuth2WebServerFlow(client_id='174353696507-9ma9jni3bl5crhrqbnkpv6d7g0nt062q.apps.googleusercontent.com',
                           client_secret='OXKTS0EbGmZDEvm5adGmYMjW',
                           scope=SCOPES,
                           redirect_uri=REDIRECT_URI)

auth_uri = flow.step1_get_authorize_url()

# This command-line server-side flow example requires the user to open the
# authentication URL in their browser to complete the process. In most
# cases, your app will use a browser-based server-side flow and your
# user will not need to copy and paste the authorization code. In this
# type of app, you would be able to skip the next 3 lines.
# You can also look at the client-side and one-time-code flows for other
# options at https://developers.google.com/+/web/signin/
print 'Please paste this URL in your browser to authenticate this program.'
print auth_uri
code = raw_input('Enter the code it gives you here: ')
Example #18
0
app = Flask(__name__)
#app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///UserRegisters.db'
#app.config.setdefault('SQLALCHEMY_TRACK_MODIFICATIONS', True)

#db = SQLAlchemy(app)
#migrate = Migrate(app, db)

'''
class UserRegister(db.Model):
    __tablename__ = 'UserRegisters'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(80), unique=True, nullable=True)
'''
flow = OAuth2WebServerFlow(client_id=os.environ['OAUTH_CLIENT_ID'],
        client_secret=os.environ['OAUTH_CLIENT_SECRET'],
        scope='https://www.googleapis.com/auth/userinfo.email',
        redirect_uri='https://career-drive.herokuapp.com/oauth2callback')


@app.route('/', methods=['GET'])
def readfile_handler():
    auth_uri = flow.step1_get_authorize_url()
    return redirect(auth_uri)

@app.route('/oauth2callback')
def oauth_callback():
    auth_code = request.args.get('code')
    credentials = flow.step2_exchange(auth_code)
    service = build('oauth2', 'v2', credentials=credentials)
    userinfo = service.userinfo().get().execute()
    print(userinfo)
Example #19
0
def addEvent():

    # Create a flow object. This object holds the client_id, client_secret, and
    # scope. It assists with OAuth 2.0 steps to get user authorization and
    # credentials.

    flow = OAuth2WebServerFlow(client_id, client_secret, scope)

    # Create a Storage object. This object holds the credentials that your
    # application needs to authorize access to the user's data. The name of the
    # credentials file is provided. If the file does not exist, it is
    # created. This object can only hold credentials for a single user, so
    # as-written, this script can only handle a single user.
    storage = Storage('credentials.dat')

    # The get() function returns the credentials for the Storage object. If no
    # credentials were found, None is returned.
    credentials = storage.get()

    # If no credentials are found or the credentials are invalid due to
    # expiration, new credentials need to be obtained from the authorization
    # server. The oauth2client.tools.run_flow() function attempts to open an
    # authorization server page in your default web browser. The server
    # asks the user to grant your application access to the user's data.
    # If the user grants access, the run_flow() function returns new credentials.
    # The new credentials are also stored in the supplied Storage object,
    # which updates the credentials.dat file.
    if credentials is None or credentials.invalid:
        credentials = run_flow(flow, storage)


# Create an httplib2.Http object to handle our HTTP requests, and authorize it
# using the credentials.authorize() function.
    http = httplib2.Http()

    http = credentials.authorize(http)

    # The apiclient.discovery.build() function returns an instance of an API service
    # object can be used to make API calls. The object is constructed with
    # methods specific to the calendar API. The arguments provided are:
    #   name of the API ('calendar')
    #   version of the API you are using ('v3')
    #   authorized httplib2.Http() object that can be used for API calls
    service = build('calendar', 'v3', http=http)

    try:
        event = {
            'summary': 'G',
            'start': {
                'dateTime': '2018-03-28T09:00:00',
                'timeZone': 'Asia/Bangkok',
            },
            'end': {
                'dateTime': '2018-03-28T09:00:00',
                'timeZone': 'Asia/Bangkok',
            },
        }
        warning = 0
        while warning == 0:

            flag = 0
            while flag == 0:
                tts("แจ้งเตือนเรื่องอะไรค่ะ")
                try:
                    summary = stt()
                    if summary == "ไม่เข้าใจที่พูดออกมาค่ะ":
                        continue
                    flag = 1
                except Exception:
                    tts("อินเทอร์เน็ตมีปัญหาค่ะ")

            text = askDateTime()
            date = str(text)
            date = date.replace(" ", "T")

            print("Test")

            event['summary'] = summary
            event['start']['dateTime'] = date
            event['end']['dateTime'] = date

            sayevent = "แจ้งเตือนเรื่อง" + summary + "วันที่" + str(
                text.day) + "เดือน" + str(text.month) + "ตอน" + str(
                    text.time())

            flag = 0
            while flag == 0:
                tts(sayevent + "ถูกต้องหรือไม่ค่ะ")
                try:
                    inputsay = stt()
                    if (inputsay == "ไม่เข้าใจที่พูดออกมาค่ะ"):
                        continue
                    flag = 1
                except Exception:
                    tts("อินเทอร์เน็ตมีปัญหาค่ะ")
                    continue

            if any([
                    "โอเค" in inputsay, "ครับ" in inputsay, "ค่ะ" in inputsay,
                    "ถูก" in inputsay
            ]):
                service.events().insert(calendarId='primary',
                                        sendNotifications=True,
                                        body=event).execute()

            warning = 1

    except Exception as e:
        tts("มีปัญหาในการต่อปฏิทินค่ะ")

    except KeyError:
        tts("มีปัญหาในการต่อปฏิทิน Google ค่ะ")
def handle_redirect():
    flow = OAuth2WebServerFlow(client_id=settings.CLIENT_ID,
                               client_secret=settings.CLIENT_SECRET,
                               scope=settings.SCOPES,
                               redirect_uri=settings.CALLBACK_URI)
    return flow.step1_get_authorize_url()
def main(argv):
    option_parser = OptionParser()
    option_parser.add_option('-c', '--create-table', action='store_true')
    option_parser.add_option('-t', '--table-name', default='devfestzurich', metavar='TABLE')
    option_parser.add_option('--table-id', default='1O7qsDkkgaDbAArUKywHVwPxVqz4RA9P1xEAfrHU', metavar='TABLE-ID')
    option_parser.add_option('-q', '--query', metavar='QUERY')
    option_parser.add_option('-k', '--key', default='AIzaSyBfoMH8qNEQYBjLA9u0jLgs5V6o7KiAFbQ', metavar='KEY')
    option_parser.add_option('-l', '--limit', default=20, metavar='LIMIT', type=int)
    option_parser.add_option('-f', '--fields', default='items(geocode,id,published),nextPageToken', metavar='FIELDS')
    option_parser.add_option('--client-id', default='265903001164-lrjmvjnqjl2sfa13ogofm3hj2roakqkj.apps.googleusercontent.com')
    option_parser.add_option('--client-secret', default='DgdHp4OsayYhTx3kPhXTYt1W')
    option_parser.add_option('--scope', default='https://www.googleapis.com/auth/fusiontables')
    option_parser.add_option('--log-level', default=0, type=int)
    option_parser.add_option('--verbose', '-v', action='count', dest='log_level')
    options, args = option_parser.parse_args(argv[1:])

    logging.basicConfig(format='%(asctime)s %(message)s', level=logging.WARN - 10 * options.log_level)

    logger = logging.getLogger(os.path.basename(argv[0]))

    flow = OAuth2WebServerFlow(options.client_id, options.client_secret, options.scope)
    storage = Storage('credentials.dat')
    credentials = storage.get()
    if credentials is None or credentials.invalid:
        credentials = run(flow, storage)

    plus_session = requests.session()
    ft_session = requests.session(headers={'Authorization': 'OAuth ' + credentials.access_token})

    if options.create_table:
        data = {
            'description': 'DevFest Zurich',
            'isExportable': True,
            'name': options.table_name,
            'columns': [
                {'name': 'id', 'type': 'STRING'},
                {'name': 'published', 'type': 'DATETIME'},
                {'name': 'query', 'type': 'STRING'},
                {'name': 'geocode', 'type': 'LOCATION'},
            ],
        }
        while True:
            ft_response = ft_session.post('https://www.googleapis.com/fusiontables/v1/tables', data=json.dumps(data), headers={'Content-Type': 'application/json'})
            if ft_response.status_code == 200:
                break
            elif ft_response.status_code == 401:
                credentials = run(flow, storage)
            else:
                print repr(ft_response)
                print repr(ft_response.content)
                raise RuntimeError

        print repr(ft_response)
        print repr(ft_response.json)

    params = {
        'fields': options.fields,
        'key': options.key,
        'maxResults': 20,
        'query': options.query,
        }
    count = 0
    while options.limit and count < options.limit:
        plus_response = plus_session.get('https://www.googleapis.com/plus/v1/activities', params=params)
        logging.info('got %d items, %d with geocode' % (len(plus_response.json['items']), len([item for item in plus_response.json['items'] if 'geocode' in item])))
        items = [Item(item_json) for item_json in plus_response.json['items'] if 'geocode' in item_json]
        for item in items:
            while True:
                time.sleep(2)
                ft_response = ft_session.post('https://www.googleapis.com/fusiontables/v1/query', headers={'Content-Length': '0'}, params={'sql': item.insert(options.table_id, options.query)})
                #print repr(ft_response)
                #print repr(ft_response.content)
                if ft_response.status_code == 200:
                    break
                elif ft_response.status_code == 401:
                    credentials = run(flow, storage)
                else:
                    print repr(ft_response)
                    print repr(ft_response.content)
                    raise RuntimeError
            count += len(items)
        if 'nextPageToken' in plus_response.json:
            params['pageToken'] = plus_response.json['nextPageToken']
        else:
            break
Example #22
0
from __future__ import print_function
import pickle
import os.path
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import httplib2
from googleapiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client import tools
FLOW = OAuth2WebServerFlow(
    client_id=
    '73558912455-smu6u0uha6c2t56n2sigrp76imm2p35j.apps.googleusercontent.com',
    client_secret='0X_IKOiJbLIU_E5gN3NefNns',
    scope=[
        'https://www.googleapis.com/auth/calendar',
        'https://www.googleapis.com/auth/contacts.readonly'
    ],
    user_agent='Smart assistant box')
storage1 = Storage('/opt/mycroft/skills/devicereservation.hanabouzid/info.dat')
credentials = storage1.get()
if credentials is None or credentials.invalid == True:
    credentials = tools.run_flow(FLOW, storage1)
print(credentials)
# Create an httplib2.Http object to handle our HTTP requests and
# authorize it with our good Credentials.
http = httplib2.Http()
http = credentials.authorize(http)
service = build('calendar', 'v3', http=http)
people_service = build(serviceName='people', version='v1', http=http)
print("authorized")
Example #23
0
                            EmailOutboxMessage, EmailOutboxAttachment,
                            TemplateVariable)
from .utils import (create_account, get_attachment_filename_from_url,
                    get_email_parameter_choices, create_recipients,
                    render_email_body, replace_cid_in_html,
                    create_reply_body_header)
from .tasks import (send_message, create_draft_email_message,
                    delete_email_message, archive_email_message,
                    update_draft_email_message)

logger = logging.getLogger(__name__)

FLOW = OAuth2WebServerFlow(
    client_id=settings.GA_CLIENT_ID,
    client_secret=settings.GA_CLIENT_SECRET,
    redirect_uri=settings.GMAIL_CALLBACK_URL,
    scope='https://mail.google.com/',
    approval_prompt='force',
)


class SetupEmailAuth(LoginRequiredMixin, View):
    def get(self, request):
        FLOW.params['state'] = generate_token(settings.SECRET_KEY,
                                              request.user.pk)
        authorize_url = FLOW.step1_get_authorize_url()

        return HttpResponseRedirect(authorize_url)


class OAuth2Callback(LoginRequiredMixin, View):
Example #24
0
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run

# Set up a Flow object to be used if we need to authenticate. This
# sample uses OAuth 2.0, and we set up the OAuth2WebServerFlow with
# the information it needs to authenticate. Note that it is called
# the Web Server Flow, but it can also handle the flow for
# installed applications.
#
# Go to the Google API Console, open your application's
# credentials page, and copy the client ID and client secret.
# Then paste them into the following code.
FLOW = OAuth2WebServerFlow(
    client_id='555561141257-hgfs8ne4bnhj3p3qg9504if59dq0m4sj.apps.googleusercontent.com',
    client_secret='JgDHnKzzu-gs4CftgAnF7GWT',
    scope='https://www.googleapis.com/auth/contacts.readonly',
    user_agent='praveen-app/1')

# If the Credentials don't exist or are invalid, run through the
# installed application flow. The Storage object will ensure that,
# if successful, the good Credentials will get written back to a
# file.
storage = Storage('info.dat')
credentials = storage.get()
if credentials is None or credentials.invalid == True:
  credentials = run(FLOW, storage)

# Create an httplib2.Http object to handle our HTTP requests and
# authorize it with our good Credentials.
http = httplib2.Http()
Example #25
0
def main():
    global in_cal
    print('Init')
    # get the list of added events
    try:
        with open("added.json", 'rb+') as infile:
            in_cal = pickle.load(infile)
    except FileNotFoundError:
        in_cal = []

    graph = gr.GraphAPI(access_token=at)

    # authenticate with google
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'fb-calendar.json')

    store = Storage(credential_path)
    creds = store.get()
    if not creds or creds.invalid:
        auth = OAuth2WebServerFlow(client_id=get_file_line("code/g_client_id"),
                            client_secret=get_file_line("code/g_client_secret"),
                            scope="https://www.googleapis.com/auth/calendar",
                            redirect_uri="http://localhost/")
        creds = tools.run_flow(auth, store)


    # now we can use the creds and send our access token along for the ride!
    http = creds.authorize(httplib2.Http())
    service = discovery.build('calendar', 'v3', http=http)

    all_e = graph.get_object(id="me", fields="events{id, name, timezone, start_time, end_time, event_times, rsvp_status}")
    events = all_e['events']['data']

    for e in events:
        ename = e['name']
        eid = e['id']
        etimezone = e['timezone']
        rsvp = e['rsvp_status']
        try:
            # for i in range(0, len(e['event_times']), 1)):
            estart = e['start_time']
            eend = e['end_time']
            if estart == '' and eend == '':
                estart = e['event_times'][0]['start_time']
                eend = e['event_times'][0]['end_time']
        except KeyError:
            # might be that only start time specified, so try get the start time
            try:
                estart = e['start_time']
                if estart != '':
                    # problem is, we have no enddate
                    eend = estart
                    eend = dp.parse(eend)
                    eend = eend + td(hours=1)
                    eend = str(eend.isoformat())
            except KeyError:
                estart=''
                eend=''

        if not (eid in in_cal) and rsvp == "attending":
            # we want to add it into the calendar
            add = {
                'summary': ename,
                'start': {
                    'dateTime': estart,
                    'timeZone': etimezone,
                },
                'end': {
                    'dateTime': eend,
                    'timeZone': etimezone,
                },
                'reminders': {
                    'useDefault': False,
                    'overrides': [
                        {'method': 'popup', 'minutes': 60},
                    ],
                },
            }
            # event = service.events().insert(calendarId=cal_id, body=add).execute()
            # print ('Event created: %s' % (event.get('htmlLink')))
            in_cal.append(eid)

        # reset.
        estart = ''
        eend = ''
Example #26
0
        storage = DjangoORMStorage(CredentialsModel, 'id', user, 'credential')
        credentials = storage.get()

        if credentials is None or credentials.invalid == True:
            FLOW.params['state'] = xsrfutil.generate_token(settings.GOOGLE_OAUTH2_CLIENT_SECRET,
                                                           request.user)
            authorize_url = FLOW.step1_get_authorize_url()

            return HttpResponseRedirect(authorize_url)

        return HttpResponseRedirect('/')


FLOW = OAuth2WebServerFlow(
    client_id=settings.GOOGLE_OAUTH2_CLIENT_ID,
    client_secret=settings.GOOGLE_OAUTH2_CLIENT_SECRET,
    scope=settings.GOOGLE_OAUTH2_SCOPES,
    redirect_uri=settings.AUTH_REDIRECT_URL)

class AuthGoogleFinishedView(View):
    def get(self, request):
        # raise
        user = None
        if not request.user.is_anonymous():
            user = request.user

        if not xsrfutil.validate_token(
            settings.GOOGLE_OAUTH2_CLIENT_SECRET,
            request.GET['state'].encode('UTF-8'),
            request.user
            ):
Example #27
0
def do_authentication(hass, config):
    """Notify user of actions and authenticate.

    Notify user of user_code and verification_url then poll
    until we have an access token.
    """
    from oauth2client.client import (OAuth2WebServerFlow,
                                     OAuth2DeviceCodeError, FlowExchangeError)
    from oauth2client.file import Storage

    oauth = OAuth2WebServerFlow(
        config[CONF_CLIENT_ID],
        config[CONF_CLIENT_SECRET],
        'https://www.googleapis.com/auth/calendar.readonly',
        'Home-Assistant.io',
    )

    persistent_notification = loader.get_component('persistent_notification')
    try:
        dev_flow = oauth.step1_get_device_and_user_codes()
    except OAuth2DeviceCodeError as err:
        persistent_notification.create(
            hass,
            'Error: {}<br />You will need to restart hass after fixing.'
            ''.format(err),
            title=NOTIFICATION_TITLE,
            notification_id=NOTIFICATION_ID)
        return False

    persistent_notification.create(
        hass,
        'In order to authorize Home-Assistant to view your calendars'
        'You must visit: <a href="{}" target="_blank">{}</a> and enter'
        'code: {}'.format(dev_flow.verification_url, dev_flow.verification_url,
                          dev_flow.user_code),
        title=NOTIFICATION_TITLE,
        notification_id=NOTIFICATION_ID)

    def step2_exchange(now):
        """Keep trying to validate the user_code until it expires."""
        if now >= dt.as_local(dev_flow.user_code_expiry):
            persistent_notification.create(
                hass, 'Authenication code expired, please restart '
                'Home-Assistant and try again',
                title=NOTIFICATION_TITLE,
                notification_id=NOTIFICATION_ID)
            listener()

        try:
            credentials = oauth.step2_exchange(device_flow_info=dev_flow)
        except FlowExchangeError:
            # not ready yet, call again
            return

        storage = Storage(hass.config.path(TOKEN_FILE))
        storage.put(credentials)
        do_setup(hass, config)
        listener()
        persistent_notification.create(
            hass,
            'We are all setup now. Check {} for calendars that have '
            'been found'.format(YAML_DEVICES),
            title=NOTIFICATION_TITLE,
            notification_id=NOTIFICATION_ID)

    listener = track_time_change(hass,
                                 step2_exchange,
                                 second=list(range(0, 60, dev_flow.interval)))

    return True
Example #28
0
# -*- coding: utf-8 -*-

# See:  https://developers.google.com/accounts/docs/OAuth2ForDevices

import httplib2
from oauth2client.client import OAuth2WebServerFlow
from googleapiclient.discovery import build

CLIENT_ID = "some+client+id"
CLIENT_SECRET = "some+client+secret"
SCOPES = ("https://www.googleapis.com/auth/youtube", )

flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, " ".join(SCOPES))

# Step 1: get user code and verification URL
# https://developers.google.com/accounts/docs/OAuth2ForDevices#obtainingacode
flow_info = flow.step1_get_device_and_user_codes()
print "Enter the following code at %s: %s" % (flow_info.verification_url,
                                              flow_info.user_code)
print "Then press Enter."
raw_input()

# Step 2: get credentials
# https://developers.google.com/accounts/docs/OAuth2ForDevices#obtainingatoken
credentials = flow.step2_exchange(device_flow_info=flow_info)
print "Access token:", credentials.access_token
print "Refresh token:", credentials.refresh_token

# Get YouTube service
# https://developers.google.com/accounts/docs/OAuth2ForDevices#callinganapi
youtube = build("youtube", "v3", http=credentials.authorize(httplib2.Http()))
import logging
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow

if len(sys.argv) != 3:
    print "Usage:./splunk cmd python ../etc/apps/googledrive_addon/bin/configure_oauth.py CLIENT_ID CLIENT_SECRET"
    sys.exit()

CLIENT_ID = sys.argv[1]
CLIENT_SECRET = sys.argv[2]
AUTH_CODE = sys.argv[3]

# Check https://developers.google.com/admin-sdk/reports/v1/guides/authorizing for all available scopes
OAUTH_SCOPE = 'https://www.googleapis.com/auth/admin.reports.audit.readonly'

# Redirect URI for installed apps
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'

storage = Storage('google_drive_creds')

# Run through the OAuth flow and retrieve credentials
logging.basicConfig(filename='debug.log', level=logging.DEBUG)
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
#authorize_url = flow.step1_get_authorize_url()
#print 'Go to the following link in your browser: '
#print  authorize_url
#code = raw_input('Enter verification code: ').strip()
credentials = flow.step2_exchange(AUTH_CODE)
storage.put(credentials)
print "OAuth sign-in succeeded"
Example #30
0
from apiclient.discovery import build
from apiclient.http import MediaFileUpload
from oauth2client.client import OAuth2WebServerFlow

# Copy your credentials from the APIs Console
CLIENT_ID = 'YOUR_CLIENT_ID'
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'

# Check https://developers.google.com/drive/scopes for all available scopes
OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'

# Path to the file to upload
FILENAME = 'document.txt'

# Run through the OAuth flow and retrieve credentials
flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE)
authorize_url = flow.step1_get_authorize_url()
print 'Go to the following link in your browser: ' + authorize_url
code = raw_input('Enter verification code: ').strip()
credentials = flow.step2_exchange(code)

# Create an httplib2.Http object and authorize it with our credentials
http = httplib2.Http()
http = credentials.authorize(http)

drive_service = build('drive', 'v2', http=http)

# Insert a file
media_body = MediaFileUpload(FILENAME, mimetype='text/plain', resumable=True)
body = {
    'title': 'My document',