示例#1
0
    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))
示例#2
0
 def test_user_get_all_empty(self):
     from balistos.models.user import User
     user = User.get_by_username('test_user')
     Session.delete(user)
     Session.flush()
     self.assertEqual(0, User.get_all().count())
     self.assertIsNone(User.get_by_username('test_user'))
示例#3
0
def initTestingDB(auditlog_types=False,
                  auditlog_entries=False,
                  groups=False,
                  users=False,
                  portlets=False,
                  mailings=False):
    engine = create_engine('sqlite:///:memory:')
    Base.metadata.create_all(engine)
    Session.configure(bind=engine)

    if auditlog_types:
        add_audit_log_event_types()

    if groups or users:
        add_groups()

    if users:
        add_users()

    if mailings:
        add_mailings()
        add_demo_mailing()

    if portlets:
        add_demo_portlet()

    if auditlog_entries:
        add_demo_auditlog_entries()
示例#4
0
def remove_playlist_clip(playlist, youtube_video_id):
    """
    Remove clip from playlist

    :param    playlist: playlist we want to delete clip from
    :type     playlist: balistos.models.Playlist
    :param    clip:     youtube video id we want to delete from playlist
    :type     clip:     [clip type]

    :returns  True if removed, False otherwise
    :rtype    boolean
    """

    pclip = PlaylistClip.get_by_playlist_and_clip(
        playlist,
        Clip.get(youtube_video_id)
    )
    if not pclip:
        return False

    state = pclip.state
    Session.delete(pclip)

    if state == 2:
        next_pclip = PlaylistClip.get_queue_playlist_clip(playlist)
        play_next_clip(playlist, pclip, next_pclip)
    elif state == 1:
        active_pclip = PlaylistClip.get_active_playlist_clip(playlist)
        set_next_in_queue(playlist, active_pclip.clip.youtube_video_id)
    return True
示例#5
0
    def setUp(self):
        self.config = testing.setUp()
        initTestingDB(groups=True)
        Group.by_id(1).product_id = 'old_id'
        Session.flush()

        self.request = testing.DummyRequest()
    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))
示例#7
0
文件: models.py 项目: almereyda/h
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
示例#8
0
    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 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)
示例#10
0
    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))
示例#11
0
 def test_billing_email_is_unique(self):
     _make_user(billing_email='*****@*****.**')
     _make_user(billing_email='*****@*****.**')
     with self.assertRaises(IntegrityError) as cm:
         Session.flush()
     self.assertIn(
         'column billing_email is not unique', cm.exception.message)
示例#12
0
    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)
示例#13
0
文件: queue.py 项目: kultus/belive.at
def handle_data(data_str):
    """Handle data from the Twitter Streaming API, via the redis queue."""
    
    # XXX debug only really.
    sys.stderr.write('.')
    
    # Decode into a unicode string.
    text = unicode(data_str, 'utf-8')
    
    # Try to parse the JSON text into a data dict.
    try:
        data = json.loads(text)
    except Exception as err:
        return logger.warn(err)
    
    # In a transaction.
    with transaction.manager:
        # If we're dealing with a status.
        if data.has_key('in_reply_to_status_id'):
            return handle_status(data, text)
        # If we're dealing with a deletion record.
        if data.has_key('delete'):
            return handle_deletion(data)
        # XXX more events, e.g.: handle verification.
    
    # Close the db connection.
    Session.remove()
示例#14
0
 def test_playlist_get_all_empty(self):
     from balistos.models.playlist import Playlist
     playlist = Playlist.get('test_playlist')
     Session.delete(playlist)
     Session.flush()
     self.assertEqual(0, Playlist.get_all().count())
     self.assertIsNone(Playlist.get('test_playlist'))
示例#15
0
    def email_change_POST(self):
        '''
            Processes POST requests to generate change email hash
        '''
        if self.check_csrf:
            token = self.request.session.get_csrf_token()
        else:
            token = ''
        if self.check_csrf and token != self.request.POST.get('token'):
            return {'status': False,
                    'msg': self.request._('csrf-mismatch',
                                          default='CSRF token did not match.',
                                          domain='pyramid_fullauth'),
                    'token': token}
        try:
            Session.query(User).filter(User.email == self.request.POST.get('email', '')).one()
            return {'status': False,
                    'msg': self.request._('User with this email exists',
                                          domain='pyramid_fullauth'),
                    'token': token}
        except NoResultFound:
            pass

        user = self.request.user
        try:
            result = self.request.registry.notify(BeforeEmailChange(self.request, user))
        except AttributeError as e:
            return {'status': False, 'msg': e.message, 'token': token}

        try:
            user.set_new_email(self.request.POST.get('email', ''))
        except EmptyError:
            return {'status': False,
                    'msg': self.request._(
                        'E-mail is empty',
                        domain='pyramid_fullauth'),
                    'token': token}
        except EmailValidationError:
            return {'status': False,
                    'msg': self.request._(
                        'Incorrect e-mail format',
                        domain='pyramid_fullauth'),
                    'token': token}

        response_values = {'status': True,
                           'msg': self.request._('We sent you email to activate your new email address',
                                                 domain='pyramid_fullauth')}
        try:
            self.request.registry.notify(AfterEmailChange(self.request, user))
        except HTTPFound as redirect:
            if self.request.is_xhr:
                response_values['url'] = redirect.location
                return response_values
            else:
                return redirect
        else:
            if self.request.is_xhr:
                return response_values
            else:
                return HTTPFound(location='/')
示例#16
0
    def test_add_pclip(self):
        from balistos.models.clip import PlaylistClip
        from balistos.models.clip import Clip
        from balistos.models.playlist import Playlist
        from datetime import datetime

        playlist = Playlist(uri='test', title=u'Test')
        clip = Clip(
            youtube_video_id='test',
            title=u'Test',
            likes=5,
            image_url='test_url',
            duration=1
        )
        Session.add(clip)
        Session.add(playlist)
        Session.flush()

        pclip = PlaylistClip(
            playlist=playlist,
            clip=clip,
            likes=0,
            state=0,
            added=datetime.now()
        )
        Session.add(pclip)
        Session.flush()
        pclip = PlaylistClip.get_by_playlist_and_clip(playlist, clip)
        self.assertEqual(playlist, pclip.playlist)
        self.assertEqual(clip, pclip.clip)
        self.assertEqual(0, pclip.state)
        self.assertEqual(0, pclip.likes)
示例#17
0
    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)
示例#18
0
    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)
示例#19
0
 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
示例#20
0
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
示例#21
0
 def test_clip_get_all_empty(self):
     from balistos.models.clip import Clip
     clips = Clip.get_all()
     for clip in clips:
         Session.delete(clip)
     Session.flush()
     self.assertEqual(0, Clip.get_all().count())
     self.assertIsNone(Clip.get('cpV0ygkmhP4'))
示例#22
0
 def test_pclip_get_all_empty(self):
     from balistos.models.clip import PlaylistClip
     pclips = PlaylistClip.get_all()
     for pclip in pclips:
         Session.delete(pclip)
     Session.flush()
     self.assertEqual(0, PlaylistClip.get_all().count())
     self.assertEqual(0, PlaylistClip.get_all().count())
示例#23
0
 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
示例#24
0
文件: models.py 项目: Zitrax/Artifakt
 def delete(self):
     # If the comment has replies it will only marked as deleted
     if len(self.replies):
         self.comment = "<DELETED>"
         self.deleted = True
     # If note it will fully deleted
     else:
         DBSession.delete(self)
示例#25
0
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
示例#26
0
 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)
示例#27
0
 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
示例#28
0
 def setUp(self):
     from balistos import configure
     Session.remove()
     createTestDB()
     self.config = testing.setUp()
     configure(self.config)
     app = self.config.make_wsgi_app()
     from webtest import TestApp
     self.testapp = TestApp(app)
示例#29
0
def _make_ipn_group():
    group = Group(
        name='monthly',
        product_id=1,
        validity=31,
        trial_validity=7,
    )
    Session.add(group)
    return group
示例#30
0
    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)
示例#31
0
    def test_disabled_correct(self):
        self.user.disable()
        self._make_disabled_entry()
        Session.flush()

        from pyramid_bimt.sanitycheck import CheckUsersEnabledDisabled
        self.assertEqual(
            CheckUsersEnabledDisabled()(),
            [],
        )
示例#32
0
文件: tasks.py 项目: ferewuz/balistos
def bootstrap_pyramid(signal, sender):
    import os
    from pyramid.paster import bootstrap
    sender.app.settings = \
        bootstrap(os.environ['BALISTOS_CONFIG'])['registry'].settings
    engine = engine_from_config(sender.app.settings, 'sqlalchemy.')

    register_after_fork(engine, engine.dispose)

    Session.configure(bind=engine)
示例#33
0
    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
示例#34
0
def main(argv=sys.argv):
    if len(argv) < 2:
        usage(argv)
    config_uri = argv[1]
    options = parse_vars(argv[2:])
    setup_logging(config_uri)
    settings = get_appsettings(config_uri, options=options)
    engine = engine_from_config(settings, 'sqlalchemy.')
    Session.configure(bind=engine)
    Base.metadata.create_all(engine)
示例#35
0
def handle_deletion(data):
    """Handle a Twitter status."""
    
    id_ = data['delete']['status']['id']
    tweet = Tweet.query.get(id_)
    if tweet:
        Session.delete(tweet)
    
    # XXX debug.
    logger.info('Deleted %d' % id_)
示例#36
0
    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)
示例#37
0
 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)
示例#38
0
 def test_populate_columns_entry_without_user(self):
     self.config.testing_securitypolicy(userid='*****@*****.**',
                                        permissive=False)
     Session.delete(User.by_id(3))
     Session.flush()
     view = self._make_view()
     self.assertEqual(view.columns['comment'], u'unread entry')
     self.assertEqual(view.columns['event_type_id'],
                      'User Changed Password')
     self.assertEqual(view.columns['user_id'], None)
     self.assertEqual(view.columns['action'], None)
示例#39
0
    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()
示例#40
0
    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')
示例#41
0
    def reset_continue(self):
        '''
            Method that serves password reset page
        '''
        user = self.request.matchdict.get('user')
        if self.check_csrf:
            token = self.request.session.get_csrf_token()
        else:
            token = ''

        if self.request.method == 'POST':
            # if turned on, check for csrf token
            if self.check_csrf and token != self.request.POST.get('token'):
                return {'status': False,
                        'msg': self.request._('csrf-mismatch',
                                              default='CSRF token did not match.',
                                              domain='pyramid_fullauth'),
                        'token': token}

            password = self.request.POST.get('password', None)
            password_confirm = self.request.POST.get('confirm_password', None)
            if password == password_confirm:

                try:
                    self.request.registry.notify(BeforeReset(self.request, user))
                    validate_passsword(self.request, password, user)

                    user.reset_key = None
                    try:
                        Session.query(AuthenticationProvider).filter(
                            AuthenticationProvider.user_id == user.id,
                            AuthenticationProvider.provider == u'email').one()
                    except NoResultFound:
                        user.providers.append(
                            AuthenticationProvider(provider=u'email',
                                                   provider_id=user.id))

                    Session.flush()
                except (ValidateError, AttributeError) as e:
                    return {'status': False, 'msg': str(e), 'token': token}

                try:
                    self.request.registry.notify(AfterReset(self.request, user))
                except HTTPFound as redirect:
                    return redirect
            else:
                return {'status': False,
                        'msg': self.request._('password-mismatch',
                                              default='Password doesn\'t match',
                                              domain='pyramid_fullauth'),
                        'token': token}

        return {'status': True, 'token': token}
示例#42
0
文件: models.py 项目: Zitrax/Artifakt
def artifakt_before_flush(session, *_):
    """When deleting a bundle certain contained artifacts should also be deleted"""
    for obj in session.deleted:
        if type(obj) is Artifakt:
            if obj.is_bundle:
                for af in obj.artifacts:
                    if not set(af.bundles) - {obj}:  # If the artifact would not be in a bundle anymore
                        if not af.keep_alive:
                            DBSession.delete(af)
            else:  # Safety checks. We try to prevent reaching this in the views.
                if obj.bundles:
                    raise ValueError("Won't delete {} (belongs to bundle)".format(obj.sha1))
示例#43
0
def dispatch_user_notifications(user, user_notifications):
    """ 4. for each channel loop and either write out a single or a batch dispatch task with the
        NotificationDispatcher ids e.g: /dispatch_email, /dispatch_sms and etc.
    """

    for ch in AVAILABLE_CHANNELS:
        # XXX check for preferences e.g: and user.channel == ch
        to_dispatch = [d for d in user_notifications if d.category == ch]
        for dispatch in to_dispatch:
            post_notification_dispatch(dispatch)
        else:
            print 'nothing here', to_dispatch
    Session.flush()
def dispatch_user_notifications(user, user_notifications):
    """ 4. for each channel loop and either write out a single or a batch dispatch task with the
        NotificationDispatcher ids e.g: /dispatch_email, /dispatch_sms and etc.
    """

    for ch in AVAILABLE_CHANNELS:
        # XXX check for preferences e.g: and user.channel == ch
        to_dispatch = [d for d in user_notifications if d.category == ch]
        for dispatch in to_dispatch:
            post_notification_dispatch(dispatch)
        else:
            print "nothing here", to_dispatch
    Session.flush()
示例#45
0
 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)
示例#46
0
文件: model.py 项目: kultus/belive.at
 def rank(self):
     """Rank by the number of promote and cover offers."""
     
     logger.warn('XXX how do we retire offers?')
     
     # Start with a rank of zero and ignore everything that's over a week old.
     n = 0
     now = datetime.datetime.utcnow()
     one_week_ago = get_one_week_ago()
     
     # For each promote offer.
     query = Session.query(PromoteOffer.created)
     query = query.filter(PromoteOffer.assignment==self)
     query = query.filter(PromoteOffer.created>one_week_ago)
     results = query.all()
     self.promote_offer_count = len(results)
     for item in results:
         created_date = item[0]
         delta = now - created_date
         # Make sure the diff is at least one second (n.b.:
         # ``timedelta.total_seconds`` requires Python>=2.7)
         if hasattr(delta, 'total_seconds'):
             tot_seconds = delta.total_seconds()
         else:
             secs = delta.seconds + delta.days * 24.0 * 3600.0
             tot_seconds = (delta.microseconds + secs * 10.0**6) / 10.0**6
         seconds = max(tot_seconds, 1)
         # Half life of 1 day.
         score = 1440 / seconds
         n += score
     
     # For each cover offer.
     query = Session.query(CoverOffer.created)
     query = query.filter(CoverOffer.assignment==self)
     query = query.filter(CoverOffer.created>one_week_ago)
     results = query.all()
     self.cover_offer_count = len(results)
     for item in results:
         created_date = item[0]
         delta = now - created_date
         if hasattr(delta, 'total_seconds'):
             tot_seconds = delta.total_seconds()
         else:
             secs = delta.seconds + delta.days * 24.0 * 3600.0
             tot_seconds = (delta.microseconds + secs * 10.0**6) / 10.0**6
         seconds = max(tot_seconds, 1)
         # Three times as important as promote offers.
         score = 3 * 1440 / seconds
         n += score
     
     return n
示例#47
0
 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)
示例#48
0
    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'*****@*****.**')
示例#49
0
    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'*****@*****.**')
示例#50
0
    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'*****@*****.**')
示例#51
0
def main(global_config, **settings):
    """This function returns a Pyramid WSGI application and is only used
    when developing BIMT in isolation."""
    engine = engine_from_config(settings, 'sqlalchemy.')
    Session.configure(bind=engine)

    config = Configurator(
        settings=settings,
        root_factory=RootFactory,
    )

    includeme(config)
    add_home_view(config)
    return config.make_wsgi_app()
示例#52
0
    def test_disabled_enabled_entry_after_disabled(self):
        self.user.disable()
        self._make_enabled_entry()
        self._make_disabled_entry()
        self._make_enabled_entry()
        Session.flush()

        from pyramid_bimt.sanitycheck import CheckUsersEnabledDisabled
        self.assertEqual(
            CheckUsersEnabledDisabled()(),
            [
                'User [email protected] (1) is disabled, but has an UserEnabled entry'
                ' after UserDisabled entry.'
            ],
        )
示例#53
0
    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ö')
示例#54
0
def includeme(config):
    registry = config.registry
    config.include('pyramid_basemodel')
    config.include('pyramid_tm')

    config.set_request_property(get_user, str('user'), reify=True)

    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.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)

    with transaction.manager:
        consumer = Consumer.get_by_key(key)
        if not consumer and not secret:
            consumer = Consumer(key=key, secret=secret, ttl=ttl)
            Session().add(consumer)

    registry.consumer = consumer
示例#55
0
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()
示例#56
0
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)
示例#57
0
 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()
示例#58
0
    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
示例#59
0
    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')
示例#60
0
    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)',
        )