def test_bad_positional(self): # Need 3 positional arguments. with self.assertRaises(TypeError): xsrfutil.validate_token(None, None) # At most 3 positional arguments. with self.assertRaises(TypeError): xsrfutil.validate_token(None, None, None, None)
def get(self): key = self.config['webapp2_extras.sessions']['secret_key'] redirect_url = str(self.request.get('redirect')) if self.me is not None: token = str(self.request.get('token')) xsrfutil.validate_token(key, token, self.me.user_id(), action_id=redirect_url) self.auth.unset_session() # Avoid data: URI redirects. if not redirect_url.startswith(('http://', 'https://', '/')): self.abort(404) return self.redirect(redirect_url)
def auth_return(request): if not xsrfutil.validate_token(settings.SECRET_KEY, request.GET['state'].encode('UTF-8'), request.user): return HttpResponseBadRequest() credential = FLOW.step2_exchange(request.GET) storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') storage.put(credential) return HttpResponseRedirect("/")
def test_token_length_differs_from_generated(self): token_time = 123456789 # Make sure it isn't too old. curr_time = token_time + xsrfutil.DEFAULT_TIMEOUT_SECS - 1 key = object() user_id = object() action_id = object() token = base64.b64encode(_helpers._to_bytes(str(token_time))) generated_token = b'a' # Make sure the token length comparison will fail. self.assertNotEqual(len(token), len(generated_token)) with mock.patch('oauth2client.contrib.xsrfutil.generate_token', return_value=generated_token) as gen_tok: self.assertFalse( xsrfutil.validate_token(key, token, user_id, current_time=curr_time, action_id=action_id)) gen_tok.assert_called_once_with(key, user_id, action_id=action_id, when=token_time)
def auth_return(request): if not xsrfutil.validate_token(SECRET_KEY, request.GET.get('state').encode("ascii"), request.user): return HttpResponseBadRequest('XSRF token could not be validated') credential = FLOW.step2_exchange(request.GET) storage = Storage(CredentialsModel, 'id', request.user, 'credential') storage.put(credential) return HttpResponseRedirect('/admin/haslerentries/entryset/')
def auth_return(request): print(request.GET) if not xsrfutil.validate_token(settings.SECRET_KEY, request.GET['state'].encode('UTF-8'), request.user): return HttpResponseBadRequest() credential = FLOW.step2_exchange(request.GET) http = httplib2.Http() http = credential.authorize(http) service = build("gmail", "v1", http=http) try: label_object = { 'messageListVisibility': "show", 'name': "IFP", 'labelListVisibility': "labelShow" } label = service.users().labels().create(userId='me', body=label_object).execute() print(label['id']) except errors.HttpError: print('An error occurred') storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') storage.put(credential) return HttpResponseRedirect("/")
def test_token_too_old_explicit_current_time(self): token_time = 123456789 curr_time = token_time + xsrfutil.DEFAULT_TIMEOUT_SECS + 1 key = user_id = None token = base64.b64encode(_to_bytes(str(token_time))) self.assertFalse(xsrfutil.validate_token(key, token, user_id, current_time=curr_time))
def auth_return(request): if not xsrfutil.validate_token(settings.SECRET_KEY, request.REQUEST['state'], request.user): return HttpResponseBadRequest() credential = FLOW.step2_exchange(request.REQUEST) storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') storage.put(credential) return HttpResponseRedirect("/")
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('/')
def auth_return_view(request): user = request.user if not xsrfutil.validate_token(settings.SECRET_KEY, str(request.GET['state']), user): return HttpResponseBadRequest() FLOW = FlowModel.objects.get(id=user).flow credential = FLOW.step2_exchange(request.GET) storage = Storage(CredentialsModel, 'id', user, 'credential') storage.put(credential) return HttpResponseRedirect('/oauth2')
def oauth2callback(request): if not xsrfutil.validate_token(settings.SECRET_KEY, str(request.GET['state']), request.user): return HttpResponseBadRequest() credential = FLOW.step2_exchange(request.GET) storage = Storage(GoogleCredentialsModel, 'id', request.user, 'credential') storage.put(credential) redirect_url = request.session['redirect_uri_after_step2'] return HttpResponseRedirect(redirect_url)
def auth_return(request): user = request.user FLOW = FlowModel.objects.get(id=user).flow if not xsrfutil.validate_token( settings.SECRET_KEY, FLOW.params['state'], user): return HttpResponseBadRequest() credential = FLOW.step2_exchange(request.GET['code']) storage = Storage(CredentialsModel, 'id', user, 'credential') storage.put(credential) return HttpResponseRedirect(reverse("oauth2:index"))
def auth_return(request): user = request.user if not xsrfutil.validate_token(settings.SECRET_KEY, str(request.GET['state']), user): return HttpResponseBadRequest() FLOW = FlowModel.objects.get(id=user).flow credential = FLOW.step2_exchange(request.GET) storage = Storage(CredentialsModel, 'id', user, 'credential') storage.put(credential) return HttpResponseRedirect("/scheduler/home")
def test_token_too_old_implicit_current_time(self): token_time = 123456789 curr_time = token_time + xsrfutil.DEFAULT_TIMEOUT_SECS + 1 key = user_id = None token = base64.b64encode(_to_bytes(str(token_time))) with mock.patch('oauth2client.contrib.xsrfutil.time') as time: time.time = mock.MagicMock(name='time', return_value=curr_time) self.assertFalse(xsrfutil.validate_token(key, token, user_id)) time.time.assert_called_once_with()
def calendar_auth_return(request): if not xsrfutil.validate_token(settings.SECRET_KEY, bytes(request.GET['state'], 'utf-8'), request.user): return HttpResponseBadRequest() credential = CALENDAR_FLOW.step2_exchange(request.GET) storage = DjangoORMStorage(CredentialsModel, 'user', request.user, 'credential') storage.put(credential) return redirect('calendar')
def auth_return(request): bits = request.GET['state'].split("|") state_token = bits[0] redir = "" if len(bits) > 1: redir = bits[1] if not xsrfutil.validate_token(settings.SECRET_KEY, str(state_token), request.user.username): return HttpResponseBadRequest() data = {'state': request.GET['state'], 'code': request.GET['code'], 'redir': redir} return render(request, "googaccount/label.html", data)
def auth_return(request): state = str(request.GET.get("state")) token_valid = xsrfutil.validate_token( settings.SECRET_KEY, bytearray(state, "utf-8"), request.user ) if not token_valid or not state: return HttpResponseRedirect("/jobs/") credential = FLOW.step2_exchange(request.GET) storage = DjangoORMStorage(CredentialsModel, "id", request.user, "credential") storage.put(credential) return HttpResponseRedirect(reverse("pjob:job_add_event"))
def get(self, request): get_state = bytes(request.GET.get('state'), 'utf8') if not xsrfutil.validate_token(settings.SECRET_KEY, get_state, request.user): return HttpResponseBadRequest() credential = FLOW.step2_exchange(request.GET.get('code')) storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') storage.put(credential) print("access_token: %s" % credential.access_token) return HttpResponseRedirect("../admin/hiringapp/submission/")
def auth_return(request): user = request.user secret = request.REQUEST['state'].split('___')[0] group_name = request.REQUEST['state'].split('___')[1] if not xsrfutil.validate_token(settings.SECRET_KEY, str(secret), user): return HttpResponseBadRequest() FLOW = FlowModel.objects.get(id=user).flow credential = FLOW.step2_exchange(request.REQUEST) storage = Storage(CredentialsModel, 'id', user, 'credential') storage.put(credential) return HttpResponseRedirect("/gmail_setup?group=" + group_name)
def get(self, request, *args, **kwargs): if not xsrfutil.validate_token(settings.SECRET_KEY, request.GET.get('state').encode(), request.user): return HttpResponseBadRequest() global flow credentials = flow.step2_exchange(request.GET) storage = DjangoORMStorage(GoogleAPIOauthInfo, 'id', request.user.id, 'credentials') storage.put(credentials) return redirect('/upload/')
def xsrf_decode(secret, state, uid): # String -> String -> id -> Either Exception Bytes # Note: returns URI as Python2 string (bytes) # Does not work with unicode URIs try: uri, tok = str(state).rsplit(':', 1) if not xsrfutil.validate_token(secret, tok, uid, action_id=uri): raise InvalidXSRFTokenError() return Right(uri) except Exception as e: return Left(err.wrap(e))
def xsrf_decode(secret, state, uid): # String -> String -> id -> Either Exception Bytes # Note: returns URI as Python2 string (bytes) # Does not work with unicode URIs try: uri, tok = str(state).rsplit(':',1) if not xsrfutil.validate_token(secret,tok,uid,action_id=uri): raise InvalidXSRFTokenError() return Right(uri) except Exception as e: return Left(err.wrap(e))
def get(self, request): if not xsrfutil.validate_token( settings.SECRET_KEY, str(request.GET['state']), request.user): return HttpResponseBadRequest() flow = get_flow(request) credential = flow.step2_exchange(code=request.GET['code']) storage = DjangoORMStorage( Credentials, 'email', settings.PRIMARY_YOUTUBE_ACCOUNT, 'credential') storage.put(credential) return HttpResponseRedirect("/")
def test_success(self): token_time = 123456789 # Make sure it isn't too old. curr_time = token_time + xsrfutil.DEFAULT_TIMEOUT_SECS - 1 key = object() user_id = object() action_id = object() token = base64.b64encode(_to_bytes(str(token_time))) with mock.patch('oauth2client.contrib.xsrfutil.generate_token', return_value=token) as gen_tok: self.assertTrue(xsrfutil.validate_token(key, token, user_id, current_time=curr_time, action_id=action_id)) gen_tok.assert_called_once_with(key, user_id, action_id=action_id, when=token_time)
def auth_return(request): if not xsrfutil.validate_token(settings.SECRET_KEY, str(request.GET['state']), request.user.username): return HttpResponseBadRequest() credential = FLOW.step2_exchange(request.GET) credential = TwitchCredentials.from_json(credential.to_json()) http = httplib2.Http() http = credential.authorize(http) resp, data = http.request("https://api.twitch.tv/kraken/user") data = json.loads(data) print data ac = TwitchAppCreds(user=request.user, label=data['name']) ac.save() return HttpResponseRedirect("/accounts/") return render(request, "twitchaccount/label.html", data)
def _parse_state_value(state, user): """Parse the value of the 'state' parameter. Parses the value and validates the XSRF token in the state parameter. Args: state: string, The value of the state parameter. user: google.appengine.api.users.User, The current user. Returns: The redirect URI, or None if XSRF token is not valid. """ uri, token = state.rsplit(':', 1) if xsrfutil.validate_token(xsrf_secret_key(), token, user.user_id(), action_id=uri): return uri else: return None
def auth_return(request): if not xsrfutil.validate_token(settings.SECRET_KEY, str(request.GET['state']), request.user.username): return HttpResponseBadRequest() credential = FLOW.step2_exchange(request.GET) http = httplib2.Http() http = credential.authorize(http) resp, data = http.request("https://api.patreon.com/oauth2/api/current_user") data = json.loads(data) name = data['data']['attributes'].get("full_name") or "(unnamed)" internal_label = "%s-%s" % (request.user.id, name) ac = PatreonAppCreds(user=request.user, label=internal_label) ac.save() storage = Storage(PatreonCredentialsModel, 'id', ac, 'credential') storage.put(credential) pu = PatreonUpdate(credentials=ac, user=request.user, type="patreon") pu.save() return HttpResponseRedirect("/patreon/")
def test_token_length_differs_from_generated(self): token_time = 123456789 # Make sure it isn't too old. curr_time = token_time + xsrfutil.DEFAULT_TIMEOUT_SECS - 1 key = object() user_id = object() action_id = object() token = base64.b64encode(_to_bytes(str(token_time))) generated_token = b'a' # Make sure the token length comparison will fail. self.assertNotEqual(len(token), len(generated_token)) with mock.patch('oauth2client.contrib.xsrfutil.generate_token', return_value=generated_token) as gen_tok: self.assertFalse(xsrfutil.validate_token(key, token, user_id, current_time=curr_time, action_id=action_id)) gen_tok.assert_called_once_with(key, user_id, action_id=action_id, when=token_time)
def _parse_state_value(state, user): """Parse the value of the 'state' parameter. Parses the value and validates the XSRF token in the state parameter. Args: state: string, The value of the state parameter. user: google.appengine.api.users.User, The current user. Raises: InvalidXsrfTokenError: if the XSRF token is invalid. Returns: The redirect URI. """ uri, token = state.rsplit(":", 1) if not xsrfutil.validate_token(xsrf_secret_key(), token, user.user_id(), action_id=uri): raise InvalidXsrfTokenError() return uri
def auth_return(request): """ Step 2 of Google OAuth 2.0 flow. """ if 'state' not in request.GET: return redirect('gauth_index') if not xsrfutil.validate_token(settings.SECRET_KEY, str(request.GET['state']), request.user): return HttpResponseBadRequest() FLOW = DjangoORMStorage(FlowModel, 'id', request.user, 'flow').get() if FLOW is None: return redirect('gauth_index') credential = FLOW.step2_exchange(request.GET) cred_storage = DjangoORMStorage(CredentialsModel, 'id', request.user, 'credential') cred_storage.put(credential) return redirect(request.session.get('next_view', '/'))
def auth_return_view(request): """Receive a successful oauth flow.""" token = smart_str(request.GET['state']) if not xsrfutil.validate_token(settings.SECRET_KEY, token, request.user): return HttpResponseBadRequest('Improper OAuth request.') if 'error' in request.GET: if request.GET['error'] != 'access_denied': # access_denied means the user clicked deny; it's not exceptional. logger.error("error on oauth return: %s", request.GET['error']) return redirect('autorespond') credential = FLOW.step2_exchange(request.GET) if credential.refresh_token is not None: # refresh tokens only come with fresh auths. # we don't want to store reauths, since we'd clobber the refresh token. http = httplib2.Http() http = credential.authorize(http) service = build("plus", "v1", http=http) res = service.people().get(userId='me').execute() email = res['emails'][0]['value'] try: GoogleCredential.objects.update_or_create( email=email, user=request.user, defaults={'credentials': credential}) except IntegrityError: logger.error('attempt to connect already-connected account %r to %r', email, request.user.email, extra={'tags': {'linker': request.user.email, 'linkee': email}}) return HttpResponseBadRequest('This Google account is already connected to a different account.') return redirect('autorespond')
def auth_return(request): '''The Token generated in index() should be validated here with the same user that was used to generate the token''' U = User( username = '******', firstname= 'Bla Bla', lastname= 'Bla Bla', email = '*****@*****.**' ) ''' Reference: 1. https://github.com/tschellenbach/Django-facebook/pull/564 2. encode() is used here because in Django 1.6 or less we used to get the string automatically but in Django 1.7+ we have to use encode() to get the string ''' if not xsrfutil.validate_token(settings.SECRET_KEY, (request.GET['state']).encode('utf-8'), U): print("Test: 1") return HttpResponseBadRequest() print("Test: 2") credential = FLOW.step2_exchange(request.GET) storage = Storage(CredentialsModel, 'id', U, 'credential') storage.put(credential) return HttpResponseRedirect("/")
def test_token_differs_from_generated_but_same_length(self): token_time = 123456789 # Make sure it isn't too old. curr_time = token_time + xsrfutil.DEFAULT_TIMEOUT_SECS - 1 key = object() user_id = object() action_id = object() token = base64.b64encode(_helpers._to_bytes(str(token_time))) # It is encoded as b'MTIzNDU2Nzg5', which has length 12. generated_token = b'M' * 12 # Make sure the token length comparison will succeed, but the token # comparison will fail. self.assertEqual(len(token), len(generated_token)) self.assertNotEqual(token, generated_token) with mock.patch('oauth2client.contrib.xsrfutil.generate_token', return_value=generated_token) as gen_tok: self.assertFalse(xsrfutil.validate_token(key, token, user_id, current_time=curr_time, action_id=action_id)) gen_tok.assert_called_once_with(key, user_id, action_id=action_id, when=token_time)
def testGenerateAndValidateToken(self): """Test generating and validating a token.""" token = xsrfutil.generate_token(TEST_KEY, TEST_USER_ID_1, action_id=TEST_ACTION_ID_1, when=TEST_TIME) # Check that the token is considered valid when it should be. self.assertTrue(xsrfutil.validate_token(TEST_KEY, token, TEST_USER_ID_1, action_id=TEST_ACTION_ID_1, current_time=TEST_TIME)) # Should still be valid 15 minutes later. later15mins = TEST_TIME + 15 * 60 self.assertTrue(xsrfutil.validate_token(TEST_KEY, token, TEST_USER_ID_1, action_id=TEST_ACTION_ID_1, current_time=later15mins)) # But not if beyond the timeout. later2hours = TEST_TIME + 2 * 60 * 60 self.assertFalse(xsrfutil.validate_token(TEST_KEY, token, TEST_USER_ID_1, action_id=TEST_ACTION_ID_1, current_time=later2hours)) # Or if the key is different. self.assertFalse(xsrfutil.validate_token('another key', token, TEST_USER_ID_1, action_id=TEST_ACTION_ID_1, current_time=later15mins)) # Or the user ID.... self.assertFalse(xsrfutil.validate_token(TEST_KEY, token, TEST_USER_ID_2, action_id=TEST_ACTION_ID_1, current_time=later15mins)) # Or the action ID... self.assertFalse(xsrfutil.validate_token(TEST_KEY, token, TEST_USER_ID_1, action_id=TEST_ACTION_ID_2, current_time=later15mins)) # Invalid when truncated self.assertFalse(xsrfutil.validate_token(TEST_KEY, token[:-1], TEST_USER_ID_1, action_id=TEST_ACTION_ID_1, current_time=later15mins)) # Invalid with extra garbage self.assertFalse(xsrfutil.validate_token(TEST_KEY, token + b'x', TEST_USER_ID_1, action_id=TEST_ACTION_ID_1, current_time=later15mins)) # Invalid with token of None self.assertFalse(xsrfutil.validate_token(TEST_KEY, None, TEST_USER_ID_1, action_id=TEST_ACTION_ID_1))
def test_token_non_integer(self): key = user_id = None token = base64.b64encode(b'abc' + xsrfutil.DELIMITER + b'xyz') self.assertFalse(xsrfutil.validate_token(key, token, user_id))
def test_token_not_valid_base64(self): key = user_id = None token = b'a' # Bad padding self.assertFalse(xsrfutil.validate_token(key, token, user_id))
def test_no_token(self): key = token = user_id = None self.assertFalse(xsrfutil.validate_token(key, token, user_id))
def post(self, request, *args, **kwargs): """ Process the POST data sent via AJAX after user clicks on the sign-in button. """ # retrive the one-time Google generated code after user granted permission to the app. code = request.POST.get("code", None) print("code:" + code) #print(request.session['test']) # Make sure the request session is still intact and hasn't been tempered with. if not xsrfutil.validate_token(settings.SECRET_KEY, str(request.session['state']), None): return HttpResponseBadRequest() # if there is no one-time Google generated code then return if code is None: return HttpResponse ("No Code") # Exchange the one-time Google generated code for an AccessToken and RefreshToken. # Remember that RefreshToken is only generated once during the initial granting of # permission by the user. try: oauth_flow = flow_from_clientsecrets('blog/client_secrets.json', scope="") oauth_flow.redirect_uri = 'postmessage' credentials = oauth_flow.step2_exchange(code) except FlowExchangeError as e: return HttpResponse("Failed to upgrade the authorization code. 401 %s" % e) commenter, created = Commenter.objects.get_or_create(email=credentials.id_token['email'], defaults={'plus_id': credentials.id_token['sub']}) request.session['cid'] = commenter.pk # retrieve the credentials object from the database based on the user's email gstorage = Storage(GoogleCredentialsModel, 'commenter', commenter, 'credential') # if the credentials object does not exist or is invalid then store it if gstorage.get() is None or credentials.invalid == True: gstorage.put(credentials) # if the commenter did not exist before, then save his/her basic profile if created: SERVICE = build('plus', 'v1') http = httplib2.Http() http = credentials.authorize(http) google_request = SERVICE.people().get(userId='me') result = google_request.execute(http=http) try: commenter.given_name = result['name']['givenName'] if ('name' in result and 'givenName' in result['name']) else None commenter.family_name = result['name']['familyName'] if ('name' in result and 'familyName' in result['name']) else None commenter.display_name = result['displayName'] if 'displayName' in result else None commenter.is_plus_user = result['isPlusUser'] if 'isPlusUser' in result else None commenter.gender = result['gender'] if 'gender' in result else None commenter.image_url = result['image']['url'] if ('image' in result and 'url' in result['image']) else None commenter.language = result['language'] if 'language' in result else None commenter.birthday = result['birthday'] if 'birthday' in result else None commenter.age_range_min = result['ageRange']['min'] if ('ageRange' in result and 'min' in result['ageRange']) else None commenter.age_range_max = result['ageRange']['max'] if ('ageRange' in result and 'max' in result['ageRange']) else None commenter.save() except Commenter.DoesNotExist as e: print(e) #return HttpResponse(json.dumps(credentials.to_json())) return HttpResponse(json.dumps({"commenter_id": commenter.pk}))
def auth_return(request): if not xsrfutil.validate_token(settings.SECRET_KEY, str(request.GET['state']), request.user.username): return HttpResponseBadRequest() data = {'state': request.GET['state'], 'code': request.GET['code']} return render(request, "googaccount/label.html", data)