plone.app.discussion/plone/app/discussion/browser/captcha.py

70 lines
2.5 KiB
Python
Raw Permalink Normal View History

# Captcha validator, see captcha.txt for design notes.
from persistent import Persistent
from plone.app.discussion.browser.comments import CommentForm
from plone.app.discussion.comment import Comment
from plone.app.discussion.interfaces import ICaptcha
from plone.app.discussion.interfaces import IDiscussionSettings
from plone.registry.interfaces import IRegistry
from plone.z3cform.fieldsets import extensible
from Products.CMFCore.utils import getToolByName
from z3c.form import interfaces
from z3c.form.field import Fields
from zope import interface
from zope.annotation import factory
2017-07-28 17:58:35 +02:00
from zope.component import adapter
from zope.component import queryUtility
from zope.interface import Interface
from zope.publisher.interfaces.browser import IDefaultBrowserLayer
2017-07-28 17:58:35 +02:00
@adapter(Comment)
@interface.implementer(ICaptcha)
class Captcha(Persistent):
2022-05-01 23:14:09 +02:00
"""Captcha input field."""
captcha = ""
2017-07-28 17:58:35 +02:00
Captcha = factory(Captcha)
2017-07-28 17:58:35 +02:00
# context, request, form
@adapter(Interface, IDefaultBrowserLayer, CommentForm)
class CaptchaExtender(extensible.FormExtender):
"""Extends the comment form with a Captcha. This Captcha extender is only
registered when a plugin is installed that provides the
"plone.app.discussion-captcha" feature.
"""
fields = Fields(ICaptcha)
def __init__(self, context, request, form):
self.context = context
self.request = request
self.form = form
registry = queryUtility(IRegistry)
settings = registry.forInterface(IDiscussionSettings, check=False)
self.captcha = settings.captcha
2022-05-01 23:14:09 +02:00
portal_membership = getToolByName(self.context, "portal_membership")
self.isAnon = portal_membership.isAnonymousUser()
def update(self):
2022-05-01 23:14:09 +02:00
if self.captcha != "disabled" and self.isAnon:
# Add a captcha field if captcha is enabled in the registry
2022-05-01 23:14:09 +02:00
self.add(ICaptcha, prefix="")
if self.captcha == "captcha":
from plone.formwidget.captcha import CaptchaFieldWidget
2022-05-01 23:14:09 +02:00
self.form.fields["captcha"].widgetFactory = CaptchaFieldWidget
elif self.captcha == "recaptcha":
from plone.formwidget.recaptcha import ReCaptchaFieldWidget
2022-05-01 23:14:09 +02:00
self.form.fields["captcha"].widgetFactory = ReCaptchaFieldWidget
elif self.captcha == "norobots":
from collective.z3cform.norobots import NorobotsFieldWidget
2022-05-01 23:14:09 +02:00
self.form.fields["captcha"].widgetFactory = NorobotsFieldWidget
else:
2022-05-01 23:14:09 +02:00
self.form.fields["captcha"].mode = interfaces.HIDDEN_MODE