Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

106 řádky
3.1 KiB

před 3 roky
  1. # -*- coding: utf-8 -*-
  2. """
  3. :author: Grey Li ()
  4. :url: http://greyli.com
  5. :copyright: © 2018 Grey Li <withlihui@gmail.com>
  6. :license: MIT, see LICENSE for more details.
  7. """
  8. import os
  9. import uuid
  10. try:
  11. from urlparse import urlparse, urljoin
  12. except ImportError:
  13. from urllib.parse import urlparse, urljoin
  14. import PIL
  15. from PIL import Image
  16. from flask import current_app, request, url_for, redirect, flash
  17. from itsdangerous import BadSignature, SignatureExpired
  18. from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
  19. from albumy.extensions import db
  20. from albumy.models import User
  21. from albumy.settings import Operations
  22. def generate_token(user, operation, expire_in=None, **kwargs):
  23. s = Serializer(current_app.config['SECRET_KEY'], expire_in)
  24. data = {'id': user.id, 'operation': operation}
  25. data.update(**kwargs)
  26. return s.dumps(data)
  27. def validate_token(user, token, operation, new_password=None):
  28. s = Serializer(current_app.config['SECRET_KEY'])
  29. try:
  30. data = s.loads(token)
  31. except (SignatureExpired, BadSignature):
  32. return False
  33. if operation != data.get('operation') or user.id != data.get('id'):
  34. return False
  35. if operation == Operations.CONFIRM:
  36. user.confirmed = True
  37. elif operation == Operations.RESET_PASSWORD:
  38. user.set_password(new_password)
  39. elif operation == Operations.CHANGE_EMAIL:
  40. new_email = data.get('new_email')
  41. if new_email is None:
  42. return False
  43. if User.query.filter_by(email=new_email).first() is not None:
  44. return False
  45. user.email = new_email
  46. else:
  47. return False
  48. db.session.commit()
  49. return True
  50. def rename_image(old_filename):
  51. ext = os.path.splitext(old_filename)[1]
  52. new_filename = uuid.uuid4().hex + ext
  53. return new_filename
  54. def resize_image(image, filename, base_width):
  55. filename, ext = os.path.splitext(filename)
  56. img = Image.open(image)
  57. if img.size[0] <= base_width:
  58. return filename + ext
  59. w_percent = (base_width / float(img.size[0]))
  60. h_size = int((float(img.size[1]) * float(w_percent)))
  61. img = img.resize((base_width, h_size), PIL.Image.ANTIALIAS)
  62. filename += current_app.config['ALBUMY_PHOTO_SUFFIX'][base_width] + ext
  63. img.save(os.path.join(current_app.config['ALBUMY_UPLOAD_PATH'], filename), optimize=True, quality=85)
  64. return filename
  65. def is_safe_url(target):
  66. ref_url = urlparse(request.host_url)
  67. test_url = urlparse(urljoin(request.host_url, target))
  68. return test_url.scheme in ('http', 'https') and \
  69. ref_url.netloc == test_url.netloc
  70. def redirect_back(default='main.index', **kwargs):
  71. for target in request.args.get('next'), request.referrer:
  72. if not target:
  73. continue
  74. if is_safe_url(target):
  75. return redirect(target)
  76. return redirect(url_for(default, **kwargs))
  77. def flash_errors(form):
  78. for field, errors in form.errors.items():
  79. for error in errors:
  80. flash(u"Error in the %s field - %s" % (
  81. getattr(form, field).label.text,
  82. error
  83. ))