PageRenderTime 102ms CodeModel.GetById 39ms app.highlight 12ms RepoModel.GetById 49ms app.codeStats 0ms

/kai/model/validators.py

https://bitbucket.org/bbangert/kai/
Python | 115 lines | 110 code | 4 blank | 1 comment | 2 complexity | ee392fb3500e6943321a49fbb892ea2f MD5 | raw file
  1"""Custom validators"""
  2import re
  3from datetime import datetime
  4
  5import formencode
  6import pylons
  7
  8from kai.model import Human, Snippet
  9
 10
 11class ExistingSnippetTitle(formencode.FancyValidator):
 12    def _to_python(self, value, state):
 13        if Snippet.exists(value):
 14            route_data = pylons.request.environ['pylons.routes_dict']
 15            slug = value.replace(" ", "_")
 16            slug = slug.lower()
 17            slug = re.sub('[^A-Za-z0-9_]+', '', slug)
 18            
 19            if route_data['action'] == 'update' and slug == route_data['id']:
 20                return value
 21            raise formencode.Invalid('Title already exists', value, state)
 22        return value
 23
 24
 25class ExistingEmail(formencode.FancyValidator):
 26    def _to_python(self, value, state):
 27        if not isinstance(value, basestring):
 28            raise formencode.Invalid('Invalid e-mail address type')
 29        users = list(Human.by_email(pylons.tmpl_context.db)[value])
 30        if not users:
 31            raise formencode.Invalid('No such e-mail address was found',
 32                                     value, state)
 33        user = users[0]
 34        
 35        # Check to see if the user has recently asked for an email token
 36        if user.password_token_issue:
 37            diff = datetime.utcnow() - user.password_token_issue
 38            if diff.days < 1 and diff.seconds < 3600:
 39                raise formencode.Invalid(
 40                    "You've already requested a password recently.  Please " 
 41                    "wait and try later.", value, state)
 42        return value
 43
 44
 45class UniqueDisplayname(formencode.FancyValidator):
 46    def _to_python(self, value, state):
 47        if list(Human.by_displayname(pylons.tmpl_context.db)[value]):
 48            raise formencode.Invalid('Display name already exists',
 49                                     value, state)
 50        else:
 51            return value
 52
 53
 54class UniqueEmail(formencode.FancyValidator):
 55    def _to_python(self, value, state):
 56        if list(Human.by_email(pylons.tmpl_context.db)[value]):
 57            raise formencode.Invalid('Email address already exists', value,
 58                                     state)
 59        else:
 60            return value
 61
 62
 63class ValidPassword(formencode.FancyValidator):
 64    def _to_python(self, value, state):
 65        if len(value) < 6:
 66            raise formencode.Invalid('Password is too short, must be at least'
 67                                     ' 6 characters', value, state)
 68        return value
 69
 70
 71class ValidLogin(formencode.FancyValidator):
 72    field_names = None
 73    validate_partial_form = False
 74    email = None
 75    answer = None
 76    password = None
 77
 78    messages = {
 79        'badlogin': "Invalid email and/or password",
 80    }
 81    
 82    def is_empty(self, value):
 83        return False
 84    
 85    def validate_python(self, field_dict, state):
 86        errors = {}
 87        email = field_dict[self.email]
 88        password = field_dict[self.password]
 89        
 90        if isinstance(email, basestring):
 91            users = list(Human.by_email(pylons.tmpl_context.db)[email])
 92        else:
 93            users = None
 94        
 95        if users:
 96            user = users[0]
 97        else:
 98            user = None
 99        
100        if not user:
101            errors[self.email] = self.message('badlogin', state)
102        if not errors:
103            valid_password = user.verify_password(password)
104            if valid_password:
105                field_dict['user'] = user
106            else:
107                errors[self.email] = self.message('badlogin', state)
108        if errors:
109            error_list = errors.items()
110            error_list.sort()
111            error_message = '<br>\n'.join(
112                ['%s: %s' % (name, value) for name, value in error_list])
113            raise formencode.Invalid(error_message,
114                                     field_dict, state,
115                                     error_dict=errors)