Example #1
0
def getAuthURL():

    FLAGS = gflags.FLAGS
    FLOW = OAuth2WebServerFlow(
        client_id="819119360720.apps.googleusercontent.com",
        client_secret="1J8iirUI-nEdi1RxkKNfFQHq",
        scope="https://www.googleapis.com/auth/calendar.readonly",
        user_agent="GCalPy-CN/0.3",
    )

    FLAGS.auth_local_webserver = False
    oauthURL = OAuth2WebServerFlow.step1_get_authorize_url(FLOW, redirect_uri="http://tracker.ics.uci.edu/gcal")

    return oauthURL, FLOW
Example #2
0
def sync(FLOW, code, email):

    http = httplib2.Http()
    s2 = OAuth2WebServerFlow.step2_exchange(FLOW, code, http=http)

    http = s2.authorize(http)

    service = build(
        serviceName="calendar", version="v3", http=http, developerKey="AIzaSyCcT484gf2or7lsOzcOnGolRWRg4c_JJGI"
    )

    calendar = service.calendars().get(calendarId="primary").execute()

    fp = None
    if "id" in calendar:
        fp = open("/data/calendars/" + calendar["id"], "w")
    else:
        fp = open("/data/calendars/tmp", "w")

    events = service.events().list(calendarId="primary").execute()

    j = 0
    while True:
        for event in events["items"]:
            j += 1
            fp.write(json.dumps(event))
            fp.write("\n")

        pt = events.get("nextPageToken")
        if pt:
            events = service.events().list(calendarId="primary", pageToken=pt).execute()
        else:
            break

    print "Wrote", j, "events into ", "/data/calendars/" + calendar["id"]
    fp.flush()
Example #3
0
# The actual view
from galah.web import app, oauth_enabled
from galah.base.crypto.passcrypt import check_seal, deserialize_seal
from galah.db.models import User
from flask.ext.login import login_user
from galah.web.auth import FlaskUser
from flask import redirect, url_for, flash, request

# Google OAuth2
from oauth2client.client import OAuth2WebServerFlow

# Google OAuth2 flow object to get user's email.
if oauth_enabled:
    flow = OAuth2WebServerFlow(
        client_id=app.config["GOOGLE_SERVERSIDE_ID"],
        client_secret=app.config["GOOGLE_SERVERSIDE_SECRET"],
        scope="https://www.googleapis.com/auth/userinfo.email",
        redirect_uri=app.config["HOST_URL"] + "/oauth2callback")


@app.route("/login/", methods=["GET", "POST"])
def login():
    form = LoginForm()

    # If the user's input isn't immediately incorrect (validate_on_submit() will
    # not check if the email and password combo is valid, only that it could be
    # valid)
    if form.validate_on_submit():
        # Find the user with the given email
        try:
            user = FlaskUser(User.objects.get(email=form.email.data))
Example #4
0
def twplaylist():

    flow = OAuth2WebServerFlow(yt_id, yt_secret, scope)
    storage = Storage('credentials.dat')
    parser = argparse.ArgumentParser(parents=[tools.argparser])
    flags = parser.parse_args()
    credentials = tools.run_flow(flow, storage, flags)
    if credentials is None or credentials.invalid:
        credentials = run(flow, storage)

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

    global youtube
    youtube = build('youtube', 'v3', http=http)

    global twitter
    twitter = tweepy.API(tweepy.OAuthHandler(t_id, t_secret))

    user = twitter.get_user(t_user)

    last_id = ''

    while True:
        try:

            ytlinks = []

            if last_id:
                print 'Grabbing ' + str(
                    t_count
                ) + ' latest tweets from ' + user.screen_name + ' since ' + str(
                    last_id)
                statuses = twitter.user_timeline(id=t_user,
                                                 since_id=int(last_id),
                                                 count=t_count)

            else:
                print 'Grabbing ' + str(
                    t_count) + ' latest tweets from ' + user.screen_name
                statuses = twitter.user_timeline(id=t_user, count=t_count)

            if len(statuses) > 0:

                last_id = statuses[0].id
                for status in statuses:
                    if (match in status.text.lower()) and (
                            status.entities.has_key('urls')):
                        url = status.entities.get('urls')[0].get(
                            'expanded_url')
                        ytcomlink = re.findall(ytcomReg, url)
                        ytbelink = re.findall(ytbeReg, url)
                        if ytbelink != []: ytlinks += ytbelink
                        if ytcomlink != []: ytlinks += ytcomlink

                print 'Adding ' + str(len(ytlinks)) + ' video(s)'
                for video in ytlinks:

                    insert = youtube.playlistItems().insert(
                        part="snippet",
                        body=dict(
                            snippet=dict(playlistId=playlist,
                                         resourceId=dict(kind="youtube#video",
                                                         videoId=video))))
                    response = insert.execute()

            else:
                print 'No new tweets since last attempt'
            print 'Waiting ' + str(sleep) + ' seconds'
            time.sleep(int(sleep))

        except Exception, e:
            print e
            client_id=settings.GOOGLE_OAUTH2_CLIENT_ID,
            client_secret=settings.GOOGLE_OAUTH2_CLIENT_SECRET,
            scope='https://www.googleapis.com/auth/youtube',
            redirect_uri='http://localhost:8000/oauth2callback/')

        if credential is None or credential.invalid == True:
            flow.params['state'] = xsrfutil.generate_token(
                settings.SECRET_KEY, request.user)
            authorize_url = flow.step1_get_authorize_url()
            return redirect(authorize_url)
        return redirect('/')


flow = OAuth2WebServerFlow(
    client_id=settings.GOOGLE_OAUTH2_CLIENT_ID,
    client_secret=settings.GOOGLE_OAUTH2_CLIENT_SECRET,
    scope='https://www.googleapis.com/auth/youtube',
    redirect_uri='http://localhost:8000/oauth2callback/')


class OAuth2CallbackView(View):
    def get(self, request, *args, **kwargs):
        if not xsrfutil.validate_token(settings.SECRET_KEY,
                                       request.GET.get('state').encode(),
                                       request.user):
            return HttpResponseBadRequest()
        credential = flow.step2_exchange(request.GET)
        storage = DjangoORMStorage(CredentialsModel, 'id', request.user.id,
                                   'credential')
        storage.put(credential)
        return redirect('/')
Example #6
0
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from oauth2client.client import OAuth2WebServerFlow, FlowExchangeError
from oauth2client.file import Storage
import os
from config import *

SCOPES = [
    'https://www.googleapis.com/auth/calendar',
    'https://www.googleapis.com/auth/drive', 'profile'
]

flow = OAuth2WebServerFlow(client_id=GOOGLE_OAUTH_CLIENT_ID,
                           client_secret=GOOGLE_OAUTH_CLIENT_SECRET,
                           scope=SCOPES,
                           redirect_uri=GOOGLE_OAUTH_REDIRECT_URI,
                           access_type='offline',
                           prompt='consent')


def get_url():
    return flow.step1_get_authorize_url()


def save(usr, code):
    try:
        credentials = flow.step2_exchange(code)
    except FlowExchangeError:
        return False

    os.chdir(
Example #7
0
DATA_SET = "1581923297927862000-1582023297927862000"

# Constants to loop over each day
current_time_ns = int(time.time() * 1e9)
one_day_ns = 86400000000000
ONE_DAY = current_time_ns - one_day_ns
DAY = current_time_ns

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

#Getting the credetials from Google to authorise my code
#Not using a function because user can allow it once
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 = input('Enter verification code: ').strip()
credentials = flow.step2_exchange(code)

#Looping over i days
for i in range(7):
    DAY = DAY - one_day_ns
    NEW_DATA_ID = (DAY, DAY - one_day_ns)

    #For the DATA_ID formatting
    TEST_ID = ("{}-{}".format(NEW_DATA_ID[0], NEW_DATA_ID[1]))

    def retrieve_data():
Example #8
0
    urlJson=stt.BASE_DIR+"/dataOfTwitter/keys/your-app-2e6b0704e6bf.json"
    f = open(urlJson, 'rb')
    SIGNED_KEY = f.read()
    f.close()
    scope = ['https://spreadsheets.google.com/feeds', 'https://docs.google.com/feeds']
    #scope = 'https://www.googleapis.com/auth/spreadsheets.readonly'
    credentials = ServiceAccountCredentials.from_json_keyfile_name(urlJson, scope)

    data = {
        'refresh_token' : 'your-token-hul2g2WIN1fEis-qn8PjfIMNpZ2',
        'client_id' : 'your-client_id.apps.googleusercontent.com',
        'client_secret' : 'Cliente-secret-h4Mzbb4RZSZG',
        'grant_type' : 'refresh_token',
    }

    r = requests.post('https://accounts.google.com/o/oauth2/token', data = data)
    credentials.access_token = ast.literal_eval(r.text)['access_token']

    gc = gspread.authorize(credentials)
    return gc

CLIENT_ID = '578335401812itj.apps.googleusercontent.com'
CLIENT_SECRET = 'GghbKvIsnXw_h4M'


flow = OAuth2WebServerFlow(client_id=CLIENT_ID,
                           client_secret=CLIENT_SECRET,
                           scope='https://spreadsheets.google.com/feeds https://docs.google.com/feeds',
                           redirect_uri='http://example.com/auth_return')

Example #9
0
import gflags
import httplib2

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

import ConfigParser

config = ConfigParser.ConfigParser()
config.read(['config.ini.dist', 'config.ini'])

FLAGS = gflags.FLAGS
FLOW = OAuth2WebServerFlow(client_id=config.get('google', 'client_id'),
                           client_secret=config.get('google', 'client_secret'),
                           scope=config.get('google', 'scope'),
                           user_agent='Endomondo Sync/0.1')

# 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)

# Create an httplib2.Http object to handle our HTTP requests and authorize it
# with our good Credentials.
Example #10
0
            pickle.dump(google_credentials, file)

        return True
    else:
        print(GOOGLE_PREFIX + 'Failed to refresh tokens, credentials are invalid now')
        return False


if os.path.exists(CREDENTIALS_FILE):
    with open(CREDENTIALS_FILE, 'rb') as file:
        google_credentials = pickle.load(file)

if not google_refresh_tokens():
    flow = OAuth2WebServerFlow(client_id=google_id,
                               client_secret=google_secret,
                               scope='https://www.googleapis.com/auth/spreadsheets',
                               redirect_uri=google_redirect,
                               prompt='consent')

    google_auth_uri = flow.step1_get_authorize_url()

    print("Please authorise yourself at the below URL and paste the code here")
    print(google_auth_uri)
    google_auth_code = input('Code: ')
    google_credentials = flow.step2_exchange(google_auth_code)

    # Pickle the credentials object
    with open(CREDENTIALS_FILE, 'wb') as file:
        pickle.dump(google_credentials, file)

##### Set up the Google Sheets service #################################################################################
Example #11
0
def ia_credentials_helper(client_id,
                          client_secret,
                          credentials_cache_file="credentials.json",
                          cache_key="default"):
    """Helper function to manage a credentials cache during testing.

    This function attempts to load and refresh a credentials object from a
    json cache file, using the cache_key and client_id as a lookup.

    If this isn't found then it starts an OAuth2 authentication flow, using
    the client_id and client_secret and if successful, saves those to the local
    cache. See :ref:`helper`.
  
    Args:
        client_id (str): Google Drive API client id string for an installed app
        client_secret (str): The corresponding client secret.
        credentials_cache_file (str): Filepath to the json credentials cache file
        cache_key (str): Optional string to allow multiple credentials for a client
           to be stored in the cache.

    Returns:
        OAuth2Credentials: A google api credentials object. As described here:
        https://developers.google.com/api-client-library/python/guide/aaa_oauth

    """
    def _load_credentials(key):
        with open(credentials_cache_file, 'r') as inf:
            cache = json.load(inf)
        cred_json = cache[key]
        return OAuth2Credentials.from_json(cred_json)

    def _save_credentials(key, credentials):
        cache = {}
        try:
            with open(credentials_cache_file, 'r') as inf:
                cache = json.load(inf)
        except (IOError, ValueError) as e:
            pass
        cache[key] = credentials.to_json()
        with open(credentials_cache_file, 'w') as ouf:
            json.dump(cache, ouf)

    credentials_key = "%s/%s/%s" % (client_id, client_secret, cache_key)
    try:
        credentials = _load_credentials(credentials_key)
        if credentials.access_token_expired:
            http = httplib2.Http()
            credentials.refresh(http)
    except (IOError, ValueError, KeyError, AccessTokenRefreshError) as e:
        # Check https://developers.google.com/drive/scopes for all available scopes
        OAUTH_SCOPE = ('https://www.googleapis.com/auth/drive ' +
                       'https://spreadsheets.google.com/feeds')
        # Redirect URI for installed apps
        REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'

        # Run through the OAuth flow and retrieve credentials
        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:\n' + authorize_url)
        code = input('Enter verification code: ').strip()
        credentials = flow.step2_exchange(code)

    _save_credentials(credentials_key, credentials)
    return credentials
Example #12
0
# -*- coding: utf-8 -*-

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

import httplib2
from six.moves import input
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."
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
def load_data_from_google_spreadsheet():
    """Shows basic usage of the Sheets API.
    Prints values from a sample spreadsheet.
    """
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    store = file.Storage('token.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = OAuth2WebServerFlow(client_id=CLIENT_ID,
                           client_secret=CLIENT_SECRET,
                           scope=SCOPES)
        creds = tools.run_flow(flow, store)
    service = build('sheets', 'v4', http=creds.authorize(Http()))

    # Call the Sheets API
    sheet_metadata = service.spreadsheets().get(spreadsheetId=SPREADSHEET_ID).execute()
    sheets = sheet_metadata.get('sheets', '')

    ranges = [sheet['properties']['title']+"!"+CELLS_RANGE for sheet in sheets]

    all_data = []
    all_users = []

    for i, sheetinstance in enumerate(sheets):
        all_data.append({ "title": sheetinstance['properties']["title"], "rtl": sheetinstance['properties']['rightToLeft']})

    request = service.spreadsheets().values().batchGet(spreadsheetId = SPREADSHEET_ID, ranges = ranges)
    data = request.execute()
    values = data['valueRanges']

    for i, sheetinstance in enumerate(sheets):
        rows = values[i]['values']

        if rows[0] != ["user","image_url","status"]:
            print(f'No data found on {sheetinstance["properties"]["title"]}.')

        else:
            conversation_data = []
            sides = {}                     # initiate dictionary for user names and profile image

            for counter, row in enumerate(rows):
                if counter == 1:
                    try:
                        talker = { 'username': row[0], 'image_url': row[1], 'status':row[2]}
                        if row[0] not in all_users:
                            all_users+=[{'username': row[0], 'image_url': row[1], 'status':row[2]}]

                    except Exception as e:
                        print(row)
                        print(i)
                        print(sys.stderr, f"could  not find valid user1 details in row no. 2 of the spreadsheet")
                        print(e)
                        sys.exit(1)
                elif counter == 2:
                    try:
                        chatmate = { 'username': row[0], 'image_url': row[1], 'status':row[2]}
                        if row[0] not in all_users:
                            all_users+=[{'username': row[0], 'image_url': row[1], 'status':row[2]}]

                    except Exception as e:
                        print(sys.stderr, f"could not find valid user2 details in row no. 3 of the spreadsheet")
                        print(e)
                        sys.exit(1)

                elif counter > 3:

                    try:
                        time = datetime.datetime.strptime(str(row[2]),"%H:%M")
                    except Exception as e:
                        print (sys.stderr, f"illegal time was given on row[{counter}]: {row}")
                        print(e)
                        sys.exit(1)

                    if row[0] in [talker["username"], chatmate["username"]]:
                        user = row[0]
                    else:
                        print(row[0]+" was entered as a username, but is not included in the users list")
                        print(row)
                        print("talker: ", talker)
                        print("chatmate: ", chatmate)
                        sys.exit(1)

                    if not(row[1] == ''):
                        message = row[1]
                    else:
                        print(f"Illegal empty message string appears on {time}")
                        sys.exit(1)


                    conversation_data.append({"user":user, "message":message, "time": time})

            all_data[i]["thread"] = conversation_data
            all_data[i]["sides"] = {"talker": talker, "chatmate":chatmate}
            all_data[i]["talker"] = talker
            all_data[i]["chatmate"] = chatmate

        for i in range(0, len(all_data)):
            if "talker" in all_data[i] and "chatmate" in all_data[i]:
                all_data[i]["other_users"] = [user for user in all_users if (user["username"] != all_data[i]["talker"]["username"] and user["username"] != all_data[i]["chatmate"]["username"])]

    return(all_data)
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run
import json

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='317796910577.apps.googleusercontent.com',
    client_secret='IvKDHSorjkShs8YHxZtya5-U',
    scope='https://www.googleapis.com/auth/calendar.readonly',
    user_agent='YOUR_APPLICATION_NAME/YOUR_APPLICATION_VERSION')

# 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)

# Create an httplib2.Http object to handle our HTTP requests and authorize it
Example #15
0
CLIENT_SECRET = ''

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

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

#Dropbox account authentication
flow = dropbox.client.DropboxOAuth2FlowNoRedirect(app_key, app_secret)

client = dropbox.client.DropboxClient('')
#print 'linked account: ', client.account_info()

#Run through the OAuth flow and retrieve credentials
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)

# 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)

print 'Select and option:'

Example #16
0
def oauth_callback(request):
    protocol = request.META.get('wsgi.url_scheme', 'https')
    domain = request.META['HTTP_HOST']  # 'glasscloor.com'
    url_path = request.get_full_path()  # '/engagement_path/ref?queries=..'
    full_url = '{}://{}{}'.format(protocol, domain, url_path)
    queryless_url = full_url[:full_url.find('?')]

    # Errors might not necessarily indicate failure.
    if request.GET.get('error', None) is not None:
        logger.warn('[ ! ] OAuth request returned with an error:'
                    '\n    {}'.format(full_url))

    oauth_engagement = get_oauth_engagement_by_url(queryless_url)
    if oauth_engagement is None:
        logger.warn('[ ! ] OAuth request does not match any OAuthConsumer:'
                    '\n    {}'.format(queryless_url))
        engagement = None
        target = None
    else:
        oauth_consumer = oauth_engagement.oauth_consumer
        engagement = oauth_engagement.engagement_ptr
        # Can't put `ref` in the redirect URI -- have to use `state`.
        # Reference: http://stackoverflow.com/a/7722099
        ref = request.GET['state']
        target_id = Target.decrypt_id(engagement.url_key, ref)
        target = Target.objects.get(id=target_id)

    access_code = request.GET.get('code', None)
    # Missing an access token indicates authorization denial.
    if access_code is None:
        return HttpResponseRedirect(oauth_consumer.bounce_url)

    scope = oauth_consumer.scope.split('+')
    if 'email' not in scope:
        scope.append('email')

    flow = OAuth2WebServerFlow(client_id=oauth_consumer.client_id,
                               client_secret=oauth_consumer.client_secret,
                               scope=scope,
                               redirect_uri=oauth_consumer.callback_url,
                               access_type='offline',
                               prompt='consent')
    credentials = flow.step2_exchange(access_code)

    email = credentials.id_token.get('email', None)
    if email is None:
        email = 'EMAIL_NOT_PROVIDED'

    oauth_result = OAuthResult(timestamp=dj_tz.now(),
                               userAgent=request.META['HTTP_USER_AGENT'],
                               ip=request.META['REMOTE_ADDR'],
                               oauth_engagement=oauth_engagement,
                               target=target,
                               email=email,
                               consumer=oauth_consumer,
                               credentials=credentials)
    oauth_result.save()

    OAuthResult.objects.filter(oauth_engagement=oauth_engagement,
                               target__email=target.email,
                               email=email,
                               consumer=oauth_consumer).\
                        exclude(id=oauth_result.id).\
                        delete()

    if not credentials.refresh_token:
        logger.info('[ ! ] Access accepted but refresh token not received for'
                    ' OAuthResult #{}'.format(oauth_result.id))

    return HttpResponseRedirect(oauth_consumer.bounce_url)
Example #17
0
 def get(self):
     flow = OAuth2WebServerFlow(CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE,
                                REDIRECT_URI)
     authorize_url = flow.step1_get_authorize_url()
Example #18
0
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client import tools

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='your_project_id',
                           client_secret='your_project_secret',
                           scope='https://www.googleapis.com/auth/calendar',
                           user_agent='Voice Task notifications/v1')

# 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('credentials.dat')
credentials = storage.get()
if credentials is None or credentials.invalid == True:
    credentials = tools.run_flow(FLOW, storage)

# Create an httplib2.Http object to handle our HTTP requests and authorize it
# with our good Credentials.
Example #19
0
 def __init__(self, proxyHost=None, proxyPort=None, proxyUser=None, proxyPassword=None):
     self.__http = createHttp(proxyHost, proxyPort, proxyUser, proxyPassword)
     self.__oauth = OAuth2WebServerFlow(self.__APP_ID, self.__APP_SECRET, self.__SCOPE,
                                        redirect_uri=self.__REDIRECT_URI)
Example #20
0
def reader_callback(request):
    ip = request.META.get('HTTP_X_REAL_IP', None) or request.META.get(
        'REMOTE_ADDR', "")
    domain = Site.objects.get_current().domain
    STEP2_URI = "http://%s%s" % (
        (domain + '.com') if not domain.endswith('.com') else domain,
        reverse('google-reader-callback'),
    )
    FLOW = OAuth2WebServerFlow(
        client_id=settings.GOOGLE_OAUTH2_CLIENTID,
        client_secret=settings.GOOGLE_OAUTH2_SECRET,
        scope="http://www.google.com/reader/api",
        redirect_uri=STEP2_URI,
        user_agent='NewsBlur Pro, www.newsblur.com',
    )
    FLOW.redirect_uri = STEP2_URI

    try:
        credential = FLOW.step2_exchange(request.REQUEST)
    except FlowExchangeError:
        logging.info(" ***> [%s] Bad token from Google Reader." %
                     (request.user, ))
        return render_to_response('social/social_connect.xhtml', {
            'error':
            'There was an error trying to import from Google Reader. Trying again will probably fix the issue.'
        },
                                  context_instance=RequestContext(request))

    user_token = None
    if request.user.is_authenticated():
        user_token = OAuthToken.objects.filter(
            user=request.user).order_by('-created_date')
    if not user_token:
        user_uuid = request.COOKIES.get('newsblur_reader_uuid')
        if user_uuid:
            user_token = OAuthToken.objects.filter(
                uuid=user_uuid).order_by('-created_date')
    if not user_token:
        session = request.session
        if session.session_key:
            user_token = OAuthToken.objects.filter(
                session_id=request.session.session_key).order_by(
                    '-created_date')
    if not user_token:
        user_token = OAuthToken.objects.filter(
            remote_ip=ip).order_by('-created_date')

    if user_token:
        user_token = user_token[0]
        user_token.credential = base64.b64encode(pickle.dumps(credential))
        user_token.session_id = request.session.session_key
        user_token.save()

    # Fetch imported feeds on next page load
    request.session['import_from_google_reader'] = True

    logging.user(request, "~BB~FW~SBFinishing Google Reader import - %s" % ip)

    if request.user.is_authenticated():
        return render_to_response('social/social_connect.xhtml', {},
                                  context_instance=RequestContext(request))

    return HttpResponseRedirect(reverse('import-signup'))
Example #21
0
def reset_sync(service_provider):
    service = get_gcal(service_provider)
    if not service:
        return service_provider

    Reservation.objects.filter(service_provider=service_provider,
                               isfromgcal=True).delete()
    for reservation in Reservation.objects.filter(
            service_provider=service_provider).select_for_update():
        if service:
            try:
                service.events().delete(calendarId=service_provider.gcal_id,
                                        eventId=reservation.gcalid).execute()
            except:
                pass
        reservation.gcalid = None
        reservation.gcalimported = None
        reservation.save()
    service_provider.gcal_updated = None
    service_provider.save()
    return service_provider


FLOW = OAuth2WebServerFlow(client_id=settings.GOOGLE_CLIENT_ID,
                           client_secret=settings.GOOGLE_CLIENT_SECRET,
                           scope='https://www.googleapis.com/auth/calendar',
                           redirect_uri=settings.BASE_URL +
                           '/myreservations/gcal/callback',
                           access_type='offline',
                           approval_prompt='force')
Example #22
0
from django.utils.crypto import get_random_string
from django.http import HttpResponseBadRequest

from django.contrib.auth import authenticate, login

import logging

logger = logging.getLogger(__name__)

from oauth2client.client import OAuth2WebServerFlow

flow = OAuth2WebServerFlow(
    client_id=settings.CLIENT_ID,
    client_secret=settings.CLIENT_SECRET,
    scope=settings.DEFAULT_SCOPE,
    auth_uri=settings.AUTHORIZATION_URL,
    token_uri=settings.ACCESS_TOKEN_URL,
    # use reverse_lazy and string_concat because the resolver is not ready when initializing this
    redirect_uri=string_concat(settings.REDIRECT_BASE.rstrip('/'), reverse_lazy('accounts:oauth_callback'))
)
"""Flow instance responsible for handling the OAuth2 process

The following settings parameters are required:

* CLIENT_ID: the client id used to authenticate oneself with the OAuth2 provider
* CLIENT_SECRET: the client secret used to authenticate oneself with the OAuth2 provider
* DEFAULT_SCOPE: the scope to ask for during the OAuth2 process
* AUTHORIZATION_URL: the url of the authorization endpoint to redirect to during step 1 of the process
* ACCESS_TOKEN_URL: the url of the token endpoint to which a POST request is made to get the access token
* REDIRECT_BASE: the base URL to which the OAuth2 endpoint must redirect
"""
Example #23
0
 def get_login_url (self):
     self.__flow = OAuth2WebServerFlow(*musicmanager.oauth)
     return self.__flow.step1_get_authorize_url()
Example #24
0
 def __init__(self):
     super(GoogleSignIn, self).__init__('google')
     self.flow = OAuth2WebServerFlow(client_id=self.consumer_id,client_secret=self.consumer_secret,scope=['https://www.googleapis.com/auth/userinfo.profile','https://www.googleapis.com/auth/youtube'],redirect_uri=YT_REDIRECT,prompt='consent')
     self.flow.params['access_type'] = 'offline'
Example #25
0
                        " " + appendingTime)  # This will be mic.say

            except KeyError, e:
                mic.say("Check Calender that you added it correctly")

        page_token = events.get('nextPageToken')

        if not page_token:
            return


# 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
Example #26
0
from mycroft.messagebus.message import Message
from mycroft.util.parse import extract_datetime
from datetime import datetime, timedelta
import httplib2
from googleapiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client import tools

#in the raspberry we add __main__.py for the authorization
UTC_TZ = u'+00:00'
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')


# TODO: Change "Template" to a unique name for your skill
class DeviceReservationSkill(MycroftSkill):

    # The constructor of the skill, which calls MycroftSkill's constructor
    def __init__(self):
        super(DeviceReservationSkill,
              self).__init__(name="DeviceReservationSkill")

    @property
Example #27
0
from oauth2client.client import OAuth2WebServerFlow

# Why my "App isn't verified" ?
# This might returned by google APIs because we are using a high level scope here
# How to fix it ?
# Just hit the continue anyway button because here you are using you own credentials so no one gonna steal your data
# else complete your developer/app profile and submit for review and get verified
# W4RR10R

__OAUTH_SCOPE = ['https://www.googleapis.com/auth/drive']
__REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'

__CLIENT_ID = input("Enter the client id: ")
__CLIENT_SECRET = input("Enter the client secret: ")

flow = OAuth2WebServerFlow(__CLIENT_ID,
                           __CLIENT_SECRET,
                           __OAUTH_SCOPE,
                           redirect_uri=__REDIRECT_URI)
auth_url = flow.step1_get_authorize_url()
print("Open this URL in any browser and get the refersh token: \n" + auth_url)
refresh_token = input("Enter the Refresh token: ")
auth = flow.step2_exchange(refresh_token).to_json()
print(auth)
Example #28
0
 def __init__(self, CLIENT_ID, CLIENT_SECRET):
     self.flow = OAuth2WebServerFlow(CLIENT_ID,
                                     CLIENT_SECRET,
                                     self.OAUTH_SCOPE,
                                     redirect_uri=self.REDIRECT_URI)
     self.credentials = None
Example #29
0
def do_authentication(hass, hass_config, 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(
        client_id=config[CONF_CLIENT_ID],
        client_secret=config[CONF_CLIENT_SECRET],
        scope='https://www.googleapis.com/auth/calendar.readonly',
        redirect_uri='Home-Assistant.io',
    )

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

    hass.components.persistent_notification.create(
        '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):
            hass.components.persistent_notification.create(
                'Authentication 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, hass_config, config)
        listener()
        hass.components.persistent_notification.create(
            '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=range(0, 60, dev_flow.interval))

    return True
Example #30
0
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.file import Storage


DAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

with open('settings.json') as settings_file:
    SETTINGS = json.load(settings_file)

storage = Storage('__credentials__')
credentials = storage.get()

if not credentials:
    flow = OAuth2WebServerFlow(
        client_id=SETTINGS['client_id'],
        client_secret=SETTINGS['client_secret'],
        scope="https://www.googleapis.com/auth/calendar.readonly",
        redirect_uri="urn:ietf:wg:oauth:2.0:oob"
    )
    auth_uri = flow.step1_get_authorize_url()
    print("Please open\n\n{}\n\nand insert the resulting code here.".format(auth_uri))
    code = raw_input("Code: ")
    credentials = flow.step2_exchange(code)
    storage.put(credentials)

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

start = datetime.datetime(2012, 12, 10, tzinfo=pytz.timezone("Europe/Berlin"))
end = start + datetime.timedelta(weeks=1)

REQUEST = "https://www.googleapis.com/calendar/v3/calendars/{}/events?timeMin={}&timeMax={}".format(
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 are copied from the API Access tab on
# the Google APIs Console
FLOW = OAuth2WebServerFlow(client_id='264532138515.apps.googleusercontent.com',
                           client_secret='B5RpwE_3_a1yIiPMOm6kp8n9',
                           scope='https://www.googleapis.com/auth/calendar',
                           user_agent='PYMEBookings/2011_1_11')

# 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)

# Create an httplib2.Http object to handle our HTTP requests and authorize it
# with our good Credentials.
Example #32
0
                            EmailLabel)
from .services import build_gmail_service
from .tasks import (send_message, create_draft_email_message,
                    delete_email_message, update_draft_email_message,
                    add_and_remove_labels_for_message)
from .utils import (get_attachment_filename_from_url,
                    get_email_parameter_choices, create_recipients,
                    render_email_body, replace_cid_in_html,
                    create_reply_body_header, reindex_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/',
    prompt='consent',
    access_type='offline',
)


class SetupEmailAuth(LoginRequiredMixin, View):
    def get(self, request):
        public = request.GET.get('public', 0)
        only_new = request.GET.get('only_new', 0)

        state = b64encode(
            anyjson.serialize({
                'token':
                generate_token(settings.SECRET_KEY, request.user.pk),
                'public':