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