Пример #1
0
def get_authenticated_service(user):
    """
    让用户到google上进行认证,返回认证后的http服务
    :param request:
    :return:
    """
    storage = Storage(CredentialsModel, 'id', user, 'credential')
    credential = storage.get()

    if credential is None or credential.invalid is True:
        result = None
    else:
        SETTING_FILE = 'production'
        # 如果是VPS中运行,则不使用代理
        if SETTING_FILE == 'production':
            http = httplib2.Http()
            http = credential.authorize(http)

        # 如果是本地运行,则使用代理,貌似使用socks5代理会出错,尝试使用http代理
        if SETTING_FILE == 'local':
            myproxy = httplib2.ProxyInfo(
                proxy_type=httplib2.socks.PROXY_TYPE_HTTP,
                proxy_host='127.0.0.1',
                proxy_port=8118)
            http = httplib2.Http(proxy_info=myproxy)
            http = credential.authorize(http)

        service = build(YOUTUBE_API_SERVICE_NAME,
                        YOUTUBE_API_VERSION,
                        http=http)
        result = service
    return result
Пример #2
0
def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    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,
                                   'gmail-python-quickstart.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else:  # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials
Пример #3
0
def get_authenticated_service(user):
    """
    让用户到google上进行认证,返回认证后的http服务
    :param request:
    :return:
    """
    storage = Storage(CredentialsModel, 'id', user, 'credential')
    credential = storage.get()

    if credential is None or credential.invalid is True:
        result = None
    else:
        SETTING_FILE = 'production'
        # 如果是VPS中运行,则不使用代理
        if SETTING_FILE == 'production':
            http = httplib2.Http()
            http = credential.authorize(http)

        # 如果是本地运行,则使用代理,貌似使用socks5代理会出错,尝试使用http代理
        if SETTING_FILE == 'local':
            myproxy = httplib2.ProxyInfo(
                proxy_type=httplib2.socks.PROXY_TYPE_HTTP,
                proxy_host='127.0.0.1', proxy_port=8118)
            http = httplib2.Http(proxy_info=myproxy)
            http = credential.authorize(http)

        service = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
                        http=http)
        result = service
    return result
    def get_credentials(options, cache_location=None):
        """
        Get credentials object needed for constructing GooglePlayAPi.
        There are a coupe of ways to get the credentials:
        - using a service
          {'service': {'json': path-to-json.json}}
          or
          {'service': {'p12': path-to-p12.p12}}
        - using oauth
          {'oauth': {'json': path-to-client-secret-json.json}}
          or
          {'oauth': {'client-id': your-client-id, 'client-secret': your-client-secret}

        :param options: the authentication options
        :param cache_location: (optional) if using oauth it'll store the credentials in a file
        :return: the credentials object
        """
        credentials = None
        flow = None

        scope = 'https://www.googleapis.com/auth/androidpublisher'
        redirect_uri = 'urn:ietf:wg:oauth:2.0:oob'

        if 'service' in options and 'json' in options['service']:
            credentials = ServiceAccountCredentials.from_json_keyfile_name(
                    options['service']['json'],
                    [scope])
        if 'service' in options and 'p12' in options['service']:
            credentials = ServiceAccountCredentials.from_p12_keyfile(
                    options['p12'],
                    [scope])
        if 'oauth' in options and 'json' in options['oauth']:
            flow = flow_from_clientsecrets(
                    options['oauth']['json'],
                    scope=scope,
                    redirect_uri=redirect_uri)
        if 'oauth' in options is True and 'client-id' in options['oauth'] and 'client-secret' in options['oauth']:
            flow = OAuth2WebServerFlow(
                    client_id=options['oauth']['client-id'],
                    client_secret=options['oauth']['client-secret'],
                    scope=scope,
                    redirect_uri=redirect_uri)

        if flow is not None:
            if cache_location is None:
                cache_location = os.path.join(os.getenv("HOME"), ".gplay", "credentials.dat")

            storage = Storage(cache_location)
            credentials = storage.get()
            if credentials is None or credentials.invalid:
                credentials = tools.run_flow(flow, storage)

        if credentials is None:
            exit(ValueError('missing credentials'))

        return credentials
Пример #5
0
def reauthorize_view(request):
    user = request.user
    storage = Storage(CredentialsModel, 'id', user, 'credential')
    if storage:
        storage.delete()
        text = '删除本地认证文件!'

    else:
        text = '在本地没有对应的storage文件,未能删除本地认证文件'

    return render_to_response('result.html', {'text': text})
Пример #6
0
def reauthorize_view(request):
    user = request.user
    storage = Storage(CredentialsModel, 'id', user, 'credential')
    if storage:
        storage.delete()
        text = '删除本地认证文件!'

    else:
        text = '在本地没有对应的storage文件,未能删除本地认证文件'

    return render_to_response('result.html',
                              {'text': text}
                              )
Пример #7
0
def main():
    if CLIENT_SECRETS is None:
        raise ValueError("You need to provide a file.")

    FLOW = flow_from_clientsecrets(
        CLIENT_SECRETS,
        scope='https://www.googleapis.com/auth/analytics.readonly',
        message=MISSING_CLIENT_SECRETS_MESSAGE)

    s = Storage()
    s.put = lambda *a, **kw: None
    credentials = run(FLOW, s)

    bits = dict([(str(name), str(getattr(credentials, name)))
                 for name in ('access_token', 'client_id', 'client_secret',
                              'refresh_token', 'token_uri', 'user_agent')])
    bits['token_expiry'] = credentials.token_expiry.strftime(EXPIRY_FORMAT)
    print 'GOOGLE_ANALYTICS_CREDENTIALS = ',
    pprint.pprint(bits)
def main():
    if CLIENT_SECRETS is None:
        raise ValueError("You need to provide a file.")

    FLOW = flow_from_clientsecrets(
        CLIENT_SECRETS,
        scope='https://www.googleapis.com/auth/analytics.readonly',
        message=MISSING_CLIENT_SECRETS_MESSAGE)

    s = Storage()
    s.put = lambda *a, **kw: None
    credentials = run(FLOW, s)

    bits = dict([(str(name), str(getattr(credentials, name))) for name in
                ('access_token', 'client_id', 'client_secret',
                'refresh_token', 'token_uri',
                'user_agent')])
    bits['token_expiry'] = credentials.token_expiry.strftime(EXPIRY_FORMAT)
    print 'GOOGLE_ANALYTICS_CREDENTIALS = ',
    pprint.pprint(bits)
Пример #9
0
def oauth2callback_view(request):
    """
    在google上确认授权之后,会转到这个页面,保存获取到的认证码
    :param request:
    :return:
    """
    user = request.user
    # there will be some error show I ignore the validate part
    # if not xsrfutil.validate_token(
    # settings.SECRET_KEY, request.REQUEST['state'], user):
    # return HttpResponseBadRequest()

    # I have to use socks5 proxy to access google, because I live in China
    # http = httplib2.Http(proxy_info=httplib2.ProxyInfo(
    # httplib2.socks.PROXY_TYPE_SOCKS5, '127.0.0.1', 8115))
    flow = FlowModel.objects.get(id=user).flow
    # To exchange an authorization code for an access token
    credential = flow.step2_exchange(request.REQUEST)
    # 保存认证
    storage = Storage(CredentialsModel, 'id', user, 'credential')
    storage.put(credential)
    return HttpResponseRedirect("/oauth2")
Пример #10
0
def oauth2callback_view(request):
    """
    在google上确认授权之后,会转到这个页面,保存获取到的认证码
    :param request:
    :return:
    """
    user = request.user
    # there will be some error show I ignore the validate part
    # if not xsrfutil.validate_token(
    # settings.SECRET_KEY, request.REQUEST['state'], user):
    # return HttpResponseBadRequest()

    # I have to use socks5 proxy to access google, because I live in China
    # http = httplib2.Http(proxy_info=httplib2.ProxyInfo(
    # httplib2.socks.PROXY_TYPE_SOCKS5, '127.0.0.1', 8115))
    flow = FlowModel.objects.get(id=user).flow
    # To exchange an authorization code for an access token
    credential = flow.step2_exchange(request.REQUEST)
    # 保存认证
    storage = Storage(CredentialsModel, 'id', user, 'credential')
    storage.put(credential)
    return HttpResponseRedirect("/oauth2")
Пример #11
0
from oauth2client.client import flow_from_clientsecrets, Storage, EXPIRY_FORMAT
from oauth2client.tools import run

gflags.DEFINE_string('secrets', None, 'Client secret JSON filename', short_name='f')

gflags.FLAGS(sys.argv)

CLIENT_SECRETS = gflags.FLAGS.secrets

MISSING_CLIENT_SECRETS_MESSAGE = ("%s is missing or doesn't contain secrets "
                                  "for a web application" % CLIENT_SECRETS)

FLOW = flow_from_clientsecrets(
    CLIENT_SECRETS,
    scope='https://www.googleapis.com/auth/analytics.readonly',
    message=MISSING_CLIENT_SECRETS_MESSAGE)


s = Storage()
s.put = lambda *a, **kw: None
credentials = run(FLOW, s)

bits = dict([(str(name), str(getattr(credentials, name))) for name in
             ('access_token', 'client_id', 'client_secret',
              'refresh_token', 'token_uri',
              'user_agent')])
bits['token_expiry'] = credentials.token_expiry.strftime(EXPIRY_FORMAT)
print 'GOOGLE_ANALYTICS_CREDENTIALS = ',
pprint.pprint(bits)

Пример #12
0
from oauth2client.client import flow_from_clientsecrets, Storage, EXPIRY_FORMAT
from oauth2client.tools import run

gflags.DEFINE_string('secrets',
                     None,
                     'Client secret JSON filename',
                     short_name='f')

gflags.FLAGS(sys.argv)

CLIENT_SECRETS = gflags.FLAGS.secrets

MISSING_CLIENT_SECRETS_MESSAGE = ("%s is missing or doesn't contain secrets "
                                  "for a web application" % CLIENT_SECRETS)

FLOW = flow_from_clientsecrets(
    CLIENT_SECRETS,
    scope='https://www.googleapis.com/auth/analytics.readonly',
    message=MISSING_CLIENT_SECRETS_MESSAGE)

s = Storage()
s.put = lambda *a, **kw: None
credentials = run(FLOW, s)

bits = dict([(str(name), str(getattr(credentials, name)))
             for name in ('access_token', 'client_id', 'client_secret',
                          'refresh_token', 'token_uri', 'user_agent')])
bits['token_expiry'] = credentials.token_expiry.strftime(EXPIRY_FORMAT)
print 'GOOGLE_ANALYTICS_CREDENTIALS = ',
pprint.pprint(bits)
Пример #13
0
import httplib2
import numpy as np
import oauth2client
import requests
from oauth2client.client import OAuth2WebServerFlow, Storage

from bson import json_util
from flask import Flask, Response, jsonify, redirect, request, url_for
from flask_login import *
from pymongo import MongoClient

global_ml_queue = []

# Initialize a storage object
storage = Storage('a_credentials_file')

# Single user auth credentials
http = httplib2.Http()

# Flask configuration
app = Flask(__name__)

# Setup logging
logging.basicConfig(filename='mvp.log', level=logging.DEBUG)

# Setup a DB incase we need this to store YouTube creds.
database = "localhost:27017"
client = MongoClient(database)
db = client.beta
threads = []