예제 #1
0
파일: validators.py 프로젝트: IanLewis/kay
def is_valid_url(message=None):
  """Check if the string passed is a valid URL.  We also blacklist some
  url schemes like javascript for security reasons.

  >>> check(is_valid_url, 'http://pocoo.org/')
  True
  >>> check(is_valid_url, 'http://zine.pocoo.org/archive')
  True
  >>> check(is_valid_url, 'zine.pocoo.org/archive')
  False
  >>> check(is_valid_url, 'javascript:alert("Zine rocks!");')
  False
  """
  if message is None:
    message = lazy_gettext(u'You have to enter a valid URL.')
  def validator(form, value):
    protocol = urlparse(value)[0]
    if not protocol or protocol == 'javascript':
      raise ValidationError(message)
  return validator
예제 #2
0
파일: validators.py 프로젝트: IanLewis/kay
def is_valid_email(message=None):
  """Check if the string passed is a valid mail address.

  >>> check(is_valid_email, '*****@*****.**')
  True
  >>> check(is_valid_email, 'somebody AT example DOT com')
  False
  >>> check(is_valid_email, 'some random string')
  False

  Because e-mail validation is painfully complex we just check the first
  part of the email if it looks okay (comments are not handled!) and ignore
  the second.
  """
  if message is None:
    message = lazy_gettext(u'You have to enter a valid e-mail address.')
  def validator(form, value):
    if len(value) > 250 or _mail_re.match(value) is None:
      raise ValidationError(message)
  return validator
예제 #3
0
def is_valid_url(message=None):
    """Check if the string passed is a valid URL.  We also blacklist some
  url schemes like javascript for security reasons.

  >>> check(is_valid_url, 'http://pocoo.org/')
  True
  >>> check(is_valid_url, 'http://zine.pocoo.org/archive')
  True
  >>> check(is_valid_url, 'zine.pocoo.org/archive')
  False
  >>> check(is_valid_url, 'javascript:alert("Zine rocks!");')
  False
  """
    if message is None:
        message = lazy_gettext(u'You have to enter a valid URL.')

    def validator(form, value):
        protocol = urlparse(value)[0]
        if not protocol or protocol == 'javascript':
            raise ValidationError(message)

    return validator
예제 #4
0
def is_valid_email(message=None):
    """Check if the string passed is a valid mail address.

  >>> check(is_valid_email, '*****@*****.**')
  True
  >>> check(is_valid_email, 'somebody AT example DOT com')
  False
  >>> check(is_valid_email, 'some random string')
  False

  Because e-mail validation is painfully complex we just check the first
  part of the email if it looks okay (comments are not handled!) and ignore
  the second.
  """
    if message is None:
        message = lazy_gettext(u'You have to enter a valid e-mail address.')

    def validator(form, value):
        if len(value) > 250 or _mail_re.match(value) is None:
            raise ValidationError(message)

    return validator
예제 #5
0
class CRUDViewGroup(ViewGroup):
    entities_per_page = 20
    templates = {
        OP_LIST: '_internal/general_list.html',
        OP_SHOW: '_internal/general_show.html',
        OP_UPDATE: '_internal/general_update.html',
    }
    forms = {}
    form = None
    owner_attr = None
    rule_template = RuleTemplate([
        Rule('/$model/list', endpoint=endpoints[OP_LIST]),
        Rule('/$model/list/<cursor>', endpoint=endpoints[OP_LIST]),
        Rule('/$model/show/<key>', endpoint=endpoints[OP_SHOW]),
        Rule('/$model/create', endpoint=endpoints[OP_CREATE]),
        Rule('/$model/update/<key>', endpoint=endpoints[OP_UPDATE]),
        Rule('/$model/delete/<key>', endpoint=endpoints[OP_DELETE]),
    ])
    messages = {
        'title_update': lazy_gettext(u"Updating a %s entity"),
        'title_create': lazy_gettext(u"Creating a new %s"),
        'result_update': lazy_gettext(u"An entity is updated successfully."),
        'result_create':
        lazy_gettext(u"A new entity is created successfully."),
        'result_delete': lazy_gettext(u"An entity is deleted successfully."),
    }

    def __init__(self, model=None, **kwargs):
        super(CRUDViewGroup, self).__init__(**kwargs)
        self.model = model or self.model
        if isinstance(self.model, basestring):
            self.model_name = self.model.split(".")[-1]
        else:
            self.model_name = self.model.__name__
        self.model_name_lower = self.model_name.lower()

    def _import_model_if_not(self):
        if isinstance(self.model, basestring):
            self.model = import_string(self.model)

    def get_additional_context_on_create(self, request, form):
        if self.owner_attr:
            if request.user.is_anonymous():
                owner = None
            else:
                owner = request.user.key()
            return {self.owner_attr: owner}
        else:
            return {}

    def get_additional_context_on_update(self, request, form):
        return {}

    def get_query(self, request):
        created_timestamp_name = None
        for k, v in self.model.fields().iteritems():
            if isinstance(v, db.DateTimeProperty):
                if hasattr(v, 'auto_now_add') and v.auto_now_add:
                    created_timestamp_name = k
        if created_timestamp_name:
            return self.model.all().order('-%s' % created_timestamp_name)
        else:
            return self.model.all()

    def get_template(self, request, name):
        return self.templates[name]

    def get_form(self, request, name):
        try:
            ret = self.forms[name]
        except KeyError:
            ret = self.form
        if isinstance(ret, basestring):
            return import_string(ret)
        else:
            return ret

    def url_for(self, *args, **kwargs):
        return url_for(*args, **kwargs)

    def get_list_url(self, cursor=None):
        return self.url_for(self.get_endpoint(OP_LIST), cursor=cursor)

    def get_detail_url(self, obj):
        return self.url_for(self.get_endpoint(OP_SHOW), key=obj.key())

    def get_delete_url(self, obj):
        return self.url_for(self.get_endpoint(OP_DELETE), key=obj.key())

    def get_update_url(self, obj):
        return self.url_for(self.get_endpoint(OP_UPDATE), key=obj.key())

    def get_create_url(self):
        return self.url_for(self.get_endpoint(OP_CREATE))

    def url_processor(self, request):
        return {
            'list_url': self.get_list_url,
            'detail_url': self.get_detail_url,
            'delete_url': self.get_delete_url,
            'update_url': self.get_update_url,
            'create_url': self.get_create_url
        }

    def authorize(self, request, operation, obj=None):
        """ Raise AuthorizationError when the operation is not permitted.
    """
        return True

    def check_authority(self, request, operation, obj=None):
        try:
            self.authorize(request, operation, obj)
        except NotAuthorized, e:
            from kay.conf import settings
            if 'kay.auth.middleware.AuthenticationMiddleware' in \
                  settings.MIDDLEWARE_CLASSES and \
                  request.user.is_anonymous():
                from kay.utils import create_login_url
                raise RequestRedirect(create_login_url(request.url))
            else:
                raise Forbidden("Access not allowed.")