コード例 #1
0
ファイル: views.py プロジェクト: tasnim07/YoutubeAPI
def google_login_callback(request):
	code = request.GET.get('code')
	if not code:
		return HttpResponse("Oops! We couldn't authenticate!")

	# FIXME: I have hard-coded the client secrets file path for now.
	flow = flow_from_clientsecrets('/Users/lxidd/Desktop/client_secrets.json',
                                   scope='https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/userinfo.email',
                                   redirect_uri='http://localhost:8000/youtube/callback')
	credentials = flow.step2_exchange(code)
	access_token = credentials.access_token

	#Get the user email address.
	params = {
		'access_token': access_token
	}
	r = requests.get('https://www.googleapis.com/oauth2/v2/userinfo', params=params)
	content = r.json()
	email = content.get('email')

	try:
		google_user = GoogleAccount.objects.get(access_token=access_token)
		user = google_user.user
	except:
		# New user
		user = User(username=email.split('@')[0], password='#!', email=email)
		user.save()
		google_user = GoogleAccount(user=user, access_token=access_token)
		google_user.save()

	user.backend = 'django.contrib.auth.backends.ModelBackend'
	login(request, user)

	return redirect(reverse('video-list'))
コード例 #2
0
ファイル: views.py プロジェクト: mihasya/gdata_sample
def add_token(request):
    #set the scope to contacts API
    cp_scope = gdata.service.lookup_scopes('cp')

    gd_client = gdata.base.service.GBaseService()
    gd_client.SetOAuthInputParameters(
        gdata.auth.OAuthSignatureMethod.RSA_SHA1,
        settings.GDATA_CREDS['key'], 
        consumer_secret=settings.GDATA_CREDS['secret'],
        rsa_key=settings.GDATA_CREDS['rsa_key']
    )
    goog_url = ''
    if not (request.GET.has_key('oauth_token')): #we don't have a token yet
        #create a request token with the contacts api scope
        rt = gd_client.FetchOAuthRequestToken(
            scopes=cp_scope
        )
        #store the token's secret in a session variable
        request.session['token_secret'] = rt.secret
        
        #get an authorization URL for our token from gdata
        gd_client.SetOAuthToken(rt)
        goog_url = gd_client.GenerateOAuthAuthorizationURL()\
                                +'&oauth_callback='+request.build_absolute_uri()
        params = {
            'goog_url': goog_url,
        }

        return render_to_response('add_token.html', params, 
                                        context_instance=RequestContext(request))

        
    else: #we've been redirected back by google with the auth token as a query parameter
        #create a request token object from the URL (converts the query param into a token object)
        rt = gdata.auth.OAuthTokenFromUrl(url=request.build_absolute_uri())
        #set the secret to what we saved above, before we went to Google
        rt.secret = request.session['token_secret']
        #set the scope again
        rt.scopes = cp_scope;
        #upgrade our request token to an access token (where the money at)
        gd_client.UpgradeToOAuthAccessToken(authorized_request_token=rt)
        """this part is confusing: we have to retrieve the authorized access 
        token by doing a lookup I have submitted an issue and a patch to the 
        Python client to make UpgradeToOAuthAccessToken return the authorized 
        token see: 
        http://code.google.com/p/gdata-python-client/issues/detail?id=213"""
        at = gd_client.token_store.find_token(rt.scopes[0])
        """save! how you store the data is arbitrary. I just pickle the token 
        object, though you could probably store the token_key and token_secret 
        individually and reconstruct the object later. (see views.home)"""
        ga = GoogleAccount() #my model
        ga.user = request.user
        ga.data = Pickle.dumps(at)
        ga.save()
        request.user.message_set.create(message="Your Google account has been "+
            "successfully added.")
        return HttpResponseRedirect('/oauth')
コード例 #3
0
ファイル: google_views.py プロジェクト: rcemmett/instafeed
def google_callback_code(request):
    response = {}
    response["authorized"] = request.GET.get("error") != "access_denied"
    if response["authorized"]:
        response["code"] = request.GET.get("code")
        refresh_token = request_refresh_token(response["code"])
        account = GoogleAccount(user_id=request.user, access_token=refresh_token)
        account.save()
    return HttpResponseRedirect("/feed/")
コード例 #4
0
ファイル: google_views.py プロジェクト: rcemmett/instafeed
def request_token(request):
    account = GoogleAccount.get_account(request.user.id)
    response = {}
    if not account:
        response["success"] = False
        response["account"] = False
        response["message"] = "No g+ account for user, call google_signup"
        return HttpResponse(json.dumps(response), mimetype="application/json")
    refresh_token = account.access_token  # really is refresh token
    post = api.request_token(refresh_token)
    r = requests.post(api.TOKEN_URL, data=post).text
    r_json = json.loads(r)
    if r_json.get("error") is not None:
        response["success"] = False
        response["account"] = True
        response["message"] = "Google + rejected your credentials"
    else:
        request.session["google_token"] = r_json["access_token"]
        request.session["google_token_expires"] = r_json["expires_in"] + time.time()
        response["success"] = True
        response["account"] = True
        response["message"] = "Access token stored in session"
    return HttpResponse(json.dumps(response), mimetype="application/json")