예제 #1
0
    def search(self):
        c.terms = request.GET.get('terms', '')
        c.results = []
        if len(c.terms) < 4:
            h.flash(
                _('Search queries must be at least 4 characters in length.'),
                'error'
            )
            redirect(url(controller='blog', action='index'))

        query = MultifieldParser(
            ['title', 'content', 'summary'],
            schema=index.schema
        ).parse(c.terms)
        results = index.searcher().search(query, limit=10)
        for result in results:
            terms = [v for k, v in query.all_terms() if k == 'content']
            url_kwargs = json.loads(result['url'])
            result['url'] = url(**url_kwargs)
            result['highlights'] = highlight(
                result['content'],
                terms,
                search.schema['content'].format.analyzer,
                ContextFragmenter(terms),
                HtmlFormatter(tagname='span', classname='highlight')
            )
            c.results.append(result)
        return render('search.tpl', slacks=True)
예제 #2
0
 def set_slug(self, form):
     try:
         model.Post.by_slug(form['slug']).one()
         h.flash(_('Slug already in use.'), 'error')
         return
     except NoResultFound:
         return form['slug']
예제 #3
0
 def edit_post(self, post):
     try:
         form = PostForms().to_python(request.POST)
         if form['delete']:
             model.Comment.by_post(c.post.id).delete()
             model.Post.by_id(c.post.id).delete()
             model.session.commit()
             h.flash(_('Post deleted successfully.'), 'success')
             redirect_url = url(controller='blog', action='index')
         else:
             category_id = self.set_category(form)
             c.post.title = form['title']
             c.post.category_id = category_id
             c.post.content = form['content']
             c.post.user_id = c.user.id
             c.post.summary = form.get('summary', '')
             if form['slug'] != c.post.slug:
                 c.post.slug = self.set_slug(form)
             model.session.commit()
             h.flash(_('Post edited successfully.'), 'success')
             redirect_url = url(
                 controller='blog',
                 action='view',
                 category=c.post.category.slug,
                 slug=c.post.slug
             )
         redirect(redirect_url)
     except validators.Invalid, e:
         return h.htmlfill(e, form=post)
예제 #4
0
    def login_complete(self):
        """This function is called once a user has succesfully logged in to
        his/her OpenID account. The user is then prompted to choose a
        preferred alias to be known as if a default one is not provided.
        """
        consumer = Consumer(session=session, store=self.openid_store)
        host = request.headers['host']
        return_url = url(host=host, controller='account',
            action='login_complete')
        result = consumer.complete(request.params, return_url)
        if result.status != 'success':
            return _('An error ocurred with login.')
        try:
            user = model.User.by_identifier(result.identity_url).one()
            session['userid'] = user.id
        except (AttributeError, NoResultFound):
            # No previous login record for the user.
            sreg_res = SRegResponse.fromSuccessResponse(result)
            try:
                email = sreg_res['email']
            except (TypeError, KeyError):
                email = ''

            try:
                name = sreg_res['nickname']
            except (TypeError, KeyError):
                name = result.identity_url
            user = model.User(
                name=name,
                identifier=result.identity_url,
                email=email
            )
            try:
                model.User.all()
            except NoResultFound:
                # Since you're going to be the only user, might as well grant
                # you administrator privileges.
                user.admin = True
            model.session.add(user)
            model.session.commit()
            session['userid'] = user.id
        session.save()
        if user.name == result.identity_url:
            h.flash(
                _('Login was successful, but now you need to set a name.'),
                'warning'
            )
            redirect(
                url(
                    controller='account',
                    action='profile',
                    id=user.id,
                    edit='true'
                )
            )
        redirect(url(controller='blog', action='index'))
예제 #5
0
    def rss(self, posts):
        if not posts:
            h.flash('There are no posts to show an RSS Feed for.', 'warning')
            redirect(url(controller='blog', action='index'))

        author = model.User.first()
        host = request_config().host
        feed_kwargs = {}
        if author.email:
            feed_kwargs['author_email'] = author.email

        feed = Atom1Feed(
            title=config['rss.title'],
            description=config['rss.description'],
            link=url(host=host, controller='blog', action='index'),
            author_name=author.name,
            author_link=url(
                host=host,
                controller='account',
                action='profile',
                id=author.id
            ),
            **feed_kwargs
        )
        for post in c.posts:
            item_kwargs = {}
            if post.user.email:
                item_kwargs['author_email'] = post.user.email

            if post.summary:
                description = post.summary
            else:
                description = _('No Summary')

            feed.add_item(
                title=post.title,
                link=url(
                    host=host,
                    controller='blog',
                    action='view',
                    category=post.category.slug,
                    slug=post.slug
                ),
                description=description,
                pubdate=post.posted,
                author_name=post.user.name,
                author_link=url(
                    host=host,
                    controller='account',
                    action='profile',
                    id=post.user.id
                ),
                **item_kwargs
            )
        response.content_type = 'application/atom+xml'
        return feed.writeString('utf-8')
예제 #6
0
    def login_complete(self):
        """This function is called once a user has succesfully logged in to
        his/her OpenID account. The user is then prompted to choose a
        preferred alias to be known as if a default one is not provided.
        """
        consumer = Consumer(session=session, store=self.openid_store)
        host = request.headers['host']
        return_url = url(host=host,
                         controller='account',
                         action='login_complete')
        result = consumer.complete(request.params, return_url)
        if result.status != 'success':
            return _('An error ocurred with login.')
        try:
            user = model.User.by_identifier(result.identity_url).one()
            session['userid'] = user.id
        except (AttributeError, NoResultFound):
            # No previous login record for the user.
            sreg_res = SRegResponse.fromSuccessResponse(result)
            try:
                email = sreg_res['email']
            except (TypeError, KeyError):
                email = ''

            try:
                name = sreg_res['nickname']
            except (TypeError, KeyError):
                name = result.identity_url
            user = model.User(name=name,
                              identifier=result.identity_url,
                              email=email)
            try:
                model.User.all()
            except NoResultFound:
                # Since you're going to be the only user, might as well grant
                # you administrator privileges.
                user.admin = True
            model.session.add(user)
            model.session.commit()
            session['userid'] = user.id
        session.save()
        if user.name == result.identity_url:
            h.flash(_('Login was successful, but now you need to set a name.'),
                    'warning')
            redirect(
                url(controller='account',
                    action='profile',
                    id=user.id,
                    edit='true'))
        redirect(url(controller='blog', action='index'))
예제 #7
0
class AccountController(BaseController):
    geoip = GeoIP(os.path.join(config['pylons.paths']['data'], 'geoip.dat'))
    openid_store = FileOpenIDStore('/var/tmp')

    @require('guest')
    def login(self):
        login = render('account/login.tpl', slacks=True)

        if request.environ['REQUEST_METHOD'] != 'POST':
            return login

        try:
            form = LoginForm().to_python(request.POST)
        except validators.Invalid, e:
            return h.htmlfill(e, form=login)

        try:
            cons = Consumer(session=session, store=self.openid_store)
            auth_request = cons.begin(form['openid_identifier'])
            auth_request.addExtension(
                SRegRequest(optional=['nickname', 'email']))
        except DiscoveryFailure:
            h.flash(_('The specified URL is not a valid OpenID end-point.'),
                    'error')
            redirect(url(controller='account', action='login'))
        host = request.headers['host']
        realm = '%s://%s' % (request_config().protocol, host)
        return_url = url(host=host,
                         controller='account',
                         action='login_complete')
        new_url = auth_request.redirectURL(return_to=return_url, realm=realm)
        redirect(new_url)
예제 #8
0
 def edit_comment(self, comment, post):
     try:
         form = CommentUserForm().to_python(request.POST)
         if form['delete']:
             model.Comment.by_id(comment.id).delete()
             c.post.comments_count -= 1
             model.session.commit()
             h.flash(_('Comment deleted successfully.'), 'success')
             redirect_url = c.post_url
         else:
             comment.content = form['comment']
             model.session.commit()
             h.flash(_('Comment edited successfully.'), 'success')
             redirect_url = '%s#comment-%d' % (c.post_url, comment.id)
         redirect(redirect_url)
     except validators.Invalid, e:
         return h.htmlfill(e, form=post)
예제 #9
0
 def edit_category(self, category_view):
     try:
         form = CategoryForm().to_python(request.POST)
         if form['delete']:
             posts = model.Post.by_category(c.category.id)
             for post in posts.all():
                 model.Comment.by_post(post.id).delete()
             posts.delete()
             model.Category.by_id(c.category.id).delete()
             model.session.commit()
             h.flash(_('Category deleted successfully.'), 'success')
             redirect_url = url(controller='blog', action='index')
         else:
             c.category.title = form['title']
             model.session.commit()
             h.flash(_('Category edited successfully.'), 'success')
             redirect_url = url(
                 controller='blog',
                 action='view',
                 category=c.category.slug
             )
         redirect(redirect_url)
     except validators.Invalid, e:
         return h.htmlfill(e, form=category_view)
예제 #10
0
    def profile(self, id='', edit=''):
        @cache.beaker_cache(**config['cache_options'])
        def get_user():
            return model.User.by_id(id).one()

        @cache.beaker_cache(**config['cache_options'])
        def get_users():
            return model.User.all()

        if not id:
            try:
                c.profiles = get_users()
            except NoResultFound:
                c.profiles = []
            return render('account/profiles.tpl', slacks=True)

        try:
            c.profile = get_user()
        except NoResultFound:
            abort(404)
        c.breadcrumbs.append({
            'title': _('Users List'),
            'url': url(controller='account', action='profile')
        })
        c.canedit = (c.user.admin or c.user.id == c.profile.id)
        c.editing = False
        if edit:
            if c.canedit:
                c.editing = True
                c.breadcrumbs.append({
                    'title': _('Editing'),
                    'url': ''
                })
            else:
                abort(403)

        sorted(c.profile.comments, reverse=True)
        try:
            c.country = self.geoip.country_code_by_addr(c.profile.ip).lower()
        except AttributeError:
            c.country = ''
        c.comments = c.profile.comments[:5]
        c.comments_count = len(c.profile.comments)
        c.posts_count = len(c.profile.posts)
        profile_page = render('account/profile.tpl', slacks=True)

        if not request.environ['REQUEST_METHOD'] == 'POST':
            return profile_page

        try:
            form = ProfileForm().to_python(request.POST)
            # Only administrators can delete users.
            if form['delete'] and c.user.admin:
                # Delete all posts, comments and finally the profile for this
                # user if checkbox is ticked.
                model.Post.by_user(c.profile.id).delete()
                model.Comment.by_user(c.profile.id).delete()
                model.User.by_id(c.profile.id).delete()
                model.session.commit()
                h.flash(_('User has been deleted.'), 'success')
                redirect_url = url(controller='blog', action='index')
            else:
                if form['name'] != c.profile.name:
                    try:
                        model.User.by_name(form['name']).one()
                        h.flash(_('Username Taken'), 'error')
                    except NoResultFound:
                        c.profile.name = form['name']

                c.profile.email = form['email']
                c.profile.identifier = form['identifier']
                c.profile.website = form['website']
                model.session.commit()
                h.flash(_('Profile Updated'), 'success')
                redirect_url = url(
                    controller='account',
                    action='profile',
                    id=c.profile.id
                )
            redirect(redirect_url)
        except validators.Invalid, e:
            return h.htmlfill(e, profile_page)
예제 #11
0
    def profile(self, id='', edit=''):
        @cache.beaker_cache(**config['cache_options'])
        def get_user():
            return model.User.by_id(id).one()

        @cache.beaker_cache(**config['cache_options'])
        def get_users():
            return model.User.all()

        if not id:
            try:
                c.profiles = get_users()
            except NoResultFound:
                c.profiles = []
            return render('account/profiles.tpl', slacks=True)

        try:
            c.profile = get_user()
        except NoResultFound:
            abort(404)
        c.breadcrumbs.append({
            'title': _('Users List'),
            'url': url(controller='account', action='profile')
        })
        c.canedit = (c.user.admin or c.user.id == c.profile.id)
        c.editing = False
        if edit:
            if c.canedit:
                c.editing = True
                c.breadcrumbs.append({'title': _('Editing'), 'url': ''})
            else:
                abort(403)

        sorted(c.profile.comments, reverse=True)
        try:
            c.country = self.geoip.country_code_by_addr(c.profile.ip).lower()
        except AttributeError:
            c.country = ''
        c.comments = c.profile.comments[:5]
        c.comments_count = len(c.profile.comments)
        c.posts_count = len(c.profile.posts)
        profile_page = render('account/profile.tpl', slacks=True)

        if not request.environ['REQUEST_METHOD'] == 'POST':
            return profile_page

        try:
            form = ProfileForm().to_python(request.POST)
            # Only administrators can delete users.
            if form['delete'] and c.user.admin:
                # Delete all posts, comments and finally the profile for this
                # user if checkbox is ticked.
                model.Post.by_user(c.profile.id).delete()
                model.Comment.by_user(c.profile.id).delete()
                model.User.by_id(c.profile.id).delete()
                model.session.commit()
                h.flash(_('User has been deleted.'), 'success')
                redirect_url = url(controller='blog', action='index')
            else:
                if form['name'] != c.profile.name:
                    try:
                        model.User.by_name(form['name']).one()
                        h.flash(_('Username Taken'), 'error')
                    except NoResultFound:
                        c.profile.name = form['name']

                c.profile.email = form['email']
                c.profile.identifier = form['identifier']
                c.profile.website = form['website']
                model.session.commit()
                h.flash(_('Profile Updated'), 'success')
                redirect_url = url(controller='account',
                                   action='profile',
                                   id=c.profile.id)
            redirect(redirect_url)
        except validators.Invalid, e:
            return h.htmlfill(e, profile_page)
예제 #12
0
     return h.htmlfill(e, form=post_form)
 # Use Akismet if a key has been provided to verify if a comment is
 # SPAM.  If it is marked as SPAM, then it will be hidden from view and
 # shown only to administrators, with the option of whether to approve
 # a comment or not.
 akismet_key = config.get('akismet.key', '')
 akismet_data = {
     'user_agent': request.environ.get('HTTP_USER_AGENT', ''),
     'user_ip': h.getip()
 }
 if akismet_key:
     akismet = Akismet(akismet_key)
     if akismet.comment_check(form['comment'], data=akismet_data):
         comment_args['spam'] = 1
         h.flash(
             _('This comment has been marked for admin approval.'),
             'warning'
         )
 # Finally, add the comment.
 comment = model.Comment(
     c.post.id,
     form['comment'],
     ip=remote_ip,
     **comment_kwargs
 )
 c.post.comments_count += 1
 model.session.add(comment)
 model.session.commit()
 redirect_url = '%s' % (url.current(),)
 if not comment.spam:
     redirect_url = u''.join(
         [redirect_url, '#comment-%s' % (comment.id,)]