def submit_success(self, appstruct): user = User( email=appstruct.get('email'), fullname=appstruct.get('fullname'), affiliate=appstruct.get('affiliate'), billing_email=appstruct.get('billing_email'), valid_to=appstruct.get('valid_to'), last_payment=appstruct.get('last_payment'), groups=[Group.by_id(group_id) for group_id in appstruct.get('groups', [])], # noqa properties=[UserProperty(key=prop.get('key'), value=prop.get('value')) # noqa for prop in appstruct.get('properties', [])], ) if appstruct.get('password'): # pragma: no branch user.password = encrypt(appstruct['password']) Session.add(user) Session.flush() self.request.registry.notify( UserCreated( self.request, user, appstruct.get('password'), u'Created manually by {}'.format(self.request.user.email) ) ) self.request.session.flash(u'User "{}" added.'.format(user.email)) return HTTPFound( location=self.request.route_path('user_view', user_id=user.id))
def test_unique_constraint(self): Session.add(UserProperty(key='foo', user_id=1)) Session.flush() with self.assertRaises(IntegrityError) as cm: Session.add(UserProperty(key='foo', user_id=1)) Session.flush() self.assertIn('key, user_id are not unique', cm.exception.message)
def includeme(config): registry = config.registry settings = registry.settings config.include('pyramid_basemodel') config.include('pyramid_tm') models = [(interfaces.IActivationClass, Activation), (interfaces.IUserClass, User), (interfaces.IUIStrings, UIStringsBase), (IConsumerClass, Consumer), (IDBSession, Session)] for iface, imp in models: if not registry.queryUtility(iface): registry.registerUtility(imp, iface) if asbool(settings.get('basemodel.should_create_all', True)): key = settings['api.key'] secret = settings.get('api.secret') ttl = settings.get('api.ttl', auth.DEFAULT_TTL) session = Session() consumer = session.query(Consumer).filter(Consumer.key == key).first() if not consumer: with transaction.manager: consumer = Consumer(key=key, secret=secret, ttl=ttl) session.add(consumer) session.flush()
def setUp(self): from pyramid_bimt.views import DatatablesDataView from pyramid_bimt.models import AuditLogEntry from pyramid_bimt.models import User self.config = testing.setUp() initTestingDB(auditlog_types=True, users=True, groups=True) self.request = testing.DummyRequest(user=User.by_email('*****@*****.**')) self.view = DatatablesDataView(self.request) self.view.model = mock.Mock() self.view.columns = OrderedDict() self.view.columns['foo'] = None self.view.columns['bar'] = None Session.add( AuditLogEntry(user=User.by_email('*****@*****.**'), comment=u'föo')) Session.add( AuditLogEntry(user=User.by_email('*****@*****.**'), comment=u'bar')) Session.flush() class DummyDatatablesAJAXView(DatatablesDataView): model = AuditLogEntry columns = OrderedDict() columns['id'] = None columns['comment'] = None def populate_columns(self, entry): self.columns['id'] = entry.id self.columns['comment'] = entry.comment self.columns['DT_RowClass'] = 'info' self.datatable_view = DummyDatatablesAJAXView
def test_success(self): "User can delete itself" self.add_user_root() user = self.makeUser('thruflo', 'Password') Session.add(user) self.authenticate() # Attempt to delete user res = self.app.get('/users/thruflo/delete_user') # Verify confirmation message self.assertTrue('Are you really sure' in res.body) # Verify that the user has not yet been deleted self.assertTrue(get_existing_user(username='******') is not None) # Delete the user res = self.app.post('/users/thruflo/delete_user') # Verify that the user has now been deleted self.assertTrue(get_existing_user(username='******') is None) # User should be logged out self.assertTrue(len(res.headers['Set-Cookie']) < 200)
def test_sucess(self): "If all conditions are met, change password" # Create a user. user = self.makeUser('thruflo', 'Password') Session.add(user) old_hash = user.password self.authenticate() # Attempt to change password. post_data = { 'old_password': '******', 'new_password': '******', 'new_confirm': 'sworDpas', 'next': '/foo/bar', } res = self.app.post('/auth/change_password', post_data) # Verify that password has changed Session.add(user) Session.refresh(user) self.assertNotEquals(user.password, old_hash) # Verify redirect self.assertEquals(res.headers['Location'], 'http://localhost/foo/bar')
def test_success(self): "Set preferred email address" # Create user with email address user = self.makeUserWithEmail() # Add another one user.emails.append( model.Email(address=u'*****@*****.**', is_preferred=True)) model.save(user) transaction.commit() Session.add(user) email1, email2 = user.emails # Sanity check self.assertNotEquals(user.preferred_email, email1) self.assertEquals(user.preferred_email, email2) # Attempt to make the address primary self.authenticate() self.app.post('/auth/prefer_email', {'email_address': email1.address}) # Verify that email is not the user's preferred email Session.add(email1) Session.refresh(email1) self.assertEquals(user.preferred_email, email1) self.assertNotEquals(user.preferred_email, email2)
def test_sucess(self): "If all conditions are met, change password" # Create a user. user = self.makeUser("thruflo", "Password") Session.add(user) old_hash = user.password self.authenticate() # Attempt to change password. post_data = { "old_password": "******", "new_password": "******", "new_confirm": "sworDpas", "next": "/foo/bar", } res = self.app.post("/auth/change_password", post_data) # Verify that password has changed Session.add(user) Session.refresh(user) self.assertNotEquals(user.password, old_hash) # Verify redirect self.assertEquals(res.headers["Location"], "http://localhost/foo/bar")
def test_sucess_logs_user_out(self): "Changing a user password logs the user out." from pyramid_simpleauth.events import UserLoggedOut from pyramid_simpleauth.model import User mock_subscriber = Mock() self.config = config_factory() self.config.add_subscriber(mock_subscriber, UserLoggedOut) self.app = TestApp(self.config.make_wsgi_app()) # Create a user. user = self.makeUser('thruflo', 'Password') Session.add(user) old_hash = user.password self.authenticate() # Attempt to change password. post_data = { 'old_password': '******', 'new_password': '******', 'new_confirm': 'sworDpas', 'next': '/foo/bar', } res = self.app.post('/auth/change_password', post_data) # Verify logged out. self.assertTrue(len(res.headers['Set-Cookie']) < 200) # Handler was called with the authentiated user as the second arg. self.assertTrue(mock_subscriber.called) event = mock_subscriber.call_args_list[0][0][0] self.assertTrue(isinstance(event.user, User))
def test_success(self): "Token is valid, email address should be confirmed" # Create a user user = self.makeUserWithEmail() # Sanity check self.assertFalse(user.emails[0].is_confirmed) # Get valid confirmation link email = user.emails[0] confirmation_link = self.makeConfirmationLink(email) # Attempt to confirm email address res = self.app.get(confirmation_link) self.assertTrue(res.location.endswith('victory_path')) # Now configure settings with a route that doesn't exist settings = {'simpleauth.after_confirm_email_route': 'success_path'} self.config = config_factory(**settings) # Not adding the route! self.app = TestApp(self.config.make_wsgi_app()) res = self.app.get(confirmation_link) self.assertEquals(res.location, 'http://localhost/') # Verify that email address has been confirmed Session.add(email) Session.refresh(email) self.assertTrue(email.is_confirmed)
def test_success(self): "Set preferred email address" # Create user with email address user = self.makeUserWithEmail() # Add another one user.emails.append(model.Email(address=u'*****@*****.**', is_preferred=True)) model.save(user) transaction.commit() Session.add(user) email1, email2 = user.emails # Sanity check self.assertNotEquals(user.preferred_email, email1) self.assertEquals(user.preferred_email, email2) # Attempt to make the address primary self.authenticate() self.app.post('/auth/prefer_email', { 'email_address': email1.address }) # Verify that email is not the user's preferred email Session.add(email1) Session.refresh(email1) self.assertEquals(user.preferred_email, email1) self.assertNotEquals(user.preferred_email, email2)
def test_wrong_old_password(self): "No password change if old password is not corret" # Create a user. user = self.makeUser("thruflo", "Password") Session.add(user) old_hash = user.password self.authenticate() # Attempt to change password. post_data = { "old_password": "******", "new_password": "******", "new_confirm": "swordpas", "next": "/foo/bar", } res = self.app.post("/auth/change_password", post_data) # Verify that password hasn't changed Session.add(user) Session.refresh(user) self.assertTrue("Wrong current password" in res.body) self.assertTrue("/foo/bar" in res.body) self.assertEquals(user.password, old_hash)
def includeme(config): registry = config.registry config.include('pyramid_basemodel') config.include('pyramid_tm') config.set_request_property(lib.user_property, 'user') if not registry.queryUtility(interfaces.IDBSession): registry.registerUtility(Session, interfaces.IDBSession) if not registry.queryUtility(interfaces.IUserClass): registry.registerUtility(User, interfaces.IUserClass) if not registry.queryUtility(interfaces.IConsumerClass): registry.registerUtility(Consumer, interfaces.IConsumerClass) if not registry.queryUtility(interfaces.IActivationClass): registry.registerUtility(Activation, interfaces.IActivationClass) settings = config.get_settings() key = settings['api.key'] secret = settings.get('api.secret') ttl = settings.get('api.ttl', DEFAULT_TTL) session = Session() with transaction.manager: consumer = Consumer.get_by_key(key) if not consumer: consumer = Consumer(key=key) consumer.secret = secret consumer.ttl = ttl session.add(consumer) session.flush() registry.consumer = consumer
def test_wrong_old_password(self): "No password change if old password is not corret" # Create a user. user = self.makeUser('thruflo', 'Password') Session.add(user) old_hash = user.password self.authenticate() # Attempt to change password. post_data = { 'old_password': '******', 'new_password': '******', 'new_confirm': 'swordpas', 'next': '/foo/bar', } res = self.app.post('/auth/change_password', post_data) # Verify that password hasn't changed Session.add(user) Session.refresh(user) self.assertTrue("Wrong current password" in res.body) self.assertTrue("/foo/bar" in res.body) self.assertEquals(user.password, old_hash)
def submit_success(self, appstruct): group = Group( name=appstruct.get('name'), product_id=appstruct.get('product_id'), validity=appstruct.get('validity'), trial_validity=appstruct.get('trial_validity'), addon=appstruct.get('addon'), forward_ipn_to_url=appstruct.get('forward_ipn_to_url'), users=[ User.by_id(user_id) for user_id in appstruct.get('users', []) ], # noqa upgrade_groups=[ Group.by_id(group_id) for group_id in appstruct.get('upgrade_groups', []) ], # noqa properties=[ GroupProperty(key=prop['key'], value=prop['value']) for prop in appstruct.get('properties', []) ], ) Session.add(group) Session.flush() self.request.session.flash(u'Group "{}" added.'.format(group.name)) return HTTPFound( location=self.request.route_path('group_edit', group_id=group.id))
def includeme(config): registry = config.registry config.include('pyramid_basemodel') config.include('pyramid_tm') config.set_request_property(lib.user_property, 'user') if not registry.queryUtility(IDBSession): registry.registerUtility(Session, IDBSession) if not registry.queryUtility(interfaces.IUserClass): registry.registerUtility(User, interfaces.IUserClass) if not registry.queryUtility(interfaces.IConsumerClass): registry.registerUtility(Consumer, interfaces.IConsumerClass) if not registry.queryUtility(interfaces.IActivationClass): registry.registerUtility(Activation, interfaces.IActivationClass) settings = config.get_settings() key = settings['api.key'] secret = settings.get('api.secret') ttl = settings.get('api.ttl', DEFAULT_TTL) session = Session() with transaction.manager: consumer = Consumer.get_by_key(key) if not consumer: consumer = Consumer(key=key) consumer.secret = secret consumer.ttl = ttl session.add(consumer) session.flush() registry.consumer = consumer
def get_or_create_user_by_email(email, cls=User): """Gets or creates an user given an email.""" # If the email is in the database we just return its user. # First try by confirmed then just any email. db_email = Email.query.filter_by(address=email, is_confirmed=True).first() if db_email: return db_email.user # Now just by email. db_email = Email.query.filter_by(address=email).first() if db_email: return db_email.user # If we got this far it doesn't exist, create a new user... username = generate_random_digest(num_bytes=15) # Build a dict with keys that the user_cls.factory method expects. # Note that the raw password will be encrypted before being saved. data = { 'password': '', 'username': username, } user = cls(**data) Session.add(user) db_email = Email(user=user, address=email) Session.add(db_email) Session.flush() return user
def includeme(config): registry = config.registry settings = registry.settings config.include('pyramid_basemodel') config.include('pyramid_tm') models = [ (IActivationClass, Activation), (IUserClass, User), (IUIStrings, UIStringsBase), (IConsumerClass, Consumer), (IDBSession, Session) ] for iface, imp in models: if not registry.queryUtility(iface): registry.registerUtility(imp, iface) if asbool(settings.get('basemodel.should_create_all', True)): key = settings['api.key'] secret = settings.get('api.secret') ttl = settings.get('api.ttl', auth.DEFAULT_TTL) session = Session() consumer = session.query(Consumer).filter(Consumer.key == key).first() if not consumer: with transaction.manager: consumer = Consumer(key=key, secret=secret, ttl=ttl) session.add(consumer) session.flush()
def _make_mailing(name='foo', days=0, subject=u'', body=u'', **kwargs): mailing = Mailing(name=name, days=days, subject=subject, body=body, **kwargs) Session.add(mailing) return mailing
def makeUserWithEmail(self): "Helper method that creates a user with an email" user = self.makeUser(u'thruflo', u'Password') Session.add(user) user.emails.append(model.Email(address=u'*****@*****.**')) transaction.commit() Session.add(user) return user
def add_playlist_clip( playlist, title, image_url, youtube_video_id, duration, username=None, state=0, ): """ Add clip to playlist :param playlist: playlist of which we want to get videos :type playlist: balistos.models.playlist.Playlist :param title: title of video :type title: str :param image_url: url of image used for thumbnail :type image_url: str :param youtube_video_id: id of video on youtube :type youtube_video_id: str :param duration: duration of video :type duration: int :param username: username of user that added this clip :type username: str :param state: state of video to be added :type state: int """ clip = Clip.get(youtube_video_id) if not clip: clip = Clip( title=title, image_url=image_url, youtube_video_id=youtube_video_id, likes=0, duration=duration, ) Session.add(clip) pclip = PlaylistClip.get_by_playlist_and_clip(playlist, clip) if not pclip: if state == 2: started = datetime.now() else: started = datetime.min pclip = PlaylistClip( added=datetime.now(), likes=0, state=state, clip=clip, playlist=playlist, username=username, started=started, ) Session.add(pclip) return pclip else: pclip.likes += 1
def _make_ipn_group(): group = Group( name='monthly', product_id=1, validity=31, trial_validity=7, ) Session.add(group) return group
def test_add_playlist(self): from balistos.models.playlist import Playlist playlist = Playlist(uri='test', title=u'Test') Session.add(playlist) Session.flush() playlist = Playlist.get('test') self.assertEqual('test', playlist.uri) self.assertEqual(u'Test', playlist.title)
def makeUser(self, username, password): """Create and save a user with the credentials provided.""" user = model.User() user.username = unicode(username) user.password = model.encrypt(password) model.save(user) transaction.commit() Session.add(user) return user
def test_add_user_username_only(self): from balistos.models.user import User user = User(username='******') Session.add(user) Session.flush() user = User.get_by_username('test') self.assertEqual('test', user.username) self.assertIsNone(user.email) self.assertIsNone(user.fullname)
def makeUser(self, username, password): """Create and save a user with the credentials provided.""" user = model.User() user.username = username user.password = model.encrypt(password) model.save(user) transaction.commit() Session.add(user) return user
def log_event(self, comment=None, read=False): from pyramid_bimt.models import AuditLogEntry from pyramid_bimt.models import AuditLogEventType event_type = AuditLogEventType.by_name(name=self.__class__.__name__) entry = AuditLogEntry( user_id=self.user.id, event_type_id=event_type.id, comment=comment, read=read, ) Session.add(entry)
def setUp(self): ''' setUp test method @see unittest.TestCase.setUp ''' Base.metadata.create_all(engine) for locale in ['pl', 'cz', 'fr']: locale_object = Language(name=text_type(locale), native_name=text_type(locale), language_code=text_type(locale)) Session.add(locale_object)
def create_user(self, update_data=None): user = User(**self.user_data) Session.add(user) # Flush to put to the DB and generate defaults Session.flush() if update_data: for update in update_data.items(): setattr(user, update[0], update[1]) transaction.commit()
def test_api_key_set_on_user_creation(self, mocked_generate): mocked_generate.return_value = 'foo' from pyramid_bimt.events import UserCreated user = User(email='*****@*****.**') Session.add(user) request = testing.DummyRequest() request.registry.notify(UserCreated(request, user, u'foö')) self.assertEqual(user.get_property('api_key', secure=True), u'foo')
def create_api_consumer(target, connection, **kwargs): key = settings['api.key'] secret = settings.get('api.secret') ttl = settings.get('api.ttl', auth.DEFAULT_TTL) session = Session() consumer = session.query(Consumer).filter(Consumer.key == key).first() if not consumer: with transaction.manager: consumer = Consumer(key=key, secret=secret, ttl=ttl) session.add(consumer) session.flush()
def test_add_user(self): from balistos.models.user import User user = User( username='******', email='*****@*****.**', fullname=u'Főo čar' ) Session.add(user) Session.flush() user = User.get_by_username('test') self.assertEqual('test', user.username) self.assertEqual('*****@*****.**', user.email) self.assertEqual(u'Főo čar', user.fullname)
def test_prefer_non_persisted_email(self): "Set non-persisted email object as new preferred email" # Create user without any email address user = self.makeUser('bob', '123') # Directly set new email as preferred email email = model.Email(address=u'*****@*****.**') user.preferred_email = email model.save(user) transaction.commit() # Verify that the new email is now the preferred email Session.add(user) self.assertEquals(user.preferred_email.address, u'*****@*****.**')
def test_success(self): """User can NOT delete itself. We have rules for what delete means.""" self.add_user_root() user = self.makeUser('thruflo', 'Password') Session.add(user) self.authenticate() # Attempt to delete user res = self.app.post('/users/thruflo/delete_user', status=404) # Verify that the user was not deleted. self.assertIsNotNone(get_existing_user(username='******'))
def test_preferred_if_only_one(self): "If user has only one email, consider it as preferred email" # Create user without any email address user = self.makeUser('bob', '123') # Directly set new email as preferred email email = model.Email(address=u'*****@*****.**') user.emails.append(email) model.save(user) transaction.commit() # Verify that the new email is now the preferred email Session.add(user) self.assertEquals(user.preferred_email.address, u'*****@*****.**')
def test_on_failure(self): einfo = mock.Mock(spec='exception traceback'.split()) einfo.exception = Exception('problem foö') einfo.traceback = str(einfo.exception) with transaction.manager: Session.add(FooTaskModel(id=1, task_id='foo')) task = self.FooTask() self.assertEqual( FooTaskModel.by_id(1).state, TaskStates.pending.name, ) task.on_failure(None, 'foo', None, None, einfo) self.assertEqual(FooTaskModel.by_id(1).traceback, u'problem foö')
def test_success(self): "Change username with valid input" # Create a user. user = self.makeUser(u"thruflo", u"Password") # Attempt to change username post_data = {"username": u"bob", "next": "/foo/bar"} self.authenticate() res = self.app.post("/auth/change_username", post_data) # Verify redirect self.assertEquals(res.location, "http://localhost/foo/bar") # Verify that username has changed Session.add(user) self.assertEquals(user.username, "bob")
def test_wrong_old_password_returns_valid_user(self): "Bug fix: user template param must not be None" from pyramid_simpleauth.view import change_password from pyramid import testing # Create a user. user = self.makeUser("thruflo", "Password") Session.add(user) post_data = {"old_password": "******", "new_password": "******", "new_confirm": "sworDpas"} request = testing.DummyRequest(post=post_data) request.user = user testing.setUp(settings={}) res = change_password(request) self.assertTrue(res["user"])
def test_failure(self): "Change username with invalid input" # Create a user. user = self.makeUser(u"thruflo", u"Password") # Attempt to assign bogus username post_data = {"username": u"$ @ 88 , /", "next": "/foo/bar"} self.authenticate() res = self.app.post("/auth/change_username", post_data) # Verify response body self.assertTrue("No spaces or funny characters" in res.body) self.assertTrue("/foo/bar" in res.body, "Response body should contain next hidden field") # Verify that username has not changed Session.add(user) self.assertEquals(user.username, "thruflo")
def add_chat_message(playlist, username, message): """ Add chat message to playlist :param playlist: current playlist :type playlist: balistos.models.playlist.Playlist :param username: username of user who added msg :type username: str :param message: chat message :type message: str """ chat_message = ChatMessage( user=User.get_by_username(username), playlist=playlist, message=message, posted=datetime.now(), ) Session.add(chat_message)
def setUp(self): settings = { 'bimt.app_title': 'BIMT', } self.request = testing.DummyRequest() self.config = testing.setUp(request=self.request, settings=settings) self.config.scan('pyramid_bimt.models.mailing') self.config.include('pyramid_mailer.testing') self.config.include('pyramid_chameleon') self.mailer = get_mailer(self.request) initTestingDB(users=True, groups=True, mailings=True, auditlog_types=True) # noqa add_routes_auth(self.config) self.user = User(email='*****@*****.**') Session.add(self.user) Session.flush()
def test_add_clip(self): from balistos.models.clip import Clip clip = Clip( youtube_video_id='test', title=u'Test', likes=5, image_url='test_url', duration=1, ) Session.add(clip) Session.flush() clip = Clip.get('test') self.assertEqual('test', clip.youtube_video_id) self.assertEqual(u'Test', clip.title) self.assertEqual(5, clip.likes) self.assertEqual('test_url', clip.image_url) self.assertEqual(1, clip.duration)
def add_demo_auditlog_entries(): """Add a dummy audit-log entry.""" with transaction.manager: read = AuditLogEntry( user=User.by_email('*****@*****.**'), event_type_id=AuditLogEventType.by_name(u'UserChangedPassword').id, comment=u'read entry', read=True, ) Session.add(read) unread = AuditLogEntry( user=User.by_email('*****@*****.**'), event_type_id=AuditLogEventType.by_name(u'UserChangedPassword').id, comment=u'unread entry', read=False, ) Session.add(unread)
def test_success(self): "Change username with valid input" # Create a user. user = self.makeUser(u'thruflo', u'Password') # Attempt to change username post_data = { 'username': u'bob', 'next': '/foo/bar', } self.authenticate() res = self.app.post('/auth/change_username', post_data) # Verify redirect self.assertEquals(res.location, 'http://localhost/foo/bar') # Verify that username has changed Session.add(user) self.assertEquals(user.username, 'bob')
def add_demo_portlet(): """Create a dummy portlet.""" with transaction.manager: admins = Group.by_name('admins') enabled = Group.by_name('enabled') portlet = Portlet( name='dummy', groups=[ admins, ], exclude_groups=[ enabled, ], position=PortletPositions.below_sidebar.name, weight=-127, html=u'You are admin.', ) Session.add(portlet)
def setUp(self): settings = { 'bimt.app_title': 'BIMT', } self.request = testing.DummyRequest() self.config = testing.setUp(request=self.request, settings=settings) self.config.include('pyramid_mailer.testing') self.config.include('pyramid_chameleon') self.mailer = get_mailer(self.request) initTestingDB(users=True, groups=True) self.group = Group(name='foo') Session.add(self.group) self.user = User(email='*****@*****.**') Session.add(self.user) self.user.groups = [ self.group, ] Session.flush()
def test_after_return(self): with transaction.manager: Session.add(FooTaskModel(task_id='foo')) task = self.FooTask() task.after_return( status='failure', retval=None, task_id='foo', args=None, kwargs=None, einfo=None) # noqa self.assertEqual( FooTaskModel.by_id(1).state, TaskStates.failure.name, ) self.assertEqual(len(handler.records), 1) self.assertEqual( handler.records[0].message, 'END pyramid_bimt.tests.test_task.FooTask ' '(celery task id: foo, app task id: 1)', )
def _make_user( self, email='*****@*****.**', billing_email=None, enabled=True, **kwargs ): user = User( email=email, password=u'secret', billing_email=billing_email, **kwargs ) Session.add(user) if enabled: user.enable() return user
def test_new_passwords_dont_match(self): "No password change if new passwords don't match" # Create a user. user = self.makeUser("thruflo", "Password") Session.add(user) old_hash = user.password self.authenticate() # Attempt to change password. post_data = {"old_password": "******", "new_password": "******", "new_confirm": "oswdrpsa"} res = self.app.post("/auth/change_password", post_data) # Verify that password hasn't changed Session.add(user) Session.refresh(user) self.assertTrue("Fields do not match" in res.body) self.assertEquals(user.password, old_hash)
def expire_subscriptions(): """Find all outstanding subscriptions and expire them.""" with transaction.manager: for user in User.get_all(): if user.enabled: if user.valid_to < date.today(): user.disable() msg = u'Disabled user {} ({}) because its valid_to ({}) ' \ 'has expired.'.format( user.email, user.id, user.valid_to) Session.add( AuditLogEntry( user_id=user.id, event_type_id=AuditLogEventType.by_name( 'UserDisabled').id, comment=msg, )) logger.info(msg) continue # handle addons for prop in user.properties: if not prop.key.startswith('addon_'): continue if not prop.key.endswith('_valid_to'): continue valid_to = datetime.strptime(prop.value, '%Y-%m-%d').date() if valid_to >= date.today(): continue group = Group.by_product_id( prop.key.split('addon_')[1].split('_valid_to')[0]) user.groups.remove(group) msg = u'Addon "{}" disabled for user {} ({}) because ' \ 'its valid_to ({}) has expired.'.format( group.name, user.email, user.id, prop.value) Session.add( AuditLogEntry( user_id=user.id, event_type_id=AuditLogEventType.by_name( 'UserDisabled').id, comment=msg, ))