def test_existing_user_cancel_subscription(self, mocked_date): user = self._make_user( email='*****@*****.**', groups=[ Group.by_name('enabled'), Group.by_name('trial'), Group.by_name('monthly'), ]) mocked_date.today.return_value = date(2013, 12, 30) view = IPNView(testing.DummyRequest()) view.provider = 'clickbank' view.params = AttrDict({ 'email': '*****@*****.**', 'trans_type': 'RFND', 'trans_id': 123, 'product_id': 1, }) resp = view.ipn() self.assertEqual(resp, 'Done.') self.assertEqual(user.enabled, False) self.assertEqual(user.valid_to, date(2013, 12, 30)) self.assertEqual(len(user.audit_log_entries), 1) self.assertEqual( user.audit_log_entries[0].event_type.name, u'UserDisabled') self.assertEqual( user.audit_log_entries[0].comment, u'Disabled by clickbank, transaction id: 123, type: RFND, note: ' u'removed from groups: enabled, trial, monthly', )
def test_existing_trial_user_new_subscription_payment( self, mocked_date, user=None ): if not user: user = self._make_user( email='*****@*****.**', groups=[Group.by_name('enabled'), Group.by_name('trial')], ) mocked_date.today.return_value = date(2013, 12, 30) view = IPNView(testing.DummyRequest()) view.provider = 'jvzoo' view.params = AttrDict({ 'email': '*****@*****.**', 'fullname': u'Föo Bar', 'trans_type': 'BILL', 'trans_id': 123, 'product_id': 1, }) resp = view.ipn() self.assertEqual(resp, 'Done.') self.assertEqual(user.enabled, True) self.assertEqual(user.trial, False) self.assertEqual(user.valid_to, date(2014, 1, 30)) self.assertEqual(user.last_payment, date(2013, 12, 30)) self.assertEqual(len(user.audit_log_entries), 1) self.assertEqual( user.audit_log_entries[0].event_type.name, u'UserEnabled') self.assertEqual( user.audit_log_entries[0].comment, u'Enabled by jvzoo, transaction id: 123, type: BILL, note: ' u'regular until 2014-01-30', )
def __init__(self, request): self.request = request self.schema = SQLAlchemySchemaNode( User, includes=self.fields, overrides={ 'properties': {'includes': ['key', 'value']}, 'email': {'validator': deferred_user_email_validator}, 'billing_email': { 'validator': deferred_user_billing_email_validator} } ) # we don't like the way ColanderAlchemy renders SA Relationships so # we manually inject a suitable SchemaNode for groups choices = [(group.id, group.name) for group in Group.get_all()] enabled = Group.by_name('enabled') choices.remove((enabled.id, enabled.name)) if not request.user.admin: admins = Group.by_name('admins') choices.remove((admins.id, admins.name)) self.schema.add( node=colander.SchemaNode( colander.Set(), name='groups', missing=[], widget=deform.widget.CheckboxChoiceWidget(values=choices), validator=deferred_groups_validator, ), )
def __call__(self): warnings = [] if not Group.by_name('admins'): warnings.append('Group "admins" missing.') if not Group.by_name('enabled'): warnings.append('Group "enabled" missing.') if not Group.by_name('trial'): warnings.append('Group "trial" missing.') return warnings
def test_exclude(self): add_groups() add_users() mailing = _make_mailing( name='foo', groups=[Group.by_name('enabled')], exclude_groups=[Group.by_name('admins'), Group.by_name('staff')], ) self.request.context = mailing self.assertItemsEqual( self.view.recipients, [User.by_email('*****@*****.**')], )
def test_existing_regular_user_new_subscription_payment(self): """Test for the "ValueError: list.remove(x): x not in list" bug.""" user = self._make_user( email='*****@*****.**', groups=[Group.by_name('enabled')], ) self.test_existing_trial_user_new_subscription_payment(user=user)
def add_users(): """Init the '*****@*****.**' and '*****@*****.**' user accounts.""" with transaction.manager: admins = Group.by_name('admins') staff = Group.by_name('staff') enabled = Group.by_name('enabled') trial = Group.by_name('trial') # Create the admin user account admin = User( email=u'*****@*****.**', password=SECRET_ENC, fullname=u'Ädmin', properties=[ UserProperty(key=u'bimt', value=u'on'), ], ) admin.groups.append(admins) admin.groups.append(enabled) Session.add(admin) # Create the staff member account staff_member = User( email=u'*****@*****.**', password=SECRET_ENC, fullname=u'Stäff Member', properties=[ UserProperty(key=u'bimt', value=u'on'), ], ) staff_member.groups.append(enabled) staff_member.groups.append(staff) Session.add(staff_member) # Create the normal user account one = User( email=u'*****@*****.**', billing_email=u'*****@*****.**', password=SECRET_ENC, fullname=u'Öne Bar', properties=[ UserProperty(key=u'bimt', value=u'on'), ], ) one.groups.append(enabled) one.groups.append(trial) Session.add(one)
def test_non_admin_and_non_admins(self): from pyramid_bimt.views.user import deferred_groups_validator self.request.user.admin = False cstruct = [ str(Group.by_name('staff').id), ] validator = deferred_groups_validator(None, {'request': self.request}) self.assertFalse(validator(None, cstruct))
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 __call__(self): warnings = [] user = User.by_id(1) if not user: warnings.append('User "admin" should have id of "1".') if user and user.enabled: warnings.append('User "admin" should be disabled in production.') if user and Group.by_name('admins') not in user.groups: warnings.append('User "admin" should be in "admins" group.') return warnings
def test_context_name_allowed_for_name(self): from pyramid_bimt.views.group import deferred_group_name_validator schema = SQLAlchemySchemaNode(Group) self.request.context = Group.by_name('enabled') self.request.POST['name'] = 'enabled' validator = deferred_group_name_validator(None, {'request': self.request}) self.assertFalse(validator(schema.get('name'), 'enabled'))
def add_demo_mailing(): """Create a dummy mailing.""" with transaction.manager: trial = Group.by_name('trial') admins = Group.by_name('admins') mailing = Mailing( name='welcome_email', groups=[ trial, ], exclude_groups=[ admins, ], trigger=MailingTriggers.after_created.name, days=1, subject=u'Über Welcome!', body=u'Welcome to this über amazing BIMT app!', ) Session.add(mailing)
def test_not_in_unsubscribed(self, get_current_request): get_current_request.return_value = self.request add_routes_user(self.config) self.request.user = User.by_email('*****@*****.**') self.request.context = _make_mailing( id=123, name='excluded', groups=[Group.by_name('admins'), Group.by_name('enabled')], exclude_groups=[], body=u'Body', subject=u'Subject') mailer = get_mailer(self.request) self.request.context.send(self.request.user) self.assertEqual(len(mailer.outbox), 1) self.assertEqual(mailer.outbox[0].subject, u'Subject') self.assertNotIn('Unsubscribe from our Newsletter', mailer.outbox[0].html) # noqa
def test_context_product_id_allowed_for_product_id(self): from pyramid_bimt.views.group import deferred_group_product_id_validator # noqa schema = SQLAlchemySchemaNode(Group) self.request.context = Group.by_name('enabled') self.request.context.product_id = '123' self.request.POST['product_id'] = '123' validator = deferred_group_product_id_validator( None, {'request': self.request}) self.assertFalse(validator(schema.get('product_id'), '123'))
def ipn_bill_transaction(self, user, group): """Handle IPN bill transaction. :param user: Selected user :type user: pyramid_bimt.models.user.User :param group: Group that user belongs to :type group: pyramid_bimt.models.Groups.Group """ validity = timedelta(days=group.validity) valid_to = date.today() + validity if group.addon: user.set_property('addon_{}_valid_to'.format(group.product_id), valid_to) user.set_property('addon_{}_last_payment'.format(group.product_id), date.today()) action = u'Addon "{}" enabled'.format(group.name) else: user.valid_to = valid_to user.last_payment = date.today() user.enable() action = u'Enabled' if Group.by_name('trial') in user.groups: user.groups.remove(Group.by_name('trial')) if group not in user.groups: # pragma: no branch user.groups.append(group) comment = COMMENT.format( action, self.provider, self.params.trans_id, self.params.trans_type, 'regular until {}'.format(valid_to), ) logger.info(comment) self.request.registry.notify(UserEnabled(self.request, user, comment))
def test_loginas_view_submit_success_as_user(self): from pyramid_bimt.models import User from pyramid_bimt.models import Group from pyramid_bimt.views.auth import LoginAs Session.add( User(email='*****@*****.**', groups=[ Group.by_name('enabled'), ])) context = User.by_email('*****@*****.**') context.groups.append(Group.by_name('impersonators')) request = testing.DummyRequest( layout_manager=mock.Mock(), session=mock.Mock(), ) form_values = {'email': '*****@*****.**'} request.user = context view = LoginAs(request) resp = view.login_as_success(form_values) self.assertEqual(resp.location, 'http://example.com') request.session.flash.assert_called_once_with( u'You have successfully logged in as user "*****@*****.**".')
def test_existing_user_refund_after_upgrade(self, mocked_date): user = self._make_user( email='*****@*****.**', groups=[ Group.by_name('enabled'), Group.by_name('trial'), Group.by_name('monthly'), ]) user.set_property('upgrade_completed', True) view = IPNView(testing.DummyRequest()) view.provider = 'clickbank' view.params = AttrDict({ 'email': '*****@*****.**', 'trans_type': 'RFND', 'trans_id': 123, 'product_id': 1, }) resp = view.ipn() self.assertEqual(resp, 'Done.') self.assertEqual(user.enabled, True) self.assertIn(Group.by_name('monthly'), user.groups) self.assertEqual(len(user.audit_log_entries), 0)
def test_non_admin_and_admins(self): from pyramid_bimt.views.user import deferred_groups_validator self.request.user.admin = False cstruct = [ str(Group.by_name('admins').id), ] validator = deferred_groups_validator(None, {'request': self.request}) with self.assertRaises(colander.Invalid) as cm: validator(None, cstruct) self.assertEqual( cm.exception.msg, 'Only admins can add users to "admins" group.', )
def test_new_user_no_trial(self, mocked_date): Group.by_name('monthly').trial_validity = None mocked_date.today.return_value = date(2013, 12, 30) view = IPNView(testing.DummyRequest()) view.provider = 'clickbank' view.params = AttrDict({ 'email': '*****@*****.**', 'fullname': u'Föo Bar', 'trans_type': 'SALE', 'trans_id': 123, 'product_id': 1, 'affiliate': '*****@*****.**', }) resp = view.ipn() self.assertEqual(resp, 'Done.') user = User.by_email('*****@*****.**') self.assertEqual(user.enabled, True) self.assertEqual(user.trial, False) self.assertEqual(user.affiliate, '*****@*****.**') self.assertEqual(user.valid_to, date(2014, 1, 30)) self.assertEqual(user.last_payment, date(2013, 12, 30)) self.assertEqual(len(user.audit_log_entries), 2) self.assertEqual( user.audit_log_entries[0].event_type.name, u'UserCreated') self.assertEqual( user.audit_log_entries[0].comment, u'Created by clickbank, transaction id: 123, type: SALE, note: ', ) self.assertEqual( user.audit_log_entries[1].event_type.name, u'UserEnabled') self.assertEqual( user.audit_log_entries[1].comment, u'Enabled by clickbank, transaction id: 123, type: SALE, note: ' u'regular until 2014-01-30', )
def save_success(self, appstruct): user = self.request.context user.email = appstruct.get('email') user.fullname = appstruct.get('fullname') user.affiliate = appstruct.get('affiliate') user.billing_email = appstruct.get('billing_email') user.valid_to = appstruct.get('valid_to') user.last_payment = appstruct.get('last_payment') if appstruct.get('password'): user.password = encrypt(appstruct['password']) groups = [Group.by_id(group_id) for group_id in appstruct['groups']] enabled = Group.by_name('enabled') if enabled in user.groups: groups.append(enabled) user.groups = groups # remove properties that are not present in appstruct for prop in copy.copy(user.properties): if prop.key not in [p['key'] for p in appstruct['properties']]: user.properties.remove(prop) # update/create properties present in appstruct for prop in appstruct['properties']: if user.has_property(prop['key']): user.set_property(key=prop['key'], value=prop.get('value')) else: user.properties.append( UserProperty(key=prop['key'], value=prop.get('value'))) self.request.session.flash( u'User "{}" modified.'.format(user.email)) return HTTPFound( location=self.request.route_path( 'user_view', user_id=user.id))
def validator(node, cstruct): id_ = str(Group.by_name('admins').id) if (not request.user.admin) and (id_ in cstruct): raise colander.Invalid( node, u'Only admins can add users to "admins" group.')
def validator(node, cstruct): if Group.by_name(cstruct): raise colander.Invalid( node, u'Group with name "{}" already exists.'.format(cstruct))