def test_last_modified(self): """Check that the last modified field is set. """ profile = UserProfile() self.session.add(profile) self.session.flush() user = User(id=profile.document_id, username='******', name='user', forum_username='******', email_validated=True, email='*****@*****.**', password='******') self.session.add(user) self.session.flush() self.session.refresh(user) self.assertIsNotNone(user.last_modified) user.name = 'changed' self.session.flush() self.session.refresh(user) self.assertIsNotNone(user.last_modified)
def test_validate_password(self): tony = User(username='******', email_validated=True, email='*****@*****.**', password='******') self.assertFalse(tony.validate_password('foobare')) self.assertTrue(tony.validate_password('foobar'))
def test_validate_password(self): tony = User( username='******', email_validated=True, email='*****@*****.**', password='******' ) self.assertFalse(tony.validate_password('foobare')) self.assertTrue(tony.validate_password('foobar'))
def _add_global_test_data(session): global_passwords['contributor'] = 'super pass' global_passwords['contributor2'] = 'better pass' global_passwords['moderator'] = 'even better pass' contributor_profile = UserProfile( categories=['amateur'], locales=[ DocumentLocale(title='', description='Me', lang='en'), DocumentLocale(title='', description='Moi', lang='fr')], geometry=DocumentGeometry(geom='SRID=3857;POINT(635956 5723604)')) contributor = User( name='Contributor', username='******', email='*****@*****.**', forum_username='******', password='******', email_validated=True, profile=contributor_profile) contributor2_profile = UserProfile( categories=['amateur'], locales=[DocumentLocale(title='...', lang='en')]) contributor2 = User( name='Contributor 2', username='******', email='*****@*****.**', forum_username='******', password='******', email_validated=True, profile=contributor2_profile) moderator_profile = UserProfile( categories=['mountain_guide'], locales=[DocumentLocale(title='', lang='en')]) moderator = User( name='Moderator', username='******', email='*****@*****.**', forum_username='******', moderator=True, password='******', email_validated=True, profile=moderator_profile) users = [moderator, contributor, contributor2] session.add_all(users) session.flush() key = settings['jwtauth.master_secret'] algorithm = 'HS256' now = datetime.datetime.utcnow() exp = now + datetime.timedelta(weeks=10) for user in [moderator, contributor, contributor2]: claims = create_claims(user, exp) token = jwt.encode(claims, key=key, algorithm=algorithm). \ decode('utf-8') add_or_retrieve_token(token, exp, user.id) global_userids[user.username] = user.id global_tokens[user.username] = token
def test_update_nonce(self): tony = User(email_validated=False) tony.update_validation_nonce(Purpose.registration, 2) def change_email(): tony.update_validation_nonce(Purpose.change_email, 2) self.assertRaisesRegexp( Exception, 'Account not validated', change_email) tony.email_validated = True change_email()
def test_validate_password(self): tony = User( username='******', email='*****@*****.**', password='******' ) self.assertPassword(tony, 'foobare', False) self.assertPassword(tony, 'foobar', True) tony.set_temp_password('bouchon') self.assertPassword(tony, 'foobare', False) self.assertPassword(tony, 'foobar', True) self.assertPassword(tony, 'bouchon', True, expect_update=True)
def test_update_cache_version_user_document_version(self): """ Test that a document is invalidated if a user name of a user that edited one of the document versions is changed. """ waypoint = Waypoint(waypoint_type='summit', elevation=2203, locales=[ WaypointLocale(lang='en', title='...', description='...') ]) user_profile = UserProfile() user = User(name='test_user', username='******', email='*****@*****.**', forum_username='******', password='******', email_validated=True, profile=user_profile) self.session.add_all([waypoint, user_profile, user]) self.session.flush() DocumentRest.create_new_version(waypoint, user.id) update_cache_version(user_profile) cache_version_user_profile = self.session.query(CacheVersion).get( user_profile.document_id) cache_version_waypoint = self.session.query(CacheVersion).get( waypoint.document_id) self.assertEqual(cache_version_waypoint.version, 2) self.assertEqual(cache_version_user_profile.version, 2)
def test_check_changes_on_user_deletion_error(self): """try to delete a user that is still referenced in a "change" """ user = User(name='test', username='******', email='*****@*****.**', forum_username='******', moderator=True, password='******', email_validated=True, profile=UserProfile(categories=['amateur'])) self.session.add(user) self.session.flush() user_ids = [user.id] change = DocumentChange(user=self.user1, change_type='created', document=self.waypoint, document_type=WAYPOINT_TYPE, area_ids=[], user_ids=user_ids) self.session.add(change) self.session.flush() try: self.session.delete(user) self.session.flush() except Exception as exc: self.assertTrue('still references user id' in exc.orig.pgerror) else: self.fail('user is still referenced in change')
def _add_test_data(self): user_id = self.global_userids['contributor'] self.profile1 = self.session.query(UserProfile).get(user_id) self.locale_en = self.profile1.get_locale('en') self.locale_fr = self.profile1.get_locale('fr') DocumentRest.create_new_version(self.profile1, user_id) self.profile2 = UserProfile(categories=['amateur']) self.session.add(self.profile2) self.profile3 = UserProfile(categories=['amateur']) self.session.add(self.profile3) self.profile4 = UserProfile(categories=['amateur']) self.profile4.locales.append( DocumentLocale(lang='en', description='You', title='')) self.profile4.locales.append( DocumentLocale(lang='fr', description='Toi', title='')) self.session.add(self.profile4) self.session.flush() # create users for the profiles self.user2 = User(name='user2', username='******', email='*****@*****.**', forum_username='******', password='******', email_validated=True, profile=self.profile2) self.user3 = User(name='user3', username='******', email='*****@*****.**', forum_username='******', password='******', email_validated=False, profile=self.profile3) self.user4 = User(name='user4', username='******', email='*****@*****.**', forum_username='******', password='******', email_validated=True, profile=self.profile4) self.session.add_all([self.user2, self.user3, self.user4]) self.session.flush()
def test_registration_confirmation(self): user = User(email='me@localhost', lang='en') link = 'http://somelink' outbox_count = self.get_email_box_length() self.email_service.send_registration_confirmation(user, link) self.assertEqual(self.get_email_box_length(), outbox_count + 1) self.assertIn("Registration", self.get_last_email().subject) self.assertIn("To activate", self.get_last_email().body) self.assertIn(link, self.get_last_email().body)
def test_last_modified(self): """Check that the last modified field is set. """ profile = UserProfile() self.session.add(profile) self.session.flush() user = User( id=profile.document_id, username='******', name='user', forum_username='******', email_validated=True, email='*****@*****.**', password='******') self.session.add(user) self.session.flush() self.session.refresh(user) self.assertIsNotNone(user.last_modified) user.name = 'changed' self.session.flush() self.session.refresh(user) self.assertIsNotNone(user.last_modified)
def test_registration_confirmation(self, _send_email): user = User(email='me@localhost', lang='en') link = 'http://somelink' self.email_service.send_registration_confirmation(user, link) _send_email.assert_called_once_with( 'me@localhost', subject='Registration on Camptocamp.org', body='''Hello To activate your account click on http://somelink Thank you very much The Camptocamp.org team''')
def test_check_changes_on_user_deletion_ok(self): """try to delete a user that is not referenced in a "change" """ user = User(name='test', username='******', email='*****@*****.**', forum_username='******', moderator=True, password='******', email_validated=True, profile=UserProfile(categories=['amateur'])) self.session.add(user) self.session.flush() self.session.delete(user) self.session.flush()
def _add_global_test_data(session): global_passwords['contributor'] = 'super pass' global_passwords['contributor2'] = 'better pass' global_passwords['moderator'] = 'even better pass' global_passwords['robot'] = 'bombproof pass' contributor_profile = UserProfile( categories=['amateur'], locales=[ DocumentLocale(title='', description='Me', lang='en'), DocumentLocale(title='', description='Moi', lang='fr')], geometry=DocumentGeometry(geom='SRID=3857;POINT(635956 5723604)')) contributor = User( name='Contributor', username='******', email='*****@*****.**', forum_username='******', password='******', email_validated=True, profile=contributor_profile) contributor2_profile = UserProfile( categories=['amateur'], locales=[DocumentLocale(title='...', lang='en')]) contributor2 = User( name='Contributor 2', username='******', email='*****@*****.**', forum_username='******', password='******', email_validated=True, profile=contributor2_profile) contributor3_profile = UserProfile( categories=['amateur'], locales=[DocumentLocale(title='...', lang='en')]) contributor3 = User( name='Contributor 3', username='******', email='*****@*****.**', forum_username='******', password='******', email_validated=True, profile=contributor3_profile) moderator_profile = UserProfile( categories=['mountain_guide'], locales=[DocumentLocale(title='', lang='en')]) moderator = User( name='Moderator', username='******', email='*****@*****.**', forum_username='******', moderator=True, password='******', email_validated=True, profile=moderator_profile) robot_profile = UserProfile( locales=[DocumentLocale(title='', lang='en')]) robot = User( name='Robot', username='******', email='*****@*****.**', forum_username='******', robot=True, password='******', email_validated=True, profile=robot_profile) users = [robot, moderator, contributor, contributor2, contributor3] session.add_all(users) session.flush() domain = 'www.somewhere.com' sso_key = SsoKey( domain=domain, key=domain ) session.add(sso_key) sso_external_id = SsoExternalId( domain=domain, external_id='1', user=contributor, token='token', expire=utc.localize(datetime.datetime.utcnow()), ) session.add(sso_external_id) session.flush() key = settings['jwtauth.master_secret'] algorithm = 'HS256' now = datetime.datetime.utcnow() exp = now + datetime.timedelta(weeks=10) for user in [robot, moderator, contributor, contributor2, contributor3]: claims = create_claims(user, exp) token = jwt.encode(claims, key=key, algorithm=algorithm). \ decode('utf-8') add_or_retrieve_token(token, exp, user.id) global_userids[user.username] = user.id global_tokens[user.username] = token
def main(argv=sys.argv): settings_file = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'loadtests.ini') settings = get_appsettings(settings_file) engine = engine_from_config(settings, 'sqlalchemy.') logging.basicConfig() logging.getLogger('sqlalchemy.engine').setLevel(logging.WARN) Session = sessionmaker() # noqa register(Session) session = Session(bind=engine) with transaction.manager: for i in range(1, NB_USERS_TO_CREATE + 1): username = BASE_USERNAME + str(i) password = username email = username + '@foo.bar' lang = 'fr' profile = UserProfile( categories=['amateur'], geometry=DocumentGeometry( version=1, geom=None, geom_detail=None), locales=[DocumentLocale(lang=lang, title='')] ) user = User( username=username, forum_username=username, name=username, email=email, lang=lang, password=password, profile=profile ) # make sure user account is directly validated user.clear_validation_nonce() user.email_validated = True session.add(user) session.flush() # also create a version for the profile # code from DocumentRest.create_new_version archive = user.profile.to_archive() archive_locales = user.profile.get_archive_locales() archive_geometry = user.profile.get_archive_geometry() meta_data = HistoryMetaData(comment='creation', user_id=user.id) versions = [] for locale in archive_locales: version = DocumentVersion( document_id=user.profile.document_id, lang=locale.lang, document_archive=archive, document_locales_archive=locale, document_geometry_archive=archive_geometry, history_metadata=meta_data ) versions.append(version) session.add(archive) session.add_all(archive_locales) session.add(meta_data) session.add_all(versions) session.flush() print('Created %d users with base username `%s`' % ( NB_USERS_TO_CREATE, BASE_USERNAME))
def post(self): """ Synchronize user details and return authentication url. Important: Email addresses need to be validated by external site. """ request = self.request sso_key = request.validated['sso_key'] sso_external_id = request.validated['sso_external_id'] user = request.validated['sso_user'] if user is None: # create new user user = User( username=request.validated['username'], name=request.validated['name'], forum_username=request.validated['forum_username'], email=request.validated['email'], email_validated=True, # MUST be validated by external site lang=request.validated['lang'], password=generate_token() # random password ) # directly create the user profile, the document id of the profile # is the user id lang = user.lang user.profile = UserProfile( categories=['amateur'], locales=[DocumentLocale(lang=lang, title='')], ) DBSession.add(user) DBSession.flush() if sso_external_id is None: sso_external_id = SsoExternalId( domain=sso_key.domain, external_id=request.validated['external_id'], user=user, ) DBSession.add(sso_external_id) sso_external_id.token = generate_token() sso_external_id.expire = sso_expire_from_now() client = get_discourse_client(request.registry.settings) discourse_userid = call_discourse(get_discourse_userid, client, user.id) if discourse_userid is None: call_discourse(client.sync_sso, user) discourse_userid = client.get_userid(user.id) # From cache # Groups are added to discourse, not removed group_ids = [] discourse_groups = None groups = request.validated['groups'] or '' for group_name in groups.split(','): if group_name == '': continue group_id = None if discourse_groups is None: discourse_groups = call_discourse(client.client.groups) group_id = None for discourse_group in discourse_groups: if discourse_group['name'] == group_name: group_id = discourse_group['id'] if group_id is None: # If group is not found, we ignore it as we want to return # a valid token for user authentication pass else: group_ids.append(group_id) for group_id in group_ids: call_discourse(client.client.add_user_to_group, group_id, discourse_userid) return { 'url': '{}/sso-login?no_redirect&{}'.format( request.registry.settings['ui.url'], urlencode({'token': sso_external_id.token})) }