Beispiel #1
0
def oauth2callback():
    # Specify the state when creating the flow in the callback so that it can
    # verified in the authorization server response.
    state = flask.session['state']

    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)
    flow.redirect_uri = flask.url_for('oauth2callback', _external=True)

    # Use the authorization server's response to fetch the OAuth 2.0 tokens.
    authorization_response = flask.request.url
    flow.fetch_token(authorization_response=authorization_response)

    # Store credentials in the session.
    # ACTION ITEM: In a production app, you likely want to save these
    #              credentials in a persistent database instead.
    credentials = flow.credentials
    flask.session['credentials'] = credentials_to_dict(credentials)
    # Load credentials from the session.
    credentials = google.oauth2.credentials.Credentials(
        **flask.session['credentials'])

    # initialize Service
    service = googleapiclient.discovery.build(API_SERVICE_NAME,
                                              API_VERSION,
                                              credentials=credentials)

    print(flask.session)
    return flask.redirect(flask.session['url'])
Beispiel #2
0
def authenticate_drive_callback():
    # Specify the state when creating the flow in the callback so that it can
    # verified in the authorization server response.
    state = session['state']

    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        client_secret_path, scopes=google_scopes, state=state)
    flow.redirect_uri = url_for('authenticate_drive_callback', _external=True)

    # Use the authorization server's response to fetch the OAuth 2.0 tokens.
    authorization_response = request.url
    flow.fetch_token(authorization_response=authorization_response)

    credentials_query = get_google_credentials()
    if credentials_query == None:
        # Store credentials
        credentials = GoogleCredentials(user_id=current_user.id,
                                        credentials_json=credentials_to_json(
                                            flow.credentials))
        db.session.add(credentials)
    else:
        credentials_query.credentials_json = credentials_to_json(
            flow.credentials)

    db.session.commit()

    return redirect(url_for('settings'))
Beispiel #3
0
async def rest_callback(request):
    state = request.query['state']
    code = request.query['code']
    callback_port = request.query['callback_port']

    try:
        flow = get_flow(f'http://127.0.0.1:{callback_port}/oauth2callback',
                        state=state)
        flow.fetch_token(code=code)
        token = google.oauth2.id_token.verify_oauth2_token(
            flow.credentials.id_token,
            google.auth.transport.requests.Request())
        email = token['email']
    except Exception as e:
        log.exception('fetching and decoding token')
        raise web.HTTPUnauthorized() from e

    db = request.app['db']
    users = [
        x async for x in db.select_and_fetchall(
            "SELECT * FROM users WHERE email = %s AND state = 'active';",
            email)
    ]

    if len(users) != 1:
        raise web.HTTPUnauthorized()
    user = users[0]

    session_id = await create_session(db, user['id'], max_age_secs=None)

    return web.json_response({
        'token': session_id,
        'username': user['username']
    })
Beispiel #4
0
def oauth2callback():
  # Specify the state when creating the flow in the callback so that it can
  # verified in the authorization server response.
  state = flask.session['state']

  try:
    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)
    flow.redirect_uri = flask.url_for('youtube_auth.oauth2callback', _external=True)

    # Use the authorization server's response to fetch the OAuth 2.0 tokens.
    authorization_response = flask.request.url
    flow.fetch_token(authorization_response=authorization_response)

    # Store credentials in the session.
    # ACTION ITEM: In a production youtube_auth, you likely want to save these
    #              credentials in a persistent database instead.
    credentials = flow.credentials
    flask.session['youtube_credentials'] = credentials_to_dict(credentials)

    return flask.redirect(flask.url_for('spotify_auth.authorize'))

  except Exception as err:
    print('something broke: {0}'.format(err) )
    return "error"
Beispiel #5
0
def auth():
    logging.info('Log in by new user')

    code = request.args.get('code')
    flow.fetch_token(code=code)
    credentials = flow.credentials

    user = services.get_user_profile(credentials)
    user_id = user[u'resourceName']

    # Try to select user from database
    user = User.get_by_user_id(user_id)
    if not user:
        user = create_new_user(user_id, credentials)
        contact = services.find_contact(credentials)

        # Create new contact with name Test Contact
        if not contact:
            logging.info('Contact not found create new one')
            contact = services.create_create(credentials)

        user.contact_id = contact[u'resourceName']

    # Update refresh token if necessary
    if credentials.refresh_token and user.refresh_token != credentials.refresh_token:
        logging.info('New refresh token provided')
        user.refresh_token = credentials.refresh_token

    auth_key = str(uuid4())
    user.token = auth_key
    user.put()

    response = redirect('/')
    response.set_cookie(AUTH_KEY, auth_key)
    return response
Beispiel #6
0
def oauth2callback():
    # Specify the state when creating the flow in the callback so that it can
    # verified in the authorization server response.
    # state = flask.session['state']

    url = json.loads(request.data.decode('utf8'))['url']

    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        CLIENT_SECRETS_FILE, scopes=SCOPES)  # , state=state)
    flow.redirect_uri = CLIENT_AUTH_REDIRECT_TO

    # Use the authorization server's response to fetch the OAuth 2.0 tokens.
    authorization_response = url
    print('Authorization url is: ' + authorization_response, file=sys.stdout)
    flow.fetch_token(authorization_response=authorization_response)

    # Store credentials in the session.
    # ACTION ITEM: In a production app, you likely want to save these
    #              credentials in a persistent database instead.
    credentials = flow.credentials
    flask.session['credentials'] = credentials_to_dict(credentials)

    credentials_to_store = credentials_to_dict(credentials, True)
    r.hmset(credentials_to_store['token'], credentials_to_store)
    return flask.jsonify(credentials_to_store['token'])
Beispiel #7
0
def oauth2callback():
  # Specify the state when creating the flow in the callback so that it can
  # verified in the authorization server response.
  state = flask.session['state']
  accountname=flask.session['accountname']

  flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
      CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)
  flow.redirect_uri = flask.url_for('gdrive.oauth2callback',  _external=True)

  # Use the authorization server's response to fetch the OAuth 2.0 tokens.
  authorization_response = flask.request.url
  flow.fetch_token(authorization_response=authorization_response)

  # Store credentials in the session.
  # ACTION ITEM: In a production app, you likely want to save these
  #              credentials in a persistent database instead.
  credentials = flow.credentials
  idinfo = id_token.verify_oauth2_token(credentials.id_token, requests.Request(), credentials.client_id)
  accountname1 = idinfo['email']
  if(accountname!=accountname1):
      raise TypeError("The account authorized is not equal to the account asked for")

  flask.session['credentials.'+accountname] = credentials_to_dict(credentials)

  return flask.redirect(flask.url_for('gdrive.bucketinfo', accountname=base64.b64encode(accountname.encode('ascii')).decode('ascii')))
Beispiel #8
0
def callback():
    if request.method == 'GET':

        state = session['state']
        flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(constants.CLIENT_SECRETS_FILE, scopes=constants.SCOPES, state=state)
        flow.redirect_uri = url_for('callback', _external=True)

        # Fetch the OAuth 2.0 tokens.
        authorization_response = request.url
        flow.fetch_token(authorization_response=authorization_response)

        # Store credentials in the session.
        credentials = flow.credentials
        session['credentials'] = {
            'token': credentials.token,
            'refresh_token': credentials.refresh_token,
            'token_uri': credentials.token_uri,
            'client_id': credentials.client_id,
            'client_secret': credentials.client_secret,
            'scopes': credentials.scopes
        }
        session['jwt'] = credentials.id_token

        return redirect(url_for('profile'))
    else:
        return make_response(json.dumps({"Error": "Method not allowed"}), 405,
                             {"Content-Type": constants.json_type})
def auth():
    """

    Returns:

    """
    # Specify the state when creating the flow in the callback so that it can
    # verified in the authorization server response.
    state = flask.session['state']

    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        CLIENT_SECRETS_FILE, scopes=None, state=state)
    flow.redirect_uri = flask.url_for('google_auth.auth', _external=True)

    # Use the authorization server's response to fetch the OAuth 2.0 tokens.
    authorization_response = flask.request.url
    flow.fetch_token(authorization_response=authorization_response)

    # Store credentials in the session.
    # ACTION ITEM: In a production app, you likely want to save these
    #              credentials in a persistent database instead.
    credentials = flow.credentials
    flask.session['credentials'] = credentials_to_dict(credentials)

    # return flask.redirect(flask.url_for('a_collect_gmail.collect_mail'))
    return flask.redirect('/loading_page')
 def redirect():
     flow.fetch_token(authorization_response=flask.request.url)
     result = {
         'access_token': flow.credentials.token,
         'refresh_token': flow.credentials.refresh_token,
     }
     return result
Beispiel #11
0
def Melo(request):
    if request.user.is_authenticated:
        estado = request.GET.get("state")

        flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
            'playlist/client_secrets.json',
            scopes=['https://www.googleapis.com/auth/youtube'],
            state=estado)

        #flow.redirect_uri = 'http://127.0.0.1:8000'+reverse('melo') #LOCAL
        flow.redirect_uri = 'https://eplayt.com' + reverse('melo')  #REMOTO

        authorization_response = request.path
        flow.fetch_token(authorization_response=authorization_response +
                         '?state=' + str(request.GET.get("state")) + '&code=' +
                         str(request.GET.get("code")) +
                         '&scope=https://www.googleapis.com/auth/youtube')

        # Store the credentials in the session.
        # ACTION ITEM for developers:
        #     Store user's access and refresh tokens in your data store if
        #     incorporating this code into your real app.
        credentials = flow.credentials
        request.session['credentials'] = {
            'token': credentials.token,
            'refresh_token': credentials.refresh_token,
            'token_uri': credentials.token_uri,
            'client_id': credentials.client_id,
            'client_secret': credentials.client_secret,
            'scopes': credentials.scopes
        }
        #print("jeje, estas son mis credenciales",request.session['credentials'])
        return redirect(reverse("listas"))
    else:
        return redirect('/')
Beispiel #12
0
def upload(request):
    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        'client_secret.json', scopes=['https://www.googleapis.com/auth/drive'])
    flow.redirect_uri = 'http://127.0.0.1:8000/upload'
    authorization_response = request.build_absolute_uri()
    if "http:" in authorization_response:
        authorization_response = "https:" + authorization_response[5:]
    flow.fetch_token(authorization_response=authorization_response)
    credentials = flow.credentials
    request.session['credentials'] = {
        'token': credentials.token,
        'refresh_token': credentials.refresh_token,
        'token_uri': credentials.token_uri,
        'client_id': credentials.client_id,
        'client_secret': credentials.client_secret,
        'scopes': credentials.scopes
    }

    drive_service = build('drive', 'v3', credentials=credentials)
    file_metadata = {
        'name': 'saved_editorial.txt',  # name change acc to file 
        'mimeType': '*/*'
    }
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    media = MediaFileUpload(
        os.path.join(BASE_DIR, 'saved_editorial.txt'),  # correct file upload
        mimetype='*/*',
        resumable=True)
    file = drive_service.files().create(body=file_metadata,
                                        media_body=media,
                                        fields='id').execute()
    print('File ID: ' + file.get('id'))

    return render(request, 'upload.html')
Beispiel #13
0
def oauth2callback():
    # Specify the state when creating the flow in the callback so that it can
    # verified in the authorization server response.
    state = flask.session['state']

    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)
    tmp_url = flask.url_for('oauth2callback', _external=True)
    if "http:" in tmp_url:
        tmp_url = "https:" + tmp_url[5:]
    flow.redirect_uri = tmp_url

    # Use the authorization server's response to fetch the OAuth 2.0 tokens.
    tmp_url = flask.request.url
    if "http:" in tmp_url:
        tmp_url = "https:" + tmp_url[5:]
    authorization_response = tmp_url
    flow.fetch_token(authorization_response=authorization_response)

    # Store credentials in the session.
    # ACTION ITEM: In a production app, you likely want to save these
    #              credentials in a persistent database instead.
    credentials = flow.credentials
    credentials_to_database(credentials, session["user_id"])

    return flask.redirect("/")
Beispiel #14
0
def oauth2callback():
    # Specify the state when creating the flow in the callback so that it can
    # verified in the authorization server response.
    if 'state' in session:
        state = session['state']
        print("STATE: ", session['state'])
    flow = google_auth_oauthlib.flow.Flow.from_client_config(
        current_app.config.get('CLIENT_CONFIG_DATA'),
        scopes=current_app.config.get('SCOPES'),
        state=state
        )
    flow.redirect_uri = url_for('auth.oauth2callback', _external=True)

    # Use the authorization server's response to fetch the OAuth 2.0 tokens.
    authorization_response = request.url
    flow.fetch_token(authorization_response=authorization_response)

    # Store credentials in db
    credentials = flow.credentials
    mongo.db.google_credentials.insert_one(
        {
            '_id': session['user_id'],
            'token': credentials.token,
            'refresh_token': credentials.refresh_token,
            'token_uri': credentials.token_uri,
            'client_id': credentials.client_id,
            'client_secret': credentials.client_secret,
            'scopes': credentials.scopes,
        }
        )
    return redirect(url_for('main.index'))
Beispiel #15
0
def create_event(start_time_str,
                 summary,
                 duration,
                 code,
                 description=None,
                 location=None):
    creds = None

    auth_code = code

    flow.fetch_token(code=auth_code)
    creds = flow.credentials

    # if os.path.exists('token.json'): check locally if user info has already been authenticated
    #     creds = Credentials.from_authorized_user_file('token.json',SCOPES)
    # if not creds or not creds.valid:
    #     if creds and creds.expired and creds.refresh_token:
    #         creds.refresh(Request())
    #     else:
    #         flow = InstalledAppFlow.from_client_secrets_file(os.path.join(settings.BASE_DIR, 'login\\static\\login\\credentials.json'),SCOPES)
    #         creds = flow.run_local_server(port=0)
    #     with open('token.json','w') as token:
    #         token.write(creds.to_json())
    service = build('calendar', 'v3', credentials=creds)

    matches = list(datefinder.find_dates(start_time_str))
    if len(matches):
        start_time = matches[0]
        end_time = start_time + timedelta(minutes=int(duration))

        event = {
            'summary': summary,
            'location': location,
            'description': description,
            'start': {
                'dateTime': start_time.strftime("%Y-%m-%dT%H:%M:%S"),
                'timeZone': 'US/Eastern',
            },
            'end': {
                'dateTime': end_time.strftime("%Y-%m-%dT%H:%M:%S"),
                'timeZone': 'US/Eastern',
            },
            'reminders': {
                'useDefault':
                False,
                'overrides': [
                    {
                        'method': 'email',
                        'minutes': 24 * 60
                    },
                    {
                        'method': 'popup',
                        'minutes': 10
                    },
                ],
            },
        }

        result = service.events().insert(calendarId='primary',
                                         body=event).execute()
Beispiel #16
0
async def rest_callback(request):
    state = request.query['state']
    code = request.query['code']
    callback_port = request.query['callback_port']

    try:
        flow = get_flow(f'http://127.0.0.1:{callback_port}/oauth2callback',
                        state=state)
        flow.fetch_token(code=code)
        token = google.oauth2.id_token.verify_oauth2_token(
            flow.credentials.id_token,
            google.auth.transport.requests.Request())
        email = token['email']
    except Exception:
        log.exception('fetching and decoding token')
        raise web.HTTPUnauthorized()

    dbpool = request.app['dbpool']
    async with dbpool.acquire() as conn:
        async with conn.cursor() as cursor:
            await cursor.execute(
                "SELECT * FROM users WHERE email = %s AND state = 'active';",
                email)
            users = await cursor.fetchall()

    if len(users) != 1:
        raise web.HTTPUnauthorized()
    user = users[0]

    session_id = await create_session(dbpool, user['id'])

    return web.json_response({
        'token': session_id,
        'username': user['username']
    })
Beispiel #17
0
def oauth2callback():
    # Specify the state when creating the flow in the callback so that it can
    # verified in the authorization server response.
    state = flask.session['state']
    uid = flask.session['uid']

    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
      CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)
    flow.redirect_uri = flask.url_for('oauth2callback', _external=True)

    # Use the authorization server's response to fetch the OAuth 2.0 tokens.
    authorization_response = flask.request.url
    flow.fetch_token(authorization_response=authorization_response)

    # Store credentials in the session.
    # ACTION ITEM: In a production app, you likely want to save these
    #              credentials in a persistent database instead.
    credentials = flow.credentials
    credentials_dict = credentials_to_dict(credentials)
    flask.session['credentials'] = credentials_dict
    logging.info(f"Current credentials are {credentials_dict}")
    sql_handler.save_token(uid, credentials_dict)
    response = flask.jsonify(credentials_dict)
    response.status_code = 200
    return response
Beispiel #18
0
def oauth2callback():
    # Specify the state when creating the flow in the callback so that it can
    # verified in the authorization server response.
    state = flask.session['state']

    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)
    flow.redirect_uri = flask.url_for('oauth2callback', _external=True)

    # Use the authorization server's response to fetch the OAuth 2.0 tokens.
    authorization_response = flask.request.url
    flow.fetch_token(authorization_response=authorization_response)

    # Store credentials in the session.
    # ACTION ITEM: In a production app, you likely want to save these
    #              credentials in a persistent database instead.
    credentials = flow.credentials
    flask.session['credentials'] = credentials_to_dict(credentials)
    user_id = flask.session['user_id']

    set_credentials(user_id, credentials)
    line_bot_api.push_message(user_id, TextSendMessage(text="已成功連結Google帳號"))
    line_bot_api.push_message(
        user_id,
        TextSendMessage(
            text=
            "歡迎使用GC Helper(Beta)\n我可以幫你將活動紀錄在Google日曆上喔!\n\n範例格式:\n6/3聚餐,在一二三餐廳\n2017/6/3下午20:00聚餐\n06.03聚餐,在一二三餐廳\n6月3日聚餐,在一二三餐廳\n六月三日聚餐,在一二三餐廳\n六月三號聚餐,在一二三餐廳\n明天下午20:00聚餐"
        ))
    return "已連結,請返回上一頁"
def callback(state):
    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        CLIENT_SECRET, scopes=SCOPES, state=state)
    flow.redirect_uri = redirect_url
    authorization_response = flask.request.url
    flow.fetch_token(authorization_response=authorization_response)
    return flow.credentials
Beispiel #20
0
def oauth2callback():
  # Specify the state when creating the flow in the callback so that it can
  # verify the authorization server response.
  state = flask.session['state']
  flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
      CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)
  flow.redirect_uri = flask.url_for('oauth2callback', _external=True)

  # Use the authorization server's response to fetch the OAuth 2.0 tokens.
  authorization_response = flask.request.url
  flow.fetch_token(authorization_response=authorization_response)

  # Store the credentials in the session.
  # ACTION ITEM for developers:
  #     Store user's access and refresh tokens in your data store if
  #     incorporating this code into your real app.
  credentials = flow.credentials
  flask.session['credentials'] = {
      'token': credentials.token,
      'refresh_token': credentials.refresh_token,
      'token_uri': credentials.token_uri,
      'client_id': credentials.client_id,
      'client_secret': credentials.client_secret,
      'scopes': credentials.scopes
  }

  return flask.redirect(flask.url_for('index'))
Beispiel #21
0
def oauth2callback():
    # Specify the state when creating the flow in the callback so that it can
    # verify the authorization server response.
    state = flask.session['state']
    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)
    flow.redirect_uri = flask.url_for('oauth2callback', _external=True)

    # Use the authorization server's response to fetch the OAuth 2.0 tokens.
    authorization_response = flask.request.url
    flow.fetch_token(authorization_response=authorization_response)

    # Store the credentials in the session.
    # ACTION ITEM for developers:
    #     Store user's access and refresh tokens in your data store if
    #     incorporating this code into your real app.
    credentials = flow.credentials
    flask.session['credentials'] = {
        'token': credentials.token,
        'refresh_token': credentials.refresh_token,
        'token_uri': credentials.token_uri,
        'client_id': credentials.client_id,
        'client_secret': credentials.client_secret,
        'scopes': credentials.scopes
    }

    return flask.redirect(flask.url_for('admin'))
Beispiel #22
0
def oauth2_callback():
    state = request.args.get('state', None)
    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        JSON_FILE, scopes=API_SCOPE, state=state)
    flow.redirect_uri = REDIRECT_URI
    flow.fetch_token(
        authorization_response=request.url.replace('http://', 'https://'))
    credentials = flow.credentials
    auth = {
        'token':
        credentials.token,
        'refresh_token':
        credentials.refresh_token,
        'id_token':
        credentials.id_token,
        'token_uri':
        credentials.token_uri,
        'client_id':
        credentials.client_id,
        'client_secret':
        credentials.client_secret,
        'scopes':
        credentials.scopes,
        'expiry':
        datetime.datetime.strftime(credentials.expiry, '%Y-%m-%d %H:%M:%S')
    }
    id = str(uuid4())
    db[id] = auth
    return id
Beispiel #23
0
    def oauth2_callback():
        import google.oauth2.credentials
        import google_auth_oauthlib.flow
        flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
            '/%s/client_secret.json' %
            os.path.dirname(os.path.abspath(__file__)),
            scopes=['profile'])
        flow.redirect_uri = url_for('oauth2_callback', _external=True)

        authorization_response = request.url
        flow.fetch_token(authorization_response=authorization_response)
        credentials = flow.credentials

        from googleapiclient.discovery import build
        people_service = build(serviceName='people',
                               version='v1',
                               credentials=credentials)
        profile = people_service.people().get(resourceName='people/me',
                                              personFields='names').execute()

        resource_name = profile['resourceName']
        display_name = [
            name for name in profile['names']
            if name['metadata']['primary'] is True
        ][0]['displayName']

        user = User.query.filter_by(social_id=resource_name).first()
        if not user:
            user = User(social_id=resource_name, name=display_name)
            with app.app_context():
                db.session.add(user)
                db.session.commit()
        user = User.query.filter_by(social_id=resource_name).first()
        login_user(user)
        return redirect(url_for('index'))
Beispiel #24
0
def oauth2callback():
    # Specify the state when creating the flow in the callback so that it can
    # verify the authorization server response.
    state = flask.session['state']
    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)
    flow.redirect_uri = flask.url_for('oauth2callback',
                                      _external=True,
                                      _scheme='https')

    # Use the authorization server's response to fetch the OAuth 2.0 tokens.
    authorization_response = flask.request.url
    authorization_response = authorization_response.replace(
        "http://", "https://")

    flow.fetch_token(authorization_response=authorization_response)

    credentials = flow.credentials

    client_refresh = {
        'email': client_data["email"],
        'token': credentials.token,
        'token_uri': credentials.token_uri,
        'client_id': credentials.client_id,
        'client_secret': credentials.client_secret,
        'scopes': credentials.scopes
    }
    if credentials.refresh_token:
        client_refresh["refresh_token"] = credentials.refresh_token

    migration.clientUpdate(client_refresh)

    return flask.redirect(flask.url_for('index'))
Beispiel #25
0
def oauth2callback():
    # Specify the state when creating the flow in the callback so that it can
    # verified in the authorization server response.
    state = flask.session['state']

    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)
    tmp_url = flask.url_for('oauth2callback', _external=True)
    if "http:" in tmp_url:
        tmp_url = "https:" + tmp_url[5:]
    flow.redirect_uri = tmp_url

    # Use the authorization server's response to fetch the OAuth 2.0 tokens.
    tmp_url = flask.request.url
    if "http:" in tmp_url:
        tmp_url = "https:" + tmp_url[5:]
    authorization_response = tmp_url
    try:
        flow.fetch_token(authorization_response=authorization_response)
    except:
        return render_template("apology.html", message="Please grant access to the google calendar.")

    # Store the credentials in venn.db
    credentials = flow.credentials
    credentials_to_database(credentials, session["user_id"])

    if session.get("next") is None:
        return redirect("/")
    else:
        return redirect(session.get("next"))
Beispiel #26
0
def oauth2callback():
    # Specify the state when creating the flow in the callback so that it can
    # verified in the authorization server response.
    state = session['state']

    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)
    flow.redirect_uri = url_for('oauth2callback', _external=True)

    # Use the authorization server's response to fetch the OAuth 2.0 tokens.
    authorization_response = request.url
    flow.fetch_token(authorization_response=authorization_response)

    # Store credentials in the session.
    # TODO: In a production app, you likely want to save these
    #              credentials in a persistent database instead.
    credentials = flow.credentials
    print("Credentials are of type: ", type(credentials))
    session['credentials'] = credentials_to_dict(credentials)

    # #Add new user to database if not there already
    # db.session.add(new_user_created)
    # db.session.commit()

    print(session['credentials'])

    #Update database with credentials
    # TODO: Encrypt credentials prior to adding to database
    return redirect(url_for('test_api_request'))
Beispiel #27
0
def oauth2callback():
    # Specify the state when creating the flow in the callback so that it can
    # verified in the authorization server response.
    state = current_user.student_profile.cal_state

    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)
    flow.redirect_uri = url_for('student.oauth2callback', _external=True)

    # Use the authorization server's response to fetch the OAuth 2.0 tokens.
    authorization_response = flask.request.url
    flow.fetch_token(authorization_response=authorization_response)

    # Store credentials in database
    credentials = flow.credentials
    current_user.student_profile.cal_token = credentials.token
    current_user.student_profile.cal_refresh_token = credentials.refresh_token
    current_user.student_profile.cal_token_uri = credentials.token_uri
    current_user.student_profile.cal_client_id = credentials.client_id
    current_user.student_profile.cal_client_secret = credentials.client_secret
    current_user.student_profile.cal_scopes = credentials.scopes
    current_user.student_profile.cal_state = state
    db.session.add(current_user)
    db.session.commit()
    add_pending_events()
    return redirect(url_for('student.calendar'))
Beispiel #28
0
def oauth2callback():
    # Specify the state when creating the flow in the callback so that it can
    # verified in the authorization server response.
    state = flask.session['state']

    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        constants.CLIENT_SECRETS_FILE, scopes=constants.SCOPES, state=state)
    flow.redirect_uri = flask.url_for('utils_api.oauth2callback',
                                      _external=True)

    # Use the authorization server's response to fetch the OAuth 2.0 tokens.
    authorization_response = flask.request.url
    flow.fetch_token(authorization_response=authorization_response)

    # Store credentials in the session.
    # ACTION ITEM: In a production app, you likely want to save these
    #                            credentials in a persistent database instead.
    credentials = flow.credentials
    flask.session['credentials'] = _credentials_to_dict(credentials)
    print('new token is {}'.format(credentials.to_json))
    constants.ACCESS_TOKEN = str(credentials.to_json)
    with open(constants.ACCESS_TOKEN_PATH, 'w') as f:
        json.dump(credentials.token, f)
        f.flush()

    return flask.redirect(flask.url_for('utils_api.test_api_request'))
Beispiel #29
0
def get_credentials():
    # Retrieve parameters. As request_url is sent as a url, we have to parse it.
    # Else the whole request will be sent to another location.
    state = request.args.get('state')
    request_url = urlparse(request.args.get('url')).geturl()

    # Specify the state when creating the flow in the callback so that it can
    # verified in the authorization server response.
    logger.info("Received request to retrieve user credentials")
    logger.debug("With url of: " + request_url)
    logger.debug("and redirect address of: " + DRIVE_REDIRECT_URI)
    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        DRIVE_CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)

    flow.redirect_uri = DRIVE_REDIRECT_URI

    # Use the authorization server's response to fetch the OAuth 2.0 tokens.
    authorization_response = request_url
    flow.fetch_token(authorization_response=authorization_response)

    # Store credentials in the session.
    # TODO: In a production version, id likely want to save these
    #              credentials in a persistent database instead.
    credentials = flow.credentials
    session['credentials'] = credentials_to_dict(credentials)

    # TODO: encrypt response credentials
    return json.dumps({
        "status": "200",
        "credentials": credentials_to_dict(credentials)
    })
Beispiel #30
0
    def __init__(self):
        # TODO вынести эту хуйню из init

        # Disable OAuthlib's HTTPS verification when running locally.
        # *DO NOT* leave this option enabled in production.
        os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'

        # Get credentials and create an API client
        flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
            self.YOUTUBE_CLIENT_SECRETS_FILE,
            self.YOUTUBE_SCOPES,
            redirect_uri='urn:ietf:wg:oauth:2.0:oob'
        )

        auth_url, _ = flow.authorization_url()
        webbrowser.open(auth_url, new=0, autoraise=True)  # redirect to url

        code = input('Enter the authorization code: ')
        flow.fetch_token(code=code)

        youtube = googleapiclient.discovery.build(
            self.YOUTUBE_SERVICE_NAME,
            self.YOUTUBE_API_VERSION,
            credentials=flow.credentials
        )

        self.live_broadcasts = YoutubeLiveBroadcasts(youtube)
        self.youtube_live_chat = YoutubeLiveChatMessage(youtube)
Beispiel #31
0
def oauth2callback():
    # Specify the state when creating the flow in the callback so that it can
    # verified in the authorization server response.

    state = flask.session['state']

    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)

    flow.redirect_uri = flask.url_for('oauth2callback', _external=True)

    # Use the authorization server's response to fetch the OAuth 2.0 tokens.
    authorization_response = flask.request.url
    authorization_response = authorization_response.replace('http', 'https')

    flow.fetch_token(authorization_response=authorization_response)

    # Store credentials in the session.
    # ACTION ITEM: In a production app, you likely want to save these
    #              credentials in a persistent database instead.
    credentials = flow.credentials

    flask.session['credentials'] = credentials_to_dict(credentials)

    return flask.redirect(flask.url_for('test_api_request'))
Beispiel #32
0
def oauth2callback():
    state = session['state']
    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)
    flow.redirect_uri = url_for('oauth2callback', _external=True)
    flow.fetch_token(authorization_response=request.url)

    save_credentials(flow.credentials)
    return redirect(url_for('static', filename='dashboard.html'))
def oauth2callback():
    state = flask.session['state']

    flow = get_flow()
    flow.redirect_uri = flask.url_for('oauth2callback', _external=True)

    authorization_response = flask.request.url
    flow.fetch_token(authorization_response=authorization_response)
    credentials = flow.credentials
    flask.session['credentials'] = credentials_to_dict(credentials)
    return flask.redirect(flask.url_for('record_api_tokens'))
Beispiel #34
0
def google_callback():
    hashid = session["ggl:form"]
    del session["ggl:form"]
    if hashid != request.args.get("state"):
        return script_error("oauth-failed")

    form = Form.get_with(hashid=hashid)

    flow = google_auth_oauthlib.flow.Flow.from_client_config(
        settings.GOOGLE_CLIENT_CONFIG,
        state=hashid,
        scopes=["https://www.googleapis.com/auth/drive.file"],
    )

    flow.redirect_uri = url_for("google_callback", _external=True, _scheme="https")

    flow.fetch_token(authorization_response=request.url.replace("http://", "https://"))

    plugin = Plugin(form_id=form.id, kind=PluginKind.google_sheets)
    plugin.access_token = json.dumps(
        {
            "token": flow.credentials.token,
            "refresh_token": flow.credentials.refresh_token,
            "token_uri": flow.credentials.token_uri,
            "id_token": flow.credentials.id_token,
            "client_id": flow.credentials.client_id,
            "client_secret": flow.credentials.client_secret,
        }
    )

    spreadsheet_title = (
        form.name
        if form.name
        else f"{settings.SERVICE_NAME} submissions for {form.hashid}"
    )[:128]

    google_creds = json.loads(plugin.access_token)
    credentials = google.oauth2.credentials.Credentials(**google_creds)
    spreadsheet_id, worksheet_id = create_google_sheet(
        form, spreadsheet_title, credentials
    )

    plugin.plugin_data = {
        "spreadsheet_id": spreadsheet_id,
        "worksheet_id": worksheet_id,
    }
    DB.session.add(plugin)
    DB.session.commit()

    return script_data({"spreadsheet_id": spreadsheet_id})
Beispiel #35
0
def google_nisseoauthcallback(store: OAuthStore):
    # Specify the state when creating the flow in the callback so that it can
    # verified in the authorization server response.
    state = store.get_state()
    flow = get_flow(state=state, token_updater=store.set_credentials)
    flow.redirect_uri = flask.url_for(
        'nisseoauthcallback',
        _external=True,
        _scheme=get_request_scheme())

    # Use the authorization server's response to fetch the OAuth 2.0 tokens.
    authorization_response = flask.url_for(
        'nisseoauthcallback', _external=True, _scheme=get_request_scheme(), **flask.request.values)
    flow.fetch_token(authorization_response=authorization_response)
    # Store credentials.
    # ACTION ITEM: In a production app, you likely want to save these
    #              credentials in a persistent database instead.
    store.set_credentials(flow.credentials)
    return ("OK", 200)
Beispiel #36
0
def oauth2callback():
    # Specify the state when creating the flow in the callback so that it can
    # verified in the authorization server response.
    state = session['state']

    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)
    flow.redirect_uri = 'http://yourjobtracker.com/oauth2callback'

    # Use the authorization server's response to fetch the OAuth 2.0 tokens.
    authorization_response = request.url
    flow.fetch_token(authorization_response=authorization_response)

    # Store credentials in the session.
    # ACTION ITEM: In a production app, you likely want to save these
    #              credentials in a persistent database instead.
    credentials = flow.credentials
    session['credentials'] = credentials_to_dict(credentials)

    return redirect('/dashboard/jobs')