Source

tgext.registration2 / tgext / registration2 / widgets.py

from pylons import request
try:
    import tg.predicates as identity
except:
    # Pre Turbogears 2.2.0 + repoze.who 2.x:
    import repoze.what.predicates as identity

from tw.forms.validators import UnicodeString, Email, FancyValidator, Invalid, \
        All, Schema, FieldsMatch
from tw.forms import TableForm, TextField, PasswordField
from tw.output import OutputText
from tw.api import WidgetsList
from tw.recaptcha import ReCaptchaWidget
from tw.recaptcha.validator import ReCaptchaValidator

import model

from pylons.i18n import ugettext as _

from tg import config


class NewUserFields(WidgetsList):
    
    user_name = TextField('user_name',
                    label_text=_("User Name"),
                    help_text=_("A short name that you will use to log in."))
                    
    email = TextField('email',
                    label_text=_("Email"),
                    help_text=_("Your email address (this will be validated)."))
                    
    email2 = TextField('email2',
                    label_text=_("Email (again)"),
                    help_text=_("Your email address again, please."))
    
    display_name = TextField('display_name',
                    label_text=_("Display Name"),
                    help_text=_("A longer user name that others will see."))
                    
    password1 = PasswordField('password1',
                    label_text=_("Password"),
                    help_text=_("Your password."))
                    
    password2 = PasswordField('password2',
                    label_text= _("Password (again)"),
                    help_text=_("Same password as above (the two should match)."))
                    
    if not config.reg_config.recaptcha.disabled:
        recaptcha_response_field = ReCaptchaWidget(
                    label_text= _("reCAPTCHA"),
                    public_key=config.reg_config.recaptcha.public_key,
                    use_ssl=True,
                   )
                    
class ExistingUserFields(WidgetsList):
    
    user_name = OutputText('user_name',
                    label_text=_("User Name") )
                    
    email = TextField('email',
                    label_text=_("Email"),
                    help_text=_("Your email address (this will be validated)."))
    
    display_name = TextField('display_name',
                    label_text=_("Display Name"),
                    help_text=_("A longer user name that others will see."))
    
    old_password = PasswordField('old_password',
                   label_text=_("Current password"),
                   help_text=_("The current (old) password."))

    password1 = PasswordField('password1',
                    label_text=_("New Password"),
                    help_text=_("Your new password. (If you would like to change it)."))

    password2 = PasswordField('password2',
                    label_text=_("New Password (again)"),
                    help_text=_("New password again (should match the input above)."))
                    
class LostPasswordFields(WidgetsList):
    
    username = TextField('username',
                    label_text=_('User Name'),
                    validator=UnicodeString(not_empty=True, max=16, strip=True))
                    
    email = TextField('email',
                    label_text=_('Email Address'),
                    validator=Email(not_empty=True, max=255))
                    
class ValidPassword(FancyValidator):
    """Validator to test for validity of password.
    """
    messages = {'invalid': 'The password you supplied is invalid.'}

    def validate_python(self, value, state):
        user = dict(request.environ['repoze.who.identity'])['user']
        if not user.validate_password(value):
            raise Invalid(self.message('invalid', state), value, state)
        return value
        
    def validate_other(self, value, state):
        return self.validate_python(value, state)
        
class DeleteUserFields(WidgetsList):
    
    password = PasswordField('password', 
                    label_text=_('Password'),
                    validator=All(UnicodeString(not_empty=True, max=40),
                                             ValidPassword()))

class UniqueUsername(FancyValidator):
    "Validator to confirm that a given user_name is unique."
    messages = {'notUnique': 'That user name is already being used.'}
    
    def _to_python(self, value, state):
        if not model.user_name_is_unique(value):
            raise Invalid(self.message('notUnique', state), value, state)
        return value

class UniqueEmail(FancyValidator):
    "Validator to confirm a given email address is unique."
    messages = {'notUnique': 'That email address is registered with another existing user.'}
    
    def _to_python(self, value, state):
        if identity.not_anonymous():
            u = dict(request.environ['repoze.who.identity'])['user']
            if value == u.email_address:
                # the user isn't trying to change their email address
                # so the value is ok
                return value 
        if not model.email_is_unique(value):
            raise Invalid(self.message('notUnique', state), value, state)
        return value
        
class TGSchema(Schema):
    filter_extra_fields = False
    allow_extra_fields = True
    ignore_key_missing = False
    
class NewUserSchema(TGSchema):
    user_name = All(UnicodeString(not_empty=True, max=16, strip=True),
                    UniqueUsername())
    email = All(Email(not_empty=True, max=255),
                UniqueEmail())
    email2 = All(Email(not_empty=True, max=255))
    display_name = UnicodeString(not_empty=True, strip=True, max=255)
    password1 = UnicodeString(not_empty=True, max=40)
    password2 = UnicodeString(not_empty=True, max=40)
    chained_validators = [FieldsMatch('password1', 'password2'),
                          FieldsMatch('email', 'email2'),
                         ]
    if not config.reg_config.recaptcha.disabled:
        chained_validators.append(
            ReCaptchaValidator(config.reg_config.recaptcha.private_key, 
                               request.remote_addr)
                )
    
class ExistingUserSchema(TGSchema):
    email = All(Email(not_empty=True, max=255),
                UniqueEmail())
    display_name = UnicodeString(not_empty=True, strip=True, max=255)
    old_password = All(UnicodeString(not_empty=True, max=40),
                                    ValidPassword())
    password1 = UnicodeString(max=40)
    password2 = UnicodeString(max=40)
    chained_validators = [FieldsMatch('password1', 'password2')]
    
class RegTableForm(TableForm):
#    template = "tgext.registration2.templates.tabletemplate3"
    validator = TGSchema

lost_password_form = RegTableForm(fields=LostPasswordFields())

delete_user_form = RegTableForm(fields=DeleteUserFields(),
                                submit_text=_('Really delete'),
                                attrs=dict(onsubmit='return confirmDelete();'),
                               )

new_user_form = RegTableForm(fields=NewUserFields(), validator=NewUserSchema())
                                    
edit_user_form = RegTableForm(fields=ExistingUserFields(), validator=ExistingUserSchema())
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.