You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

226 lines
7.5 KiB

  1. from datetime import datetime
  2. import hashlib
  3. from werkzeug.security import generate_password_hash, check_password_hash
  4. from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
  5. from markdown import markdown
  6. import bleach
  7. from itsdangerous import BadSignature
  8. from flask import current_app
  9. from flask_login import UserMixin, AnonymousUserMixin
  10. from . import db, login_manager
  11. class Permission:
  12. FOLLOW = 1
  13. COMMENT = 2
  14. WRITE = 4
  15. MODERATE = 8
  16. ADMIN = 16
  17. class Role(db.Model):
  18. __tablename__ = 'roles'
  19. id = db.Column(db.Integer, primary_key=True)
  20. name = db.Column(db.String(64), unique=True)
  21. default = db.Column(db.Boolean, default=False, index=True)
  22. permissions = db.Column(db.Integer)
  23. users = db.relationship('User', backref='role', lazy='dynamic')
  24. def __init__(self, **kwargs):
  25. super(Role, self).__init__(**kwargs)
  26. if self.permissions is None:
  27. self.permissions = 0
  28. @staticmethod
  29. def insert_roles():
  30. roles = {
  31. 'User': [Permission.FOLLOW, Permission.COMMENT, Permission.WRITE],
  32. 'Moderator': [Permission.FOLLOW, Permission.COMMENT,
  33. Permission.WRITE, Permission.MODERATE],
  34. 'Administrator': [Permission.FOLLOW, Permission.COMMENT,
  35. Permission.WRITE, Permission.MODERATE,
  36. Permission.ADMIN]
  37. }
  38. default_role = 'User'
  39. for r in roles:
  40. role = Role.query.filter_by(name=r).first()
  41. if role is None:
  42. role = Role(name=r)
  43. role.reset_permissions()
  44. for perm in roles[r]:
  45. role.add_permission(perm)
  46. role.default = (role.name == default_role)
  47. db.session.add(role)
  48. db.session.commit()
  49. def add_permission(self, perm):
  50. if not self.has_permission(perm):
  51. self.permissions += perm
  52. def remove_permission(self, perm):
  53. if self.has_permission(perm):
  54. self.permissions -= perm
  55. def reset_permissions(self):
  56. self.permissions = 0
  57. def has_permission(self, perm):
  58. return self.permissions & perm == perm
  59. def __repr__(self):
  60. return '<Role %r>' % self.name
  61. class User(UserMixin, db.Model):
  62. __tablename__ = 'users'
  63. id = db.Column(db.Integer, primary_key=True)
  64. email = db.Column(db.String(64), unique=True, index=True)
  65. username = db.Column(db.String(64), unique=True, index=True)
  66. role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
  67. password_hash = db.Column(db.String(128))
  68. confirmed = db.Column(db.Boolean, default=False)
  69. name = db.Column(db.String(64))
  70. location = db.Column(db.String(64))
  71. about_me = db.Column(db.Text())
  72. member_since = db.Column(db.DateTime(), default=datetime.utcnow)
  73. last_seen = db.Column(db.DateTime(), default=datetime.utcnow)
  74. avatar_hash = db.Column(db.String(32))
  75. posts = db.relationship('Post', backref='author', lazy='dynamic')
  76. def __init__(self, **kwargs):
  77. super(User, self).__init__(**kwargs)
  78. if self.role is None:
  79. if self.email == current_app.config['FLASKY_ADMIN']:
  80. self.role = Role.query.filter_by(name='Administrator').first()
  81. else:
  82. self.role = Role.query.filter_by(default=True).first()
  83. if self.email is not None and self.avatar_hash is None:
  84. self.avatar_hash = self.gravatar_hash()
  85. @property
  86. def password(self):
  87. raise AttributeError('Password is not a readable attribute')
  88. @password.setter
  89. def password(self, password):
  90. self.password_hash = generate_password_hash(password)
  91. def verify_password(self, password):
  92. return check_password_hash(self.password_hash, password)
  93. def generate_confirmation_token(self, expiration=3600):
  94. s = Serializer(current_app.config['SECRET_KEY'], expiration)
  95. return s.dumps({'confirm': self.id}).decode('utf-8')
  96. def confirm(self, token):
  97. s = Serializer(current_app.config['SECRET_KEY'])
  98. try:
  99. data = s.loads(token.encode('utf-8'))
  100. except BadSignature:
  101. return False
  102. if data.get('confirm') != self.id:
  103. return False
  104. self.confirmed = True
  105. db.session.add(self)
  106. return True
  107. def generate_reset_token(self, expiration=3600):
  108. s = Serializer(current_app.config['SECRET_KEY'], expiration)
  109. return s.dumps({'reset': self.id}).decode('utf-8')
  110. @staticmethod
  111. def reset_password(token, new_password):
  112. s = Serializer(current_app.config['SECRET_KEY'])
  113. try:
  114. data = s.loads(token.encode('utf-8'))
  115. except BadSignature:
  116. return False
  117. user = User.query.get(data.get('reset'))
  118. if user is None:
  119. return False
  120. user.password = new_password
  121. db.session.add(user)
  122. return True
  123. def generate_email_change_token(self, new_email, expiration=3600):
  124. s = Serializer(current_app.config['SECRET_KEY'], expiration)
  125. return s.dumps(
  126. {'change_email': self.id, 'new_email': new_email}).decode('utf-8')
  127. def change_email(self, token):
  128. s = Serializer(current_app.config['SECRET_KEY'])
  129. try:
  130. data = s.loads(token.encode('utf-8'))
  131. except BadSignature:
  132. return False
  133. if data.get('change_email') != self.id:
  134. return False
  135. new_email = data.get('new_email')
  136. if new_email is None:
  137. return False
  138. if self.query.filter_by(email=new_email).first() is not None:
  139. return False
  140. self.email = new_email
  141. self.gravatar_hash = self.gravatar_hash()
  142. db.session.add(self)
  143. return True
  144. def can(self, perm):
  145. return self.role is not None and self.role.has_permission(perm)
  146. def is_administrator(self):
  147. return self.can(Permission.ADMIN)
  148. def ping(self):
  149. self.last_seen = datetime.utcnow()
  150. db.session.add(self)
  151. db.session.commit()
  152. def gravatar_hash(self):
  153. return hashlib.md5(self.email.lower().encode('utf-8')).hexdigest()
  154. def gravatar(self, size=100, default='identicon', rating='g'):
  155. url = 'https://secure.gravatar.com/avatar'
  156. hash = self.avatar_hash or self.gravatar_hash()
  157. return '{url}/{hash}?s={size}&d={default}&r={rating}'.format(
  158. url=url, hash=hash, size=size, default=default, rating=rating)
  159. def __repr__(self):
  160. return '<User %r>' % self.username
  161. class Post(db.Model):
  162. __tablename__ = 'posts'
  163. id = db.Column(db.Integer, primary_key=True)
  164. body = db.Column(db.Text)
  165. body_html = db.Column(db.Text)
  166. timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
  167. author_id = db.Column(db.Integer, db.ForeignKey('users.id'))
  168. @staticmethod
  169. def on_changed_body(target, value, oldvalue, initiator):
  170. allowed_tags = ['a', 'abbr', 'acronym', 'b', 'blockquote', 'code',
  171. 'em', 'i', 'li', 'ol', 'pre', 'strong', 'ul',
  172. 'h1', 'h2', 'h3', 'p']
  173. md = markdown(value, output_format='html')
  174. clean_md = bleach.clean(md, tags=allowed_tags, strip=True)
  175. target.body_html = bleach.linkify(clean_md)
  176. db.event.listen(Post.body, 'set', Post.on_changed_body)
  177. class AnonymousUser(AnonymousUserMixin):
  178. def can(self, perm):
  179. return False
  180. def is_administrator(self):
  181. return False
  182. login_manager.anonymous_user = AnonymousUser
  183. @login_manager.user_loader
  184. def load_user(user_id):
  185. return User.query.get(int(user_id))