def test_change_password(client, session): init_password = "******" new_password = "******" register(client, "*****@*****.**", init_password, "UserB") # Can login with initial password rv = login(client, "*****@*****.**", init_password) assert b"Logged as UserB" in rv.data # Change password resp = client.post( "/change", data=dict(password=init_password, new_password=new_password, new_password_confirm=new_password), follow_redirects=True, ) assert resp.status_code == 200 assert b"You successfully changed your password." in resp.data # Logout logout(client) # Test login with new password resp = login(client, "*****@*****.**", new_password) print(resp.data) assert b"Logged as UserB" in resp.data logout(client) # Test login with old password resp = login(client, "*****@*****.**", init_password) assert b"Invalid password" in resp.data
def test_auth_flow_denied(provider_fixture): app = provider_fixture with app.test_request_context(): redirect_uri = url_for('oauth2test.authorized', _external=True) with app.test_client() as client: # First login on provider site login(client) r = client.get(url_for('oauth2test.login')) assert r.status_code == 302 next_url, data = parse_redirect(r.location) # Authorize page r = client.get(next_url, query_string=data) assert r.status_code == 200 # User rejects request data['confirm'] = 'no' data['scope'] = 'test:scope' data['state'] = '' r = client.post(next_url, data=data) assert r.status_code == 302 next_url, data = parse_redirect(r.location) assert next_url == redirect_uri assert data.get('error') == 'access_denied' # Returned r = client.get(next_url, query_string=data) assert r.status_code == 200 assert r.data == b'Access denied: error=access_denied'
def main(): global SHORT_PAUSE_TIME, LONG_PAUSE_TIME argument_parser = argparse.ArgumentParser(description=( "logs in to user's facebook account, and click See more for all his/her posts" )) argument_parser.add_argument('-u', '--username', default=None, help="username of user") argument_parser.add_argument('-p', '--password', default=None, help="password of user") argument_parser.add_argument('-s', '--sp', type=int, default=SHORT_PAUSE_TIME, help="short pause duration") argument_parser.add_argument('-l', '--lp', type=int, default=LONG_PAUSE_TIME, help="long pause duration") arguments = argument_parser.parse_args() if arguments.username is None or arguments.password is None: print("Missing username or password of account!") exit() if arguments.sp != SHORT_PAUSE_TIME: SHORT_PAUSE_TIME = arguments.sp if arguments.lp != LONG_PAUSE_TIME: LONG_PAUSE_TIME = arguments.lp # configure ChromeDriver options = Options() options.add_argument('--ignore-certificate-errors') options.add_argument('--test-type') options.add_argument('--disable-notifications') options.add_argument('--disable-extensions') options.add_experimental_option("detach", True) options.add_experimental_option( 'prefs', { 'credentials_enable_service': False, 'profile': { 'password_manager_enabled': False } }) # point to Google Chrome executable location, default location is used if platform.system() == 'Windows': options.binary_location = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe" else: options.binary_location = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" driver = webdriver.Chrome(options=options) driver.get(FACEBOOK_HOME) helpers.login(driver, arguments.username, arguments.password) time.sleep(SHORT_PAUSE_TIME) see_more(driver)
def test_opening_balance_errors(browser, test_client, db): login(browser) build_catalog(browser, test_client, db) browser.get('http://localhost:3000/artists') browser.find_element_by_id('settings').click() path = os.getcwd() + f"/tests/func/{CASE}/opening_balance_errors.csv" browser.find_element_by_id('opening-balance-to-upload').send_keys(path) time.sleep(1) browser.find_element_by_id('opening-balance-upload').click() time.sleep(1) assert browser.find_element_by_id( 'header').text == 'Fix Opening Balance Errors' table = browser.find_element_by_id('opening-balance-errors') rows = table.find_elements_by_tag_name('tr') assert len(rows) == 4 time.sleep(1) browser.find_element_by_id('updatebutton-2').click() time.sleep(1) table = browser.find_element_by_id('opening-balance-errors') rows = table.find_elements_by_tag_name('tr') assert len(rows) == 3
def test_my_ratings(driver, django_db_blocker): # creating a video login(driver) with django_db_blocker.unblock(): me = UserPreferences.objects.get(user__username=test_username) video_id1 = create_test_video() video_id2 = create_test_video() video_1 = Video.objects.get(video_id=video_id1) video_2 = Video.objects.get(video_id=video_id2) ExpertRating.objects.create(video_1=video_1, video_2=video_2, **{k: 50 for k in VIDEO_FIELDS}, user=me) open_more_menu(driver) WebDriverWait(driver, TIME_WAIT).until( EC.visibility_of_element_located((By.ID, 'video_details_menu'))) print("Going to the details page") expert_interface_btn = driver.find_element_by_id('video_details_menu') expert_interface_btn.click() WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.CLASS_NAME, 'video_id_text_field'))) elem = driver.find_element_by_class_name('video_id_text_field') elem = elem.find_element_by_tag_name('input') elem.clear() elem.send_keys(video_id1, Keys.HOME) if elem.get_attribute('value') != video_id1: elem.send_keys(3 * [Keys.DELETE]) WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located( (By.CLASS_NAME, 'button_video_ratings'))) # opening ratings page driver.find_element_by_class_name('button_video_ratings').click() WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, 'id_my_ratings'))) WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.CLASS_NAME, 'video_rating_video'))) # have only 1 rating assert len(driver.find_elements_by_class_name('video_rating_video')) == 1 # rerate driver.find_elements_by_class_name('video_rating_rerate')[0].click() # on the right page assert driver.current_url.split('/')[-2:] == [video_id1, video_id2] logout(driver)
def test_profile_view(app): """Test the profile view.""" app.config['USERPROFILES_EMAIL_ENABLED'] = False with app.test_request_context(): profile_url = url_for('invenio_userprofiles.profile') with app.test_client() as client: sign_up(app, client) login(app, client) resp = client.get(profile_url) assert resp.status_code == 200 assert 'name="profile_form"' in str(resp.data) # Valid submission should work resp = client.post(profile_url, data=prefix( 'profile', dict( username=test_usernames['valid'], full_name='Valid Name', ))) assert resp.status_code == 200 data = resp.get_data(as_text=True) assert test_usernames['valid'] in data assert 'Valid' in data assert 'Name' in data # Invalid submission should not save data resp = client.post( profile_url, data=prefix( 'profile', dict( username=test_usernames['invalid_characters'], full_name='Valid Name', ))) assert resp.status_code == 200 assert test_usernames['invalid_characters'] in \ resp.get_data(as_text=True) resp = client.get(profile_url) assert resp.status_code == 200 assert test_usernames['valid'] in resp.get_data(as_text=True) # Whitespace should be trimmed client.post(profile_url, data=prefix( 'profile', dict( username='******'.format(test_usernames['valid']), full_name='Valid Name ', ))) resp = client.get(profile_url) assert resp.status_code == 200 data = resp.get_data(as_text=True) assert test_usernames['valid'] in data assert 'Valid Name ' not in data
def test_auth_flow_denied(provider_fixture): app = provider_fixture with app.test_request_context(): redirect_uri = url_for("oauth2test.authorized", _external=True) with app.test_client() as client: # First login on provider site login(client) r = client.get(url_for("oauth2test.login")) assert r.status_code == 302 next_url, data = parse_redirect(r.location) # Authorize page r = client.get(next_url, query_string=data) assert r.status_code == 200 # User rejects request data["confirm"] = "no" data["scope"] = "test:scope" data["state"] = "" r = client.post(next_url, data=data) assert r.status_code == 302 next_url, data = parse_redirect(r.location) assert next_url == redirect_uri assert data.get("error") == "access_denied" # Returned r = client.get(next_url, query_string=data) assert r.status_code == 200 assert r.data == b"Access denied: error=access_denied"
def test_feature_links(driver, django_db_blocker): login(driver) set_all_features_enabled(django_db_blocker) print("Going to the expert interface...") expert_interface_btn = driver.find_element_by_id('expert_interface') expert_interface_btn.click() WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, 'id_expert_rating_page'))) for f in VIDEO_FIELDS: elem_id = "id_explanation_" + f WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, elem_id))) link = driver.find_element_by_id(elem_id).get_attribute('href') assert link.startswith('http'), link resp = get(link) assert resp.ok assert resp.status_code == 200 assert 'MediaWiki' in resp.text print(f, resp.text[:500]) logout(driver)
def test_profile(client, session): helpers.register(client, "*****@*****.**", "fluttershy", "UserTP") helpers.login(client, "*****@*****.**", "fluttershy") rv = client.get("/user", follow_redirects=True) assert b"Please fill me !" in rv.data assert b"Please fill me !" in rv.data helpers.logout(client)
def test_delete_segmented_upload(api, users, location): with api.test_request_context(), api.test_client() as client: login(client) # Create a segmented upload init_response = client.post( "/sword/staging", headers={ "Content-Disposition": f"segment-init; segment_count=2; segment_size=10; size=15", }, ) assert init_response.status_code == HTTPStatus.CREATED assert "Location" in init_response.headers # Upload a single segment response = client.post( init_response.headers["Location"], headers={"Content-Disposition": f"segment; segment_number=1",}, data=b"1234567890", ) # Delete the whole thing response = client.delete(init_response.headers["Location"],) assert response.status_code == HTTPStatus.NO_CONTENT assert MultipartObject.query.count() == 0 assert Part.query.count() == 0
def test_authorized_app_revocation(developer_app_fixture): """Test managing authorized application tokens through the views.""" app = developer_app_fixture with app.test_request_context(): with app.test_client() as client: login(client) # Check that there is a single token for the authorized application assert Token.query.count() == 1 # Check that the authorized application is visible on index view resp = client.get(url_for('invenio_oauth2server_settings.index')) assert resp.status_code == 200 assert 'Test description' in str(resp.get_data()) assert 'Test name' in str(resp.get_data()) # Revoke the authorized application token resp = client.get(url_for( 'invenio_oauth2server_settings.token_revoke', token_id=1), follow_redirects=True) assert resp.status_code == 200 # Authorized application should no longer exist on index assert 'Test description' not in str(resp.get_data()) assert 'Test name' not in str(resp.get_data()) # Check that the authorized application token was actually deleted assert Token.query.count() == 0
def test_comment_uncertified(driver, django_db_blocker): # creating a user and leaving a comment, checking that it is not shown username = str(uuid1()) domain = f"@{uuid1()}.com" with django_db_blocker.unblock(): u = DjangoUser.objects.create_user(username=username, is_active=True) EmailDomain.objects.create(domain=domain, status=EmailDomain.STATUS_ACCEPTED) ui = UserInformation.objects.create(user=u) up = UserPreferences.objects.create(user=u) v = Video.objects.create(video_id=random_alphanumeric()) VerifiableEmail.objects.create(user=ui, email=f"test{domain}") VideoComment.objects.create(user=up, video=v, comment="test") login(driver) res = do_api_call_v2(driver, '/video_comments/?video__video_id=' + v.video_id) assert res['count'] == 0 with django_db_blocker.unblock(): VerifiableEmail.objects.filter( user=ui, email=f"test{domain}").update(is_verified=True) res = do_api_call_v2(driver, '/video_comments/?video__video_id=' + v.video_id) assert res['count'] == 1 logout(driver) with django_db_blocker.unblock(): u.delete() v.delete()
def test_post_by_reference_segmented(api, users, location, task_delay): with api.test_request_context(), api.test_client() as client: # Assemble a segmented upload from parts, and complete it segmented_upload_record: SegmentedUploadRecord = SegmentedUploadRecord.create( {} ) multipart_object = MultipartObject.create( bucket=segmented_upload_record.bucket, key="some-key", size=15, chunk_size=10, ) Part.create(multipart_object, 0, stream=io.BytesIO(b"abcdefghij")) Part.create(multipart_object, 1, stream=io.BytesIO(b"klmno")) multipart_object.complete() login(client) ttl = ( datetime.datetime.now(tz=datetime.timezone.utc) + datetime.timedelta(0, 3600) ).isoformat() response = client.post( "/sword/service-document", data=json.dumps( { "@context": JSON_LD_CONTEXT, "@type": "ByReference", "byReferenceFiles": [ { "@id": f"http://localhost/sword/staging/{segmented_upload_record.id}", "contentDisposition": "attachment; filename=some-resource.json", "contentType": "application/json", "dereference": True, "ttl": ttl, } ], } ), headers={ "Content-Disposition": "attachment; by-reference=true", "Content-Type": "application/ld+json", }, ) assert response.status_code == HTTPStatus.CREATED object_version = ObjectVersion.query.one() tags = TagManager(object_version) assert tags == { ObjectTagKey.Packaging: "http://purl.org/net/sword/3.0/package/Binary", ObjectTagKey.ByReferenceTemporaryID: str(segmented_upload_record.id), ObjectTagKey.FileState: FileState.Pending, ObjectTagKey.ByReferenceDereference: "true", ObjectTagKey.ByReferenceNotDeleted: "true", ObjectTagKey.OriginalDeposit: "true", ObjectTagKey.ByReferenceTTL: ttl, }
def test_create_record_check_acl_priority(app, db, es, es_acl_prepare, test_users): with app.test_client() as client: with db.session.begin_nested(): acl1 = DefaultACL(name='default', schemas=[RECORD_SCHEMA], priority=0, originator=test_users.u1, operation='get') actor1 = SystemRoleActor(name='auth', system_role='any_user', acl=acl1, originator=test_users.u1) acl2 = DefaultACL(name='default', schemas=[RECORD_SCHEMA], priority=1, originator=test_users.u1, operation='get') actor2 = SystemRoleActor(name='auth', system_role='authenticated_user', acl=acl2, originator=test_users.u1) db.session.add(acl1) db.session.add(actor1) db.session.add(acl2) db.session.add(actor2) login(client, test_users.u1) response = client.post(records_url(), data=json.dumps({ 'title': 'blah', 'contributors': [] }), content_type='application/json') assert response.status_code == 201 rest_metadata = get_json(response)['metadata'] assert 'control_number' in rest_metadata index, doctype = schema_to_index(RECORD_SCHEMA) rec_md = current_search_client.get( index=index, doc_type=doctype, id=str( PersistentIdentifier.get( 'recid', rest_metadata['control_number']).object_uuid)) clear_timestamp(rec_md) assert rec_md['_source']['_invenio_explicit_acls'] == [{ 'operation': 'get', 'id': acl2.id, 'timestamp': 'cleared', 'system_role': ['authenticated_user'] }]
async def send_item_store(self): from settings import TOGOOD_CLIENT try: login() except Exception as e: await alert_admin(f"error while login\n{e}") data = self.config["data"] for store in data: try: item_string = TOGOOD_CLIENT.fetch_store_id( store["store_id"], store["origin"]["lat"], store["origin"]["lon"]) item_dict = get_store_details(item_string) nb_items = item_dict["nb_items"] if nb_items == store["items"]: logging.info("no change in baskets") continue else: store["items"] = nb_items if nb_items > 0: embed = info_to_embed(item_dict) else: embed = discord.Embed( title=f"Panier {item_dict['store_name']}", description= "Tu as raté ta chance ... il n'y a plus de paniers disponibles", color=0xe32400) await self.channel.send(embed=embed) except Exception as e: await alert_admin(f"error while fetching a store\n{e}")
def test_login_logout(client, session): """Make sure login and logout works.""" resp = register(client, "*****@*****.**", "fluttershy", "UserA", "User A") assert resp.status_code == 200 resp = json.loads(resp.data) assert "created_at" in resp assert "access_token" in resp rv = login(client, "*****@*****.**", "fluttershy") rv = client.get("/home") assert rv.status_code == 200 assert b"Logged as UserA" in rv.data rv = logout(client) rv = client.get("/home") assert rv.status_code == 200 assert b"UserA" not in rv.data rv = login(client, "*****@*****.**" + "x", "fluttershy") assert rv.status_code == 200 assert b"Specified user does not exist" in rv.data rv = login(client, "*****@*****.**", "fluttershy" + "x") assert rv.status_code == 200 assert b"Invalid password" in rv.data
def test_rest_delete_record(app, db, es, es_acl_prepare, test_users): with app.test_client() as client: with db.session.begin_nested(): acl = DefaultACL(name='default', schemas=[RECORD_SCHEMA], priority=0, originator=test_users.u1, operation='update') actor = UserActor(name='u1', users=[test_users.u1], acl=acl, originator=test_users.u1) db.session.add(acl) db.session.add(actor) pid, record = create_record({'keywords': ['blah']}, clz=SchemaEnforcingRecord) RecordIndexer().index(record) current_search_client.indices.refresh() current_search_client.indices.flush() login(client, test_users.u2) response = client.delete(record_url(pid)) assert response.status_code == 403 login(client, test_users.u1) response = client.delete(record_url(pid)) assert response.status_code == 204 with pytest.raises(NoResultFound): Record.get_record(pid.object_uuid)
def test_no_show(driver, django_db_blocker): login(driver) with django_db_blocker.unblock(): username = "******" + str(uuid1()) u = DjangoUser.objects.create_user(username=username) ui = UserInformation.objects.create(user=u, show_my_profile=False) r = do_api_call_v2(driver=driver, url=f'/user_information/{ui.id}/', expect_fail=True) assert not r.ok r = do_api_call_v2(driver=driver, url=f'/user_information/?user__username={username}') assert r['count'] == 0 # test that can see my own hidden profile with django_db_blocker.unblock(): UserInformation.objects.filter(user__username=test_username).update( show_my_profile=False) r = do_api_call_v2( driver=driver, url=f'/user_information/?user__username={test_username}') assert r['count'] == 1 with django_db_blocker.unblock(): UserInformation.objects.filter(user__username=test_username).update( show_my_profile=True) logout(driver) with django_db_blocker.unblock(): u.delete()
def test_start_segmented(api, location, users): with api.test_request_context(), api.test_client() as client: login(client) response = client.post( "/sword/staging", headers={ "Content-Disposition": "segment-init; segment_count=2; segment_size=10000000; size=20000000", }, ) assert response.status_code == HTTPStatus.CREATED assert "Location" in response.headers record_metadata = RecordMetadata.query.one() record = SegmentedUploadRecord(record_metadata.json, model=record_metadata) response = client.get(response.headers["Location"]) assert response.json == { "@context": JSON_LD_CONTEXT, "@id": "http://localhost/sword/staging/" + str(record.id), "@type": "Temporary", "segments": { "received": [], "expecting": [1, 2], "size": 20000000, "segment_size": 10000000, }, }
def test_change_email_whitespace(app): """Test send verification form.""" mail = app.extensions['mail'] with app.test_request_context(): profile_url = url_for('invenio_userprofiles.profile') with app.test_client() as client: sign_up(app, client) login(app, client) resp = client.get(profile_url) assert resp.status_code == 200 data = prefix( 'profile', dict( username='******', full_name='Test User', email=app.config['TEST_USER_EMAIL'], email_repeat=app.config['TEST_USER_EMAIL'], )) with mail.record_messages() as outbox: assert len(outbox) == 0 data['profile-email_repeat'] = data['profile-email'] = '*****@*****.**' resp = client.post(profile_url, data=data) assert 'Invalid email address' not in resp.get_data(as_text=True) # Email was sent for email address confirmation. assert len(outbox) == 1
def test_1_create_post(self): # Get the driver driver = self.driver # Login helpers.login() driver.get(helpers.BASE_URL + '/') driver.find_element_by_link_text('New').click() title = driver.find_element_by_name('title') title.send_keys('Selenium test article 123') body = driver.find_element_by_name('body') body.send_keys( 'This is the article text {{!--readmore--}} And this is the rest of the text after readmore' ) # Save the post driver.find_element_by_xpath("//input[@value='Save']").click() # Verify if the post was successfully saved .. postElem = driver.find_element_by_css_selector( '.content > article > header > div > h1') assert postElem.text == 'Selenium test article 123'
def test_withlogin(driver, django_db_blocker): login(driver) # going to user personal profile driver.find_element_by_id('personal_info_menu').click() # editing the profile WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, 'edit_userprofile_button_id'))) driver.find_element_by_id('edit_userprofile_button_id').click() WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located( (By.CLASS_NAME, 'to_verified_domains_class'))) # going to the list of domains driver.find_element_by_class_name('to_verified_domains_class').click() WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, 'domains'))) with _create_emails(django_db_blocker) as domains: ack_email, rej_email, pend_email = domains driver.refresh() WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, 'domains'))) _test_domains(driver, ack_email, rej_email, pend_email) logout(driver)
def test_logging_user(client, session): helpers.register(client, "*****@*****.**", "fluttershy", "UserTLU") helpers.login(client, "*****@*****.**", "fluttershy") rv = client.get("/user", follow_redirects=True) assert b"*****@*****.**" in rv.data helpers.logout(client) assert b"Logged as UserTLU" in rv.data
def main(): # get the instagram user & password from standard input usr = input("Enter your username: "******"Enter your password: "******"excludeSwitches", ["enable-automation"]) # disable chrome "save password" popup options.add_experimental_option( 'prefs', { 'credentials_enable_service': False, 'profile': { 'password_manager_enabled': False } }) # open a new Chrome browser | get an event-firing-web-driver instance global driver driver = Chrome(options=options) # sleep to prevent issues with the server sleep(randint(3, 5)) # login to instagram account login(driver, usr, pwd) # follow up follow(driver, reader()) # closes all browser windows and ends driver's session. driver.quit()
def test_personal_token_management(settings_fixture): """Test managing personal tokens through the views.""" app = settings_fixture with app.test_request_context(): with app.test_client() as client: login(client) # Non-existing token should return 404 resp = client.get( url_for('invenio_oauth2server_settings.token_view', token_id=1000) ) resp.status_code == 404 # Get the new token form resp = client.get( url_for('invenio_oauth2server_settings.token_new') ) resp.status_code == 200 assert _('New personal access token') in str(resp.get_data()) # Create a new token resp = client.post( url_for('invenio_oauth2server_settings.token_new'), data={ 'name': 'Test_Token', }, follow_redirects=True ) assert resp.status_code == 200 assert 'Personal access token / Test_Token' in str(resp.get_data()) assert 'test:scope' in str(resp.get_data()) assert 'test:scope2' in str(resp.get_data()) token = Token.query.first() # Rename the token resp = client.post( url_for('invenio_oauth2server_settings.token_view', token_id=token.id), data=dict(name='Test_Token_Renamed') ) assert resp.status_code == 200 assert 'Test_Token_Renamed' in str(resp.get_data()) # Token should be visible on index resp = client.get(url_for('invenio_oauth2server_settings.index')) assert resp.status_code == 200 assert 'Test_Token_Renamed' in str(resp.get_data()) # Delete the token resp = client.post( url_for('invenio_oauth2server_settings.token_view', token_id=1), data=dict(delete=True), follow_redirects=True) assert resp.status_code == 200 # Token should no longer exist on index assert 'Test_Token_Renamed' not in str(resp.get_data())
def __init__(self, email, password): helpers.login(email, password) self.files = {} self.files['/'] = dict(st_mode=(S_IFDIR | 0755), st_ctime=time(), st_mtime=time(), st_atime=time(), st_nlink=2)
def test_valid_logout(self): self.app.get('/register', follow_redirects=True) register(self, '*****@*****.**', 'FlaskIsAwesome', 'FlaskIsAwesome') self.app.get('/login', follow_redirects=True) login(self, '*****@*****.**', 'FlaskIsAwesome') response = self.app.get('/logout', follow_redirects=True) self.assertIn(b'Goodbye!', response.data)
def test_add_contact_missing_call(client, session): helpers.register(client, "*****@*****.**", "fluttershy", "UserTACMC") helpers.login(client, "*****@*****.**", "fluttershy") helpers.update_profile(client, "F4JFD", "JN09CX") rv = client.post("/contacts/new", data=dict(gridsquare="JN18CX"), follow_redirects=True) assert b"This field is required." in rv.data
def test_add_contact(client, session): helpers.register(client, "*****@*****.**", "fluttershy", "UserTAC") helpers.login(client, "*****@*****.**", "fluttershy") helpers.update_profile(client, "F0COIN", "JN18CX") rv = helpers.add_contact(client, "F4TEST", "JN11DW") assert b"<td>F4TEST</td>" in rv.data assert b"<td>783.0 Km</td>" in rv.data assert b"<td>179.0</td>" in rv.data assert b"<td>S</td>" in rv.data
def test_change_password(driver, django_db_blocker): login(driver) newpass = secrets.token_urlsafe(32) set_password(driver, newpass) login(driver, test_password=newpass) set_password(driver, test_password)
def test_add_contact_missing_locator(client, session): helpers.register(client, "*****@*****.**", "fluttershy", "UserTACML") helpers.login(client, "*****@*****.**", "fluttershy") helpers.update_profile(client, "F4JFD", "JN09CX") rv = client.post("/contacts/new", data=dict(callsign="F4TEST"), follow_redirects=True) assert b"QTH is too broad or empty, please input valid QTH" in rv.data
def test_user_ui_pref_videos(driver, django_db_blocker): """Test that user preferences are saved and videos are shown.""" login(driver) with django_db_blocker.unblock(): create_test_video(name="test") print("Going to user interface") ui_button = driver.find_element_by_id('user_interface') ui_button.click() WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, 'search_phrase'))) print("Typing search phrase") search_phrase_field = driver.find_element_by_id('search_phrase') search_phrase_field.clear() search_phrase_field.send_keys('test') # random preferences np.random.seed(42) values = np.random.rand(len(VIDEO_FIELDS)) * 100 WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, 'id_search_not_loading'))) for f, v in zip(VIDEO_FIELDS, values): set_slider_value(driver, s_id='preference_slider_' + f, value=v) WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, 'id_search_not_loading'))) WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, 'id_search_not_loading'))) print("Loading recommendations") load_rec_btn = driver.find_element_by_id("load_recommendations") load_rec_btn.click() WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.ID, 'id_search_not_loading'))) entry = do_api_call_v2(driver, url='/user_preferences/my/') values_got = [entry[x] for x in VIDEO_FIELDS] values_transformed = values / 2 + 50 diff = np.max(np.abs(values_transformed - values_got)) assert diff < 5, (values_transformed, values_got) print("Preferences normal", diff) WebDriverWait(driver, TIME_WAIT).until( EC.presence_of_element_located((By.CLASS_NAME, 'video_search_result'))) videos = driver.find_elements_by_class_name('video_search_result') assert videos, "No videos returned in search, or it took too long." print("Got", len(videos), "videos") logout(driver)
def test_implicit_flow(provider_fixture): app = provider_fixture with app.test_request_context(): redirect_uri = url_for('oauth2test.authorized', _external=True) with app.test_client() as client: # First login on provider site login(client) for client_id in ['dev', 'confidential']: data = dict( redirect_uri=redirect_uri, response_type='token', # For implicit grant type client_id=client_id, scope='test:scope', state='teststate' ) # Authorize page r = client.get(url_for( 'invenio_oauth2server.authorize', **data ), follow_redirects=True) assert r.status_code == 200 # User confirms request data['confirm'] = 'yes' data['scope'] = 'test:scope' data['state'] = 'teststate' r = client.post(url_for('invenio_oauth2server.authorize'), data=data) assert r.status_code == 302 # Important - access token exists in URI fragment and must not # be sent to the client. next_url, data = parse_redirect(r.location, parse_fragment=True) assert data['access_token'] assert data['token_type'] == 'Bearer' assert data['state'] == 'teststate' assert data['scope'] == 'test:scope' assert data.get('refresh_token') is None assert next_url == redirect_uri # Authentication flow has now been completed, and the client # can use the access token to make request to the provider. r = client.get(url_for('invenio_oauth2server.info', access_token=data['access_token'])) assert r.status_code == 200 assert json.loads(r.get_data()).get('client') == client_id assert json.loads(r.get_data()).get('user') == app.user1.id assert json.loads(r.get_data()).get('scopes') \ == [u'test:scope']
def test_settings_index(provider_fixture): app = provider_fixture with app.test_request_context(): with app.test_client() as client: # Create a remote account (linked account) r = client.get(url_for("invenio_oauth2server_settings.index"), follow_redirects=True) # assert 401 == r.status_code login(client) res = client.get(url_for("invenio_oauth2server_settings.index")) assert 200 == res.status_code res = client.get(url_for("invenio_oauth2server_settings.client_new")) assert 200 == res.status_code # Valid POST res = client.post( url_for("invenio_oauth2server_settings.client_new"), data=dict( name="Test", description="Test description", website="http://inveniosoftware.org", is_confidential=True, redirect_uris="http://localhost/oauth/authorized/", ), ) assert 302 == res.status_code # Invalid redirect_uri (must be https) res = client.post( url_for("invenio_oauth2server_settings.client_new"), data=dict( name="Test", description="Test description", website="http://inveniosoftware.org", is_confidential=True, redirect_uris="http://example.org/oauth/authorized/", ), ) assert 200 == res.status_code # Valid res = client.post( url_for("invenio_oauth2server_settings.client_new"), data=dict( name="Test", description="Test description", website="http://inveniosoftware.org", is_confidential=True, redirect_uris="https://example.org/oauth/authorized/\n" "http://localhost:4000/oauth/authorized/", ), ) assert 302 == res.status_code
def test_get_current_userprofile(app): """Test get_current_userprofile.""" with app.test_request_context(): profile_url = url_for('invenio_userprofiles.profile') with app.test_client() as client: # Logged in user should have userprofile sign_up(app, client) login(app, client) resp = client.get(profile_url) assert 'name="profile_form"' in resp.get_data(as_text=True) assert current_userprofile.is_anonymous is False assert current_user.id == current_userprofile.user_id
def test_implicit_flow(provider_fixture): app = provider_fixture with app.test_request_context(): redirect_uri = url_for("oauth2test.authorized", _external=True) with app.test_client() as client: # First login on provider site login(client) for client_id in ["dev", "confidential"]: data = dict( redirect_uri=redirect_uri, response_type="token", # For implicit grant type client_id=client_id, scope="test:scope", state="teststate", ) # Authorize page r = client.get(url_for("invenio_oauth2server.authorize", **data), follow_redirects=True) assert r.status_code == 200 # User confirms request data["confirm"] = "yes" data["scope"] = "test:scope" data["state"] = "teststate" r = client.post(url_for("invenio_oauth2server.authorize"), data=data) assert r.status_code == 302 # Important - access token exists in URI fragment and must not # be sent to the client. next_url, data = parse_redirect(r.location, parse_fragment=True) assert data["access_token"] assert data["token_type"] == "Bearer" assert data["state"] == "teststate" assert data["scope"] == "test:scope" assert data.get("refresh_token") is None assert next_url == redirect_uri # Authentication flow has now been completed, and the client # can use the access token to make request to the provider. r = client.get(url_for("invenio_oauth2server.info", access_token=data["access_token"])) assert r.status_code == 200 assert json.loads(r.get_data()).get("client") == client_id assert json.loads(r.get_data()).get("user") == app.user1_id assert json.loads(r.get_data()).get("scopes") == [u"test:scope"]
def test_profile_view(app): """Test the profile view.""" app.config['USERPROFILES_EMAIL_ENABLED'] = False with app.test_request_context(): profile_url = url_for('invenio_userprofiles.profile') with app.test_client() as client: sign_up(app, client) login(app, client) resp = client.get(profile_url) assert resp.status_code == 200 assert 'name="profile_form"' in str(resp.data) # Valid submission should work resp = client.post(profile_url, data=prefix('profile', dict( username=test_usernames['valid'], full_name='Valid Name', ))) assert resp.status_code == 200 data = resp.get_data(as_text=True) assert test_usernames['valid'] in data assert 'Valid' in data assert 'Name' in data # Invalid submission should not save data resp = client.post(profile_url, data=prefix('profile', dict( username=test_usernames['invalid_characters'], full_name='Valid Name', ))) assert resp.status_code == 200 assert test_usernames['invalid_characters'] in \ resp.get_data(as_text=True) resp = client.get(profile_url) assert resp.status_code == 200 assert test_usernames['valid'] in resp.get_data(as_text=True) # Whitespace should be trimmed client.post(profile_url, data=prefix('profile', dict( username='******'.format(test_usernames['valid']), full_name='Valid Name ', ))) resp = client.get(profile_url) assert resp.status_code == 200 data = resp.get_data(as_text=True) assert test_usernames['valid'] in data assert 'Valid Name ' not in data
def test_profile_name_exists(app): """Test the profile view.""" app.config['USERPROFILES_EMAIL_ENABLED'] = False with app.test_request_context(): profile_url = url_for('invenio_userprofiles.profile') # Create an existing user email1 = '*****@*****.**' password1 = '123456' with app.test_client() as client: sign_up(app, client, email=email1, password=password1) login(app, client, email=email1, password=password1) assert client.get(profile_url).status_code == 200 resp = client.post(profile_url, data=prefix('profile', dict( username='******', full_name='Valid Name',))) assert 'has-error' not in resp.get_data(as_text=True) # Create another user and try setting username to same as above user. with app.test_client() as client: sign_up(app, client) login(app, client) resp = client.get(profile_url) assert resp.status_code == 200 resp = client.post(profile_url, data=prefix('profile', dict( username='******', full_name='Another name', ))) assert resp.status_code == 200 assert 'Username already exists.' in resp.get_data(as_text=True) # Now set it to something else and do it twice. data = prefix('profile', dict( username='******', full_name='Another name', )) resp = client.post(profile_url, data=data) assert resp.status_code == 200 assert 'has-error' not in resp.get_data(as_text=True) resp = client.post(profile_url, data=data) assert resp.status_code == 200 assert 'has-error' not in resp.get_data(as_text=True)
def test_send_verification_form(app): """Test send verification form.""" mail = app.extensions['mail'] with app.test_request_context(): profile_url = url_for('invenio_userprofiles.profile') with app.test_client() as client: sign_up(app, client) login(app, client) resp = client.get(profile_url) assert resp.status_code == 200 assert 'You have not yet verified your email address' in \ resp.get_data(as_text=True) with mail.record_messages() as outbox: assert len(outbox) == 0 resp = client.post(profile_url, data=prefix('verification', dict( send_verification_email='Title' ))) assert len(outbox) == 1
def login_page(): if request.method == 'POST': # Handle the login request try: user = helpers.login(request) except LoginException as e: return render_template('login.html', error=e.message) session['logged_in'] = True session['user_id'] = user.id flash('You were logged in') return redirect(url_for('show_entries')) else: # Just display the login page return render_template('login.html', error=None)
def test_not_allowed_public_refresh_flow(expiration_fixture): """Public token should not allow refreshing.""" app = expiration_fixture # First login on provider site with app.test_request_context(): with app.test_client() as client: login(client) data = dict( redirect_uri=url_for("oauth2test.authorized", _external=True), scope="test:scope", response_type="code", client_id="dev", state="mystate", ) r = client.get(url_for("invenio_oauth2server.authorize", **data)) assert r.status_code == 200 data["confirm"] = "yes" data["scope"] = "test:scope" data["state"] = "mystate" # Obtain one time code r = client.post(url_for("invenio_oauth2server.authorize"), data=data) assert r.status_code == 302 next_url, res_data = parse_redirect(r.location) assert res_data["code"] assert res_data["state"] == "mystate" # Exchange one time code for access token r = client.post( url_for("invenio_oauth2server.access_token"), data=dict(client_id="dev", client_secret="dev", grant_type="authorization_code", code=res_data["code"]), ) assert r.status_code == 200 json_resp = json.loads(r.get_data()) assert json_resp["access_token"] assert json_resp["refresh_token"] assert json_resp["expires_in"] > 0 assert json_resp["scope"] == "test:scope" assert json_resp["token_type"] == "Bearer" refresh_token = json_resp["refresh_token"] old_access_token = json_resp["access_token"] # Access token valid r = client.get(url_for("invenio_oauth2server.info", access_token=old_access_token)) assert r.status_code == 200 Token.query.filter_by(access_token=old_access_token).update( dict(expires=datetime.utcnow() - timedelta(seconds=1)) ) db.session.commit() # Access token is expired r = client.get(url_for("invenio_oauth2server.info", access_token=old_access_token), follow_redirects=True) assert r.status_code == 401 # Obtain new access token with refresh token r = client.post( url_for("invenio_oauth2server.access_token"), data=dict( client_id="dev", client_secret="dev", grant_type="refresh_token", refresh_token=refresh_token ), follow_redirects=True, ) # Only confidential clients can refresh expired token. assert r.status_code == 401
def test_invalid_authorize_requests(provider_fixture): app = provider_fixture # First login on provider site with app.test_request_context(): redirect_uri = url_for("oauth2test.authorized", _external=True) with app.test_client() as client: login(client) for client_id in ["dev", "confidential"]: scope = "test:scope" response_type = "code" error_url = url_for("invenio_oauth2server.errors", _external=True) # Valid request authorize request r = client.get( url_for("invenio_oauth2server.authorize"), data={ "redirect_uri": redirect_uri, "scope": scope, "response_type": response_type, "client_id": client_id, }, ) assert r.status_code == 200 # Invalid scope r = client.get( url_for( "invenio_oauth2server.authorize", redirect_uri=redirect_uri, scope="INVALID", response_type=response_type, client_id=client_id, ) ) assert r.status_code == 302 next_url, data = parse_redirect(r.location) assert data["error"] == "invalid_scope" assert next_url == redirect_uri # Invalid response type r = client.get( url_for( "invenio_oauth2server.authorize", redirect_uri=redirect_uri, scope=scope, response_type="invalid", client_id=client_id, ) ) assert r.status_code == 302 next_url, data = parse_redirect(r.location) assert data["error"] == "unsupported_response_type" assert next_url == redirect_uri # Missing response_type r = client.get( url_for( "invenio_oauth2server.authorize", redirect_uri=redirect_uri, scope=scope, client_id=client_id ) ) assert r.status_code == 302 next_url, data = parse_redirect(r.location) assert data["error"] == "invalid_request" assert next_url == redirect_uri # Duplicate parameter r = client.get( url_for( "invenio_oauth2server.authorize", redirect_uri=redirect_uri, scope=scope, response_type="invalid", client_id=client_id, ) + "&client_id={0}".format(client_id) ) assert r.status_code == 302 next_url, data = parse_redirect(r.location) assert data["error"] == "invalid_request" assert next_url == error_url # Invalid client_id r = client.get( url_for( "invenio_oauth2server.authorize", redirect_uri=redirect_uri, scope=scope, response_type=response_type, client_id="invalid", ) ) assert r.status_code == 302 next_url, data = parse_redirect(r.location) assert data["error"] == "invalid_request" assert error_url in next_url r = client.get(next_url, query_string=data) assert "invalid_request" in str(r.data) # Invalid redirect uri r = client.get( url_for( "invenio_oauth2server.authorize", redirect_uri="http://localhost/", scope=scope, response_type=response_type, client_id=client_id, ) ) assert r.status_code == 302 next_url, data = parse_redirect(r.location) assert data["error"] == "invalid_request" assert error_url in next_url
def web_auth_flow(provider_fixture): app = provider_fixture # Go to login - should redirect to oauth2 server for login an # authorization with app.app_context(): with app.test_client() as client: r = client.get("/oauth2test/test-ping") # First login on provider site login(client) r = client.get("/oauth2test/login") assert r.status_code == 302 next_url, data = parse_redirect(r.location) # Authorize page r = client.get(next_url, query_string=data) assert r.status_code == 200 # User confirms request data["confirm"] = "yes" data["scope"] = "test:scope" data["state"] = "" r = client.post(next_url, data=data) assert r.status_code == 302 next_url, data = parse_redirect(r.location) assert next_url == "http://{0}/oauth2test/authorized".format(app.config["SERVER_NAME"]) assert "code" in data # User is redirected back to client site. # - The client view /oauth2test/authorized will in the # background fetch the access token. r = client.get(next_url, query_string=data) assert r.status_code == 200 # Authentication flow has now been completed, and the access # token can be used to access protected resources. r = client.get("/oauth2test/test-ping") assert r.status_code == 200 assert json.loads(r.get_data()) == dict(ping="pong") # Authentication flow has now been completed, and the access # token can be used to access protected resources. r = client.get("/oauth2test/test-ping") assert r.status_code == 200 assert json.loads(r.get_data()) == dict(ping="pong") r = client.get("/oauth2test/test-info") assert r.status_code == 200 json_resp = json.loads(r.get_data()) assert json_resp["client"] == "confidential" assert json_resp["user"] == app.user1_id assert json_resp["scopes"] == [u"test:scope"] # Access token doesn't provide access to this URL. r = client.get("/oauth2test/test-invalid", base_url="http://{0}".format(app.config["SERVER_NAME"])) assert r.status_code == 401 # # Now logout r = client.get("/oauth2test/logout") assert r.status_code == 200 assert r.data == "logout" # And try to access the information again r = client.get("/oauth2test/test-ping") assert r.status_code == 403
def test_client_management(settings_fixture): """Test managing clients through the views.""" app = settings_fixture with app.test_request_context(): with app.test_client() as client: login(client) # Non-existing client should return 404 resp = client.get( url_for('invenio_oauth2server_settings.client_view', client_id=1000) ) assert resp.status_code == 404 # Create a new client resp = client.post( url_for('invenio_oauth2server_settings.client_new'), data=dict( name='Test_Client', description='Test description for Test_Client.', website='http://inveniosoftware.org/', redirect_uris=url_for( 'invenio_oauth2server_settings.index', _external=True), is_confditential=1 ), follow_redirects=True) assert resp.status_code == 200 assert 'Application / Test_Client' in str(resp.get_data()) test_client = Client.query.first() assert test_client.client_id in str(resp.get_data()) # Client should be visible on index resp = client.get(url_for('invenio_oauth2server_settings.index')) assert resp.status_code == 200 assert 'Test_Client' in str(resp.get_data()) # Reset client secret original_client_secret = test_client.client_secret resp = client.post( url_for('invenio_oauth2server_settings.client_reset', client_id=test_client.client_id), data=dict(reset='yes'), follow_redirects=True ) assert resp.status_code == 200 assert test_client.client_secret in str(resp.get_data()) assert original_client_secret not in str(resp.get_data()) # Invalid redirect uri should error original_redirect_uris = test_client.redirect_uris resp = client.post( url_for('invenio_oauth2server_settings.client_view', client_id=test_client.client_id), data=dict( name='Test_Client', description='Test description for Test_Client', website='http://inveniosoftware.org/', redirect_uris='https:/invalid', ) ) assert resp.status_code == 200 assert test_client.redirect_uris == original_redirect_uris # Modify the client resp = client.post( url_for('invenio_oauth2server_settings.client_view', client_id=test_client.client_id), data=dict( name='Modified_Name', description='Modified Description', website='http://modified-url.org', redirect_uris='https://example.org', ) ) assert resp.status_code == 200 assert 'Modified_Name' in str(resp.get_data()) assert 'Modified Description' in str(resp.get_data()) assert 'http://modified-url.org' in str(resp.get_data()) # Delete the client resp = client.post( url_for('invenio_oauth2server_settings.client_view', client_id=test_client.client_id), follow_redirects=True, data=dict(delete=True) ) assert resp.status_code == 200 assert test_client.name not in str(resp.get_data())
def test_change_email(app): """Test send verification form.""" mail = app.extensions['mail'] with app.test_request_context(): profile_url = url_for('invenio_userprofiles.profile') # Create an existing user email1 = '*****@*****.**' password1 = '123456' with app.test_client() as client: sign_up(app, client, email=email1, password=password1) login(app, client, email=email1, password=password1) assert client.get(profile_url).status_code == 200 with app.test_client() as client: sign_up(app, client) login(app, client) resp = client.get(profile_url) assert resp.status_code == 200 data = prefix('profile', dict( username='******', full_name='Test User', email=app.config['TEST_USER_EMAIL'], email_repeat=app.config['TEST_USER_EMAIL'], )) # Test that current_user stops validation of email client.post(profile_url, data=data) assert resp.status_code == 200 assert 'has-error' not in resp.get_data(as_text=True) # Test existing email of another user. data['profile-email_repeat'] = data['profile-email'] = email1 resp = client.post(profile_url, data=data) assert 'has-error' in resp.get_data(as_text=True) # Test empty email data['profile-email_repeat'] = data['profile-email'] = '' resp = client.post(profile_url, data=data) assert 'has-error' in resp.get_data(as_text=True) # Test not an email data['profile-email_repeat'] = data['profile-email'] = 'sadfsdfs' resp = client.post(profile_url, data=data) assert 'has-error' in resp.get_data(as_text=True) # Test different emails data['profile-email_repeat'] = '*****@*****.**' data['profile-email'] = '*****@*****.**' resp = client.post(profile_url, data=data) assert 'has-error' in resp.get_data(as_text=True) # Test whitespace with mail.record_messages() as outbox: assert len(outbox) == 0 data['profile-email_repeat'] = data['profile-email'] = '*****@*****.**' resp = client.post(profile_url, data=data) assert 'has-error' not in resp.get_data(as_text=True) # Email was sent for email address confirmation. assert len(outbox) == 1
def test_invalid_authorize_requests(provider_fixture): app = provider_fixture # First login on provider site with app.test_request_context(): redirect_uri = url_for('oauth2test.authorized', _external=True) with app.test_client() as client: login(client) for client_id in ['dev', 'confidential']: scope = 'test:scope' response_type = 'code' error_url = url_for('invenio_oauth2server.errors') # Valid request authorize request r = client.get( url_for('invenio_oauth2server.authorize'), data={ 'redirect_uri': redirect_uri, 'scope': scope, 'response_type': response_type, 'client_id': client_id, }) assert r.status_code == 200 # Invalid scope r = client.get(url_for( 'invenio_oauth2server.authorize', redirect_uri=redirect_uri, scope='INVALID', response_type=response_type, client_id=client_id, )) assert r.status_code == 302 next_url, data = parse_redirect(r.location) assert data['error'] == 'invalid_scope' assert next_url == redirect_uri # Invalid response type r = client.get(url_for( 'invenio_oauth2server.authorize', redirect_uri=redirect_uri, scope=scope, response_type='invalid', client_id=client_id, )) assert r.status_code == 302 next_url, data = parse_redirect(r.location) assert data['error'] == 'unauthorized_client' assert next_url == redirect_uri # Missing response_type r = client.get(url_for( 'invenio_oauth2server.authorize', redirect_uri=redirect_uri, scope=scope, client_id=client_id, )) assert r.status_code == 302 next_url, data = parse_redirect(r.location) assert data['error'] == 'invalid_request' assert next_url == redirect_uri # Duplicate parameter r = client.get(url_for( 'invenio_oauth2server.authorize', redirect_uri=redirect_uri, scope=scope, response_type='invalid', client_id=client_id, ) + "&client_id={0}".format(client_id)) assert r.status_code == 302 next_url, data = parse_redirect(r.location) assert data['error'] == 'invalid_request' assert next_url == redirect_uri # Invalid client_id r = client.get(url_for( 'invenio_oauth2server.authorize', redirect_uri=redirect_uri, scope=scope, response_type=response_type, client_id='invalid', )) assert r.status_code == 302 next_url, data = parse_redirect(r.location) assert data['error'] == 'invalid_client_id' assert error_url in next_url r = client.get(next_url, query_string=data) assert 'invalid_client_id' in str(r.data) # Invalid redirect uri r = client.get(url_for( 'invenio_oauth2server.authorize', redirect_uri='http://localhost/', scope=scope, response_type=response_type, client_id=client_id, )) assert r.status_code == 302 next_url, data = parse_redirect(r.location) assert data['error'] == 'mismatching_redirect_uri' assert error_url in next_url
def test_refresh_flow(provider_fixture): app = provider_fixture with app.test_request_context(): base_url = "https://{0}".format(app.config["SERVER_NAME"]) redirect_uri = url_for("oauth2test.authorized", _external=True) with app.test_client() as client: # First login on provider site login(client) data = dict( redirect_uri=redirect_uri, scope="test:scope", response_type="code", client_id="confidential", state="mystate", ) r = client.get(url_for("invenio_oauth2server.authorize", **data)) assert r.status_code == 200 data["confirm"] = "yes" data["scope"] = "test:scope" data["state"] = "mystate" # Obtain one time code r = client.post(url_for("invenio_oauth2server.authorize"), data=data) r.status_code == 302 next_url, res_data = parse_redirect(r.location) assert res_data["code"] assert res_data["state"] == "mystate" # Exchange one time code for access token r = client.post( url_for("invenio_oauth2server.access_token"), data=dict( client_id="confidential", client_secret="confidential", grant_type="authorization_code", code=res_data["code"], ), ) assert r.status_code == 200 json_resp = json.loads(r.get_data()) assert json_resp["access_token"] assert json_resp["refresh_token"] assert json_resp["scope"] == "test:scope" assert json_resp["token_type"] == "Bearer" refresh_token = json_resp["refresh_token"] old_access_token = json_resp["access_token"] # Access token valid r = client.get(url_for("invenio_oauth2server.info", access_token=old_access_token)) assert r.status_code == 200 # Obtain new access token with refresh token r = client.post( url_for("invenio_oauth2server.access_token"), data=dict( client_id="confidential", client_secret="confidential", grant_type="refresh_token", refresh_token=refresh_token, ), ) r.status_code == 200 json_resp = json.loads(r.get_data()) assert json_resp["access_token"] assert json_resp["refresh_token"] assert json_resp["access_token"] != old_access_token assert json_resp["refresh_token"] != refresh_token assert json_resp["scope"] == "test:scope" assert json_resp["token_type"] == "Bearer" # New access token valid r = client.get(url_for("invenio_oauth2server.info", access_token=json_resp["access_token"])) assert r.status_code == 200 # Old access token no longer valid r = client.get(url_for("invenio_oauth2server.info", access_token=old_access_token), base_url=base_url) assert r.status_code == 401
def test_refresh_flow(provider_fixture): app = provider_fixture with app.test_request_context(): base_url = 'https://{0}'.format(app.config['SERVER_NAME']) redirect_uri = url_for('oauth2test.authorized', _external=True) with app.test_client() as client: # First login on provider site login(client) data = dict( redirect_uri=redirect_uri, scope='test:scope', response_type='code', client_id='confidential', state='mystate' ) r = client.get(url_for('invenio_oauth2server.authorize', **data)) assert r.status_code == 200 data['confirm'] = 'yes' data['scope'] = 'test:scope' data['state'] = 'mystate' # Obtain one time code r = client.post( url_for('invenio_oauth2server.authorize'), data=data ) r.status_code == 302 next_url, res_data = parse_redirect(r.location) assert res_data['code'] assert res_data['state'] == 'mystate' # Exchange one time code for access token r = client.post( url_for('invenio_oauth2server.access_token'), data=dict( client_id='confidential', client_secret='confidential', grant_type='authorization_code', code=res_data['code'], ) ) assert r.status_code == 200 json_resp = json.loads(r.get_data()) assert json_resp['access_token'] assert json_resp['refresh_token'] assert json_resp['scope'] == 'test:scope' assert json_resp['token_type'] == 'Bearer' refresh_token = json_resp['refresh_token'] old_access_token = json_resp['access_token'] # Access token valid r = client.get(url_for('invenio_oauth2server.info', access_token=old_access_token)) assert r.status_code == 200 # Obtain new access token with refresh token r = client.post( url_for('invenio_oauth2server.access_token'), data=dict( client_id='confidential', client_secret='confidential', grant_type='refresh_token', refresh_token=refresh_token, ) ) r.status_code == 200 json_resp = json.loads(r.get_data()) assert json_resp['access_token'] assert json_resp['refresh_token'] assert json_resp['access_token'] != old_access_token assert json_resp['refresh_token'] != refresh_token assert json_resp['scope'] == 'test:scope' assert json_resp['token_type'] == 'Bearer' # New access token valid r = client.get(url_for('invenio_oauth2server.info', access_token=json_resp['access_token'])) assert r.status_code == 200 # Old access token no longer valid r = client.get(url_for('invenio_oauth2server.info', access_token=old_access_token,), base_url=base_url) assert r.status_code == 401
def web_auth_flow(provider_fixture): app = provider_fixture # Go to login - should redirect to oauth2 server for login an # authorization with app.app_context(): with app.test_client() as client: r = client.get('/oauth2test/test-ping') # First login on provider site login(client) r = client.get('/oauth2test/login') assert r.status_code == 302 next_url, data = parse_redirect(r.location) # Authorize page r = client.get(next_url, query_string=data) assert r.status_code == 200 # User confirms request data['confirm'] = 'yes' data['scope'] = 'test:scope' data['state'] = '' r = client.post(next_url, data=data) assert r.status_code == 302 next_url, data = parse_redirect(r.location) assert next_url == 'http://{0}/oauth2test/authorized'.format( app.config['SERVER_NAME']) assert 'code' in data # User is redirected back to client site. # - The client view /oauth2test/authorized will in the # background fetch the access token. r = client.get(next_url, query_string=data) assert r.status_code == 200 # Authentication flow has now been completed, and the access # token can be used to access protected resources. r = client.get('/oauth2test/test-ping') assert r.status_code == 200 assert json.loads(r.get_data()) == dict(ping='pong') # Authentication flow has now been completed, and the access # token can be used to access protected resources. r = client.get('/oauth2test/test-ping') assert r.status_code == 200 assert json.loads(r.get_data()) == dict(ping='pong') r = client.get('/oauth2test/test-info') assert r.status_code == 200 json_resp = json.loads(r.get_data()) assert json_resp['client'] == 'confidential' assert json_resp['user'] == app.user1.id assert json_resp['scopes'] == [u'test:scope'] # Access token doesn't provide access to this URL. r = client.get( '/oauth2test/test-invalid', base_url='http://{0}'.format(app.config['SERVER_NAME']) ) assert r.status_code == 401 # # Now logout r = client.get('/oauth2test/logout') assert r.status_code == 200 assert r.data == "logout" # And try to access the information again r = client.get('/oauth2test/test-ping') assert r.status_code == 403