| | 100 | class ListCharField(forms.CharField): |
| | 101 | """ |
| | 102 | Items seperated by spaces. |
| | 103 | |
| | 104 | >>> f = ListCharField() |
| | 105 | >>> f.clean(' one two tree') |
| | 106 | [u'one', u'two', u'tree'] |
| | 107 | """ |
| | 108 | def clean(self, value): |
| | 109 | raw_value = super(ListCharField, self).clean(value) |
| | 110 | value = raw_value.strip() |
| | 111 | items = [i.strip() for i in value.split(" ")] |
| | 112 | items = [i for i in items if i] # eliminate empty items |
| | 113 | return items |
| | 114 | |
| | 115 | |
| | 116 | class InternalURLField(forms.CharField): |
| | 117 | """ |
| | 118 | Uses e.g. for back urls via a http GET parameter |
| | 119 | validates the URL and check if is't a internal url and not |
| | 120 | a external. |
| | 121 | |
| | 122 | >>> f = InternalURLField() |
| | 123 | >>> f.clean('/a/foobar/url/') |
| | 124 | u'/a/foobar/url/' |
| | 125 | |
| | 126 | >>> f.clean('http://eval.domain.tld') |
| | 127 | Traceback (most recent call last): |
| | 128 | ... |
| | 129 | ValidationError: [u'Open redirect found.'] |
| | 130 | |
| | 131 | >>> f = InternalURLField(must_start_with="/_command/") |
| | 132 | >>> f.clean('/_command/a/foobar/url/') |
| | 133 | u'/_command/a/foobar/url/' |
| | 134 | |
| | 135 | >>> f.clean('/a/wrong/url/') |
| | 136 | Traceback (most recent call last): |
| | 137 | ... |
| | 138 | ValidationError: [u'Open redirect found.'] |
| | 139 | """ |
| | 140 | default_error_message = "Open redirect found." |
| | 141 | |
| | 142 | def __init__(self, must_start_with=None, *args, **kwargs): |
| | 143 | self.must_start_with = must_start_with |
| | 144 | super(InternalURLField, self).__init__(*args, **kwargs) |
| | 145 | |
| | 146 | def clean(self, value): |
| | 147 | value = super(InternalURLField, self).clean(value) |
| | 148 | if "://" in value: |
| | 149 | raise ValidationError(self.default_error_message) |
| | 150 | if self.must_start_with and not value.startswith(self.must_start_with): |
| | 151 | raise ValidationError(self.default_error_message) |
| | 152 | return value |
| | 153 | |
| | 154 | |
| | 155 | |