| 1 |
import datetime |
| 2 |
import hmac |
| 3 |
import math |
| 4 |
import random |
| 5 |
import re |
| 6 |
import sys |
| 7 |
from hashlib import sha1 |
| 8 |
from urllib.parse import urlparse |
| 9 |
|
| 10 |
from flask import abort |
| 11 |
from flask import render_template |
| 12 |
from flask import request |
| 13 |
from peewee import BooleanField |
| 14 |
from peewee import DateTimeField |
| 15 |
from peewee import DoesNotExist |
| 16 |
from peewee import ForeignKeyField |
| 17 |
from peewee import Model |
| 18 |
from peewee import SelectQuery |
| 19 |
from werkzeug.security import check_password_hash |
| 20 |
from werkzeug.security import generate_password_hash |
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
def get_object_or_404(query_or_model, *query): |
| 25 |
if not isinstance(query_or_model, SelectQuery): |
| 26 |
query_or_model = query_or_model.select() |
| 27 |
try: |
| 28 |
return query_or_model.where(*query).get() |
| 29 |
except DoesNotExist: |
| 30 |
abort(404) |
| 31 |
|
| 32 |
def object_list(template_name, qr, var_name='object_list', **kwargs): |
| 33 |
pq = PaginatedQuery(qr, kwargs.pop('paginate_by', 20)) |
| 34 |
kwargs[var_name] = pq.get_list() |
| 35 |
return render_template(template_name, pagination=pq, page=pq.get_page(), **kwargs) |
| 36 |
|
| 37 |
|
| 38 |
class PaginatedQuery(object): |
| 39 |
page_var = 'page' |
| 40 |
|
| 41 |
def __init__(self, query_or_model, paginate_by): |
| 42 |
self.paginate_by = paginate_by |
| 43 |
|
| 44 |
if isinstance(query_or_model, SelectQuery): |
| 45 |
self.query = query_or_model |
| 46 |
self.model = self.query.model |
| 47 |
else: |
| 48 |
self.model = query_or_model |
| 49 |
self.query = self.model.select() |
| 50 |
|
| 51 |
def get_page(self): |
| 52 |
curr_page = request.args.get(self.page_var) |
| 53 |
if curr_page and curr_page.isdigit(): |
| 54 |
return int(curr_page) |
| 55 |
return 1 |
| 56 |
|
| 57 |
def get_count(self): |
| 58 |
if not hasattr(self, '_get_count'): |
| 59 |
self._get_count = self.query.count() |
| 60 |
return self._get_count |
| 61 |
|
| 62 |
def get_pages(self): |
| 63 |
if not hasattr(self, '_get_pages'): |
| 64 |
self._get_pages = int(math.ceil( |
| 65 |
float(self.get_count()) / self.paginate_by)) |
| 66 |
return self._get_pages |
| 67 |
|
| 68 |
def get_list(self): |
| 69 |
return self.query.paginate(self.get_page(), self.paginate_by) |
| 70 |
|
| 71 |
def get_page_range(self, window=3): |
| 72 |
# a windowed list of page numbers around the current page, with None |
| 73 |
# marking gaps (rendered as an ellipsis), e.g. [1, None, 4, 5, 6, None, 20]. |
| 74 |
total = self.get_pages() |
| 75 |
current = min(self.get_page(), total) |
| 76 |
pages = sorted(set( |
| 77 |
[1, total] + |
| 78 |
list(range(max(1, current - window), min(total, current + window) + 1)) |
| 79 |
)) |
| 80 |
result = [] |
| 81 |
prev = 0 |
| 82 |
for page in pages: |
| 83 |
if page > prev + 1: |
| 84 |
result.append(None) |
| 85 |
result.append(page) |
| 86 |
prev = page |
| 87 |
return result |
| 88 |
|
| 89 |
|
| 90 |
def get_next(): |
| 91 |
if not request.query_string: |
| 92 |
return request.path |
| 93 |
return '%s?%s' % (request.path, request.query_string) |
| 94 |
|
| 95 |
def is_safe_url(url): |
| 96 |
# only allow redirects to relative, same-host paths -- reject absolute |
| 97 |
# urls (http://evil.com) and scheme-relative urls (//evil.com). |
| 98 |
if not url: |
| 99 |
return False |
| 100 |
parsed = urlparse(url) |
| 101 |
return not parsed.scheme and not parsed.netloc |
| 102 |
|
| 103 |
def slugify(s): |
| 104 |
return re.sub(r'[^a-z0-9_\-]+', '-', s.lower()) |
| 105 |
|
| 106 |
def load_class(s): |
| 107 |
path, klass = s.rsplit('.', 1) |
| 108 |
__import__(path) |
| 109 |
mod = sys.modules[path] |
| 110 |
return getattr(mod, klass) |
| 111 |
|
| 112 |
def get_dictionary_from_model(model, fields=None, exclude=None): |
| 113 |
model_class = type(model) |
| 114 |
data = {} |
| 115 |
|
| 116 |
fields = fields or {} |
| 117 |
exclude = exclude or {} |
| 118 |
curr_exclude = exclude.get(model_class, []) |
| 119 |
curr_fields = fields.get(model_class, model._meta.sorted_field_names) |
| 120 |
|
| 121 |
for field_name in curr_fields: |
| 122 |
if field_name in curr_exclude: |
| 123 |
continue |
| 124 |
field_obj = model_class._meta.fields[field_name] |
| 125 |
field_data = model.__data__.get(field_name) |
| 126 |
if isinstance(field_obj, ForeignKeyField) and field_data and field_obj.rel_model in fields: |
| 127 |
rel_obj = getattr(model, field_name) |
| 128 |
data[field_name] = get_dictionary_from_model(rel_obj, fields, exclude) |
| 129 |
else: |
| 130 |
data[field_name] = field_data |
| 131 |
return data |
| 132 |
|
| 133 |
def get_model_from_dictionary(model, field_dict, strict=False): |
| 134 |
if isinstance(model, Model): |
| 135 |
model_instance = model |
| 136 |
check_fks = True |
| 137 |
else: |
| 138 |
model_instance = model() |
| 139 |
check_fks = False |
| 140 |
models = [model_instance] |
| 141 |
for field_name, value in field_dict.items(): |
| 142 |
try: |
| 143 |
field_obj = model._meta.fields[field_name] |
| 144 |
except KeyError: |
| 145 |
if not strict: |
| 146 |
setattr(model_instance, field_name, value) |
| 147 |
continue |
| 148 |
|
| 149 |
if isinstance(value, dict) and isinstance(field_obj, ForeignKeyField): |
| 150 |
rel_obj = field_obj.rel_model |
| 151 |
if check_fks: |
| 152 |
try: |
| 153 |
rel_obj = getattr(model, field_name) |
| 154 |
except field_obj.rel_model.DoesNotExist: |
| 155 |
pass |
| 156 |
if rel_obj is None: |
| 157 |
rel_obj = field_obj.rel_model |
| 158 |
rel_inst, rel_models = get_model_from_dictionary(rel_obj, value) |
| 159 |
models.extend(rel_models) |
| 160 |
setattr(model_instance, field_name, rel_inst) |
| 161 |
else: |
| 162 |
if isinstance(field_obj, BooleanField): |
| 163 |
if isinstance(value, str) and value.lower() in ('0', 'f', 'false', ''): |
| 164 |
value = False |
| 165 |
elif isinstance(field_obj, DateTimeField): |
| 166 |
value = deserialize_datetime(field_obj, value) |
| 167 |
|
| 168 |
setattr(model_instance, field_name, field_obj.python_value(value)) |
| 169 |
return model_instance, models |
| 170 |
|
| 171 |
def deserialize_datetime(field_obj, value): |
| 172 |
formats = ('%Y-%m-%dT%H:%M:%S%z', |
| 173 |
'%Y-%m-%dT%H:%M:%S.%f', |
| 174 |
'%Y-%m-%dT%H:%M:%S', |
| 175 |
'%Y-%m-%dT', |
| 176 |
'%Y-%m-%d') |
| 177 |
for fmt in formats: |
| 178 |
try: |
| 179 |
return datetime.datetime.strptime(value, fmt) |
| 180 |
except Exception: |
| 181 |
continue |
| 182 |
return value |
| 183 |
|
| 184 |
def path_to_models(model, path): |
| 185 |
accum = [] |
| 186 |
if '__' in path: |
| 187 |
attr, path = path.split('__', 1) |
| 188 |
else: |
| 189 |
attr, path = path, '' |
| 190 |
if attr in model._meta.fields: |
| 191 |
field = model._meta.fields[attr] |
| 192 |
accum.append(field.rel_model) |
| 193 |
else: |
| 194 |
raise AttributeError('%s has no related field named "%s"' % (model, attr)) |
| 195 |
if path: |
| 196 |
accum.extend(path_to_models(model, path)) |
| 197 |
return accum |
| 198 |
|
| 199 |
|
| 200 |
def convert_boolean(s): |
| 201 |
if isinstance(s, str) and s.lower() in ('', '0', 'false', 'f'): |
| 202 |
return False |
| 203 |
return bool(s) |
| 204 |
|
| 205 |
|
| 206 |
# legacy django-style salted-sha1 hashes, e.g. "a1b2c$<40 hex chars>". |
| 207 |
LEGACY_PASSWORD_RE = re.compile(r'^[0-9a-f]{5}\$[0-9a-f]{40}$') |
| 208 |
|
| 209 |
# hashing method passed to werkzeug -- override to tune cost, e.g. in tests. |
| 210 |
# See werkzeug.security.generate_password_hash for accepted values. |
| 211 |
PASSWORD_HASH_METHOD = 'scrypt' |
| 212 |
|
| 213 |
|
| 214 |
def get_hexdigest(salt, raw_password): |
| 215 |
data = salt + raw_password |
| 216 |
return sha1(data.encode('utf8')).hexdigest() |
| 217 |
|
| 218 |
def is_legacy_password(enc_password): |
| 219 |
return bool(LEGACY_PASSWORD_RE.match(enc_password or '')) |
| 220 |
|
| 221 |
def make_password(raw_password): |
| 222 |
return generate_password_hash(raw_password, method=PASSWORD_HASH_METHOD) |
| 223 |
|
| 224 |
def check_password(raw_password, enc_password): |
| 225 |
if is_legacy_password(enc_password): |
| 226 |
salt, hsh = enc_password.split('$', 1) |
| 227 |
return hmac.compare_digest(hsh, get_hexdigest(salt, raw_password)) |
| 228 |
return check_password_hash(enc_password, raw_password) |