models.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. # -*- coding: utf-8 -*-
  2. """
  3. flaskbb.user.models
  4. ~~~~~~~~~~~~~~~~~~~~
  5. This module provides the models for the user.
  6. :copyright: (c) 2014 by the FlaskBB Team.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. from datetime import datetime
  10. from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
  11. from itsdangerous import SignatureExpired
  12. from werkzeug.security import generate_password_hash, check_password_hash
  13. from flask import current_app, url_for
  14. from flask_login import UserMixin, AnonymousUserMixin
  15. from flaskbb._compat import max_integer
  16. from flaskbb.extensions import db, cache
  17. from flaskbb.utils.settings import flaskbb_config
  18. from flaskbb.utils.database import CRUDMixin
  19. from flaskbb.forum.models import (Post, Topic, topictracker, TopicsRead,
  20. ForumsRead)
  21. from flaskbb.message.models import Conversation
  22. groups_users = db.Table(
  23. 'groups_users',
  24. db.Column('user_id', db.Integer(), db.ForeignKey('users.id')),
  25. db.Column('group_id', db.Integer(), db.ForeignKey('groups.id')))
  26. class Group(db.Model, CRUDMixin):
  27. __tablename__ = "groups"
  28. id = db.Column(db.Integer, primary_key=True)
  29. name = db.Column(db.String(255), unique=True, nullable=False)
  30. description = db.Column(db.Text)
  31. # Group types
  32. admin = db.Column(db.Boolean, default=False, nullable=False)
  33. super_mod = db.Column(db.Boolean, default=False, nullable=False)
  34. mod = db.Column(db.Boolean, default=False, nullable=False)
  35. guest = db.Column(db.Boolean, default=False, nullable=False)
  36. banned = db.Column(db.Boolean, default=False, nullable=False)
  37. # Moderator permissions (only available when the user a moderator)
  38. mod_edituser = db.Column(db.Boolean, default=False, nullable=False)
  39. mod_banuser = db.Column(db.Boolean, default=False, nullable=False)
  40. # User permissions
  41. editpost = db.Column(db.Boolean, default=True, nullable=False)
  42. deletepost = db.Column(db.Boolean, default=False, nullable=False)
  43. deletetopic = db.Column(db.Boolean, default=False, nullable=False)
  44. posttopic = db.Column(db.Boolean, default=True, nullable=False)
  45. postreply = db.Column(db.Boolean, default=True, nullable=False)
  46. # Methods
  47. def __repr__(self):
  48. """Set to a unique key specific to the object in the database.
  49. Required for cache.memoize() to work across requests.
  50. """
  51. return "<{} {}>".format(self.__class__.__name__, self.id)
  52. @classmethod
  53. def selectable_groups_choices(cls):
  54. return Group.query.order_by(Group.name.asc()).with_entities(
  55. Group.id, Group.name
  56. ).all()
  57. class User(db.Model, UserMixin, CRUDMixin):
  58. __tablename__ = "users"
  59. __searchable__ = ['username', 'email']
  60. id = db.Column(db.Integer, primary_key=True)
  61. username = db.Column(db.String(200), unique=True, nullable=False)
  62. email = db.Column(db.String(200), unique=True, nullable=False)
  63. _password = db.Column('password', db.String(120), nullable=False)
  64. date_joined = db.Column(db.DateTime, default=datetime.utcnow())
  65. lastseen = db.Column(db.DateTime, default=datetime.utcnow())
  66. birthday = db.Column(db.DateTime)
  67. gender = db.Column(db.String(10))
  68. website = db.Column(db.String(200))
  69. location = db.Column(db.String(100))
  70. signature = db.Column(db.Text)
  71. avatar = db.Column(db.String(200))
  72. notes = db.Column(db.Text)
  73. theme = db.Column(db.String(15))
  74. language = db.Column(db.String(15), default="en")
  75. posts = db.relationship("Post", backref="user", lazy="dynamic")
  76. topics = db.relationship("Topic", backref="user", lazy="dynamic")
  77. post_count = db.Column(db.Integer, default=0)
  78. primary_group_id = db.Column(db.Integer, db.ForeignKey('groups.id'),
  79. nullable=False)
  80. primary_group = db.relationship('Group', lazy="joined",
  81. backref="user_group", uselist=False,
  82. foreign_keys=[primary_group_id])
  83. secondary_groups = \
  84. db.relationship('Group',
  85. secondary=groups_users,
  86. primaryjoin=(groups_users.c.user_id == id),
  87. backref=db.backref('users', lazy='dynamic'),
  88. lazy='dynamic')
  89. tracked_topics = \
  90. db.relationship("Topic", secondary=topictracker,
  91. primaryjoin=(topictracker.c.user_id == id),
  92. backref=db.backref("topicstracked", lazy="dynamic"),
  93. lazy="dynamic")
  94. # Properties
  95. @property
  96. def last_post(self):
  97. """Returns the latest post from the user"""
  98. return Post.query.filter(Post.user_id == self.id).\
  99. order_by(Post.date_created.desc()).first()
  100. @property
  101. def url(self):
  102. """Returns the url for the user"""
  103. return url_for("user.profile", username=self.username)
  104. @property
  105. def permissions(self):
  106. """Returns the permissions for the user"""
  107. return self.get_permissions()
  108. @property
  109. def groups(self):
  110. """Returns user groups"""
  111. return self.get_groups()
  112. @property
  113. def days_registered(self):
  114. """Returns the amount of days the user is registered."""
  115. days_registered = (datetime.utcnow() - self.date_joined).days
  116. if not days_registered:
  117. return 1
  118. return days_registered
  119. @property
  120. def topic_count(self):
  121. """Returns the thread count"""
  122. return Topic.query.filter(Topic.user_id == self.id).count()
  123. @property
  124. def posts_per_day(self):
  125. """Returns the posts per day count"""
  126. return round((float(self.post_count) / float(self.days_registered)), 1)
  127. @property
  128. def topics_per_day(self):
  129. """Returns the topics per day count"""
  130. return round((float(self.topic_count) / float(self.days_registered)), 1)
  131. # Methods
  132. def __repr__(self):
  133. """Set to a unique key specific to the object in the database.
  134. Required for cache.memoize() to work across requests.
  135. """
  136. return "<{} {}>".format(self.__class__.__name__, self.username)
  137. def _get_password(self):
  138. """Returns the hashed password"""
  139. return self._password
  140. def _set_password(self, password):
  141. """Generates a password hash for the provided password"""
  142. self._password = generate_password_hash(password)
  143. # Hide password encryption by exposing password field only.
  144. password = db.synonym('_password',
  145. descriptor=property(_get_password,
  146. _set_password))
  147. def check_password(self, password):
  148. """Check passwords. If passwords match it returns true, else false"""
  149. if self.password is None:
  150. return False
  151. return check_password_hash(self.password, password)
  152. @classmethod
  153. def authenticate(cls, login, password):
  154. """A classmethod for authenticating users
  155. It returns true if the user exists and has entered a correct password
  156. :param login: This can be either a username or a email address.
  157. :param password: The password that is connected to username and email.
  158. """
  159. user = cls.query.filter(db.or_(User.username == login,
  160. User.email == login)).first()
  161. if user:
  162. authenticated = user.check_password(password)
  163. else:
  164. authenticated = False
  165. return user, authenticated
  166. def _make_token(self, data, timeout):
  167. s = Serializer(current_app.config['SECRET_KEY'], timeout)
  168. return s.dumps(data)
  169. def _verify_token(self, token):
  170. s = Serializer(current_app.config['SECRET_KEY'])
  171. data = None
  172. expired, invalid = False, False
  173. try:
  174. data = s.loads(token)
  175. except SignatureExpired:
  176. expired = True
  177. except Exception:
  178. invalid = True
  179. return expired, invalid, data
  180. def make_reset_token(self, expiration=3600):
  181. """Creates a reset token. The duration can be configured through the
  182. expiration parameter.
  183. :param expiration: The time in seconds how long the token is valid.
  184. """
  185. return self._make_token({'id': self.id, 'op': 'reset'}, expiration)
  186. def verify_reset_token(self, token):
  187. """Verifies a reset token. It returns three boolean values based on
  188. the state of the token (expired, invalid, data)
  189. :param token: The reset token that should be checked.
  190. """
  191. expired, invalid, data = self._verify_token(token)
  192. if data and data.get('id') == self.id and data.get('op') == 'reset':
  193. data = True
  194. else:
  195. data = False
  196. return expired, invalid, data
  197. def recalculate(self):
  198. """Recalculates the post count from the user."""
  199. post_count = Post.query.filter_by(user_id=self.id).count()
  200. self.post_count = post_count
  201. self.save()
  202. return self
  203. def all_topics(self, page):
  204. """Returns a paginated result with all topics the user has created."""
  205. return Topic.query.filter(Topic.user_id == self.id).\
  206. filter(Post.topic_id == Topic.id).\
  207. order_by(Post.id.desc()).\
  208. paginate(page, flaskbb_config['TOPICS_PER_PAGE'], False)
  209. def all_posts(self, page):
  210. """Returns a paginated result with all posts the user has created."""
  211. return Post.query.filter(Post.user_id == self.id).\
  212. paginate(page, flaskbb_config['TOPICS_PER_PAGE'], False)
  213. def track_topic(self, topic):
  214. """Tracks the specified topic
  215. :param topic: The topic which should be added to the topic tracker.
  216. """
  217. if not self.is_tracking_topic(topic):
  218. self.tracked_topics.append(topic)
  219. return self
  220. def untrack_topic(self, topic):
  221. """Untracks the specified topic
  222. :param topic: The topic which should be removed from the
  223. topic tracker.
  224. """
  225. if self.is_tracking_topic(topic):
  226. self.tracked_topics.remove(topic)
  227. return self
  228. def is_tracking_topic(self, topic):
  229. """Checks if the user is already tracking this topic
  230. :param topic: The topic which should be checked.
  231. """
  232. return self.tracked_topics.filter(
  233. topictracker.c.topic_id == topic.id).count() > 0
  234. def add_to_group(self, group):
  235. """Adds the user to the `group` if he isn't in it.
  236. :param group: The group which should be added to the user.
  237. """
  238. if not self.in_group(group):
  239. self.secondary_groups.append(group)
  240. return self
  241. def remove_from_group(self, group):
  242. """Removes the user from the `group` if he is in it.
  243. :param group: The group which should be removed from the user.
  244. """
  245. if self.in_group(group):
  246. self.secondary_groups.remove(group)
  247. return self
  248. def in_group(self, group):
  249. """Returns True if the user is in the specified group
  250. :param group: The group which should be checked.
  251. """
  252. return self.secondary_groups.filter(
  253. groups_users.c.group_id == group.id).count() > 0
  254. @cache.memoize(timeout=max_integer)
  255. def get_groups(self):
  256. """Returns all the groups the user is in."""
  257. return [self.primary_group] + list(self.secondary_groups)
  258. @cache.memoize(timeout=max_integer)
  259. def get_permissions(self, exclude=None):
  260. """Returns a dictionary with all permissions the user has"""
  261. if exclude:
  262. exclude = set(exclude)
  263. else:
  264. exclude = set()
  265. exclude.update(['id', 'name', 'description'])
  266. perms = {}
  267. # Get the Guest group
  268. for group in self.groups:
  269. columns = set(group.__table__.columns.keys()) - set(exclude)
  270. for c in columns:
  271. perms[c] = getattr(group, c)
  272. return perms
  273. def invalidate_cache(self):
  274. """Invalidates this objects cached metadata."""
  275. cache.delete_memoized(self.get_permissions, self)
  276. cache.delete_memoized(self.get_groups, self)
  277. def ban(self):
  278. """Bans the user. Returns True upon success."""
  279. if not self.get_permissions()['banned']:
  280. banned_group = Group.query.filter(
  281. Group.banned == True
  282. ).first()
  283. self.primary_group_id = banned_group.id
  284. self.save()
  285. self.invalidate_cache()
  286. return True
  287. return False
  288. def unban(self):
  289. """Unbans the user. Returns True upon success."""
  290. if self.get_permissions()['banned']:
  291. member_group = Group.query.filter(
  292. Group.admin == False,
  293. Group.super_mod == False,
  294. Group.mod == False,
  295. Group.guest == False,
  296. Group.banned == False
  297. ).first()
  298. self.primary_group_id = member_group.id
  299. self.save()
  300. self.invalidate_cache()
  301. return True
  302. return False
  303. def save(self, groups=None):
  304. """Saves a user. If a list with groups is provided, it will add those
  305. to the secondary groups from the user.
  306. :param groups: A list with groups that should be added to the
  307. secondary groups from user.
  308. """
  309. if groups is not None:
  310. # TODO: Only remove/add groups that are selected
  311. secondary_groups = self.secondary_groups.all()
  312. for group in secondary_groups:
  313. self.remove_from_group(group)
  314. db.session.commit()
  315. for group in groups:
  316. # Do not add the primary group to the secondary groups
  317. if group.id == self.primary_group_id:
  318. continue
  319. self.add_to_group(group)
  320. self.invalidate_cache()
  321. db.session.add(self)
  322. db.session.commit()
  323. return self
  324. def delete(self):
  325. """Deletes the User."""
  326. # This isn't done automatically...
  327. Conversation.query.filter_by(user_id=self.id).delete()
  328. ForumsRead.query.filter_by(user_id=self.id).delete()
  329. TopicsRead.query.filter_by(user_id=self.id).delete()
  330. # This should actually be handeld by the dbms.. but dunno why it doesnt
  331. # work here
  332. from flaskbb.forum.models import Forum
  333. last_post_forums = Forum.query.\
  334. filter_by(last_post_user_id=self.id).all()
  335. for forum in last_post_forums:
  336. forum.last_post_user_id = None
  337. forum.save()
  338. db.session.delete(self)
  339. db.session.commit()
  340. return self
  341. class Guest(AnonymousUserMixin):
  342. @property
  343. def permissions(self):
  344. return self.get_permissions()
  345. @property
  346. def groups(self):
  347. return self.get_groups()
  348. @cache.memoize(timeout=max_integer)
  349. def get_groups(self):
  350. return Group.query.filter(Group.guest == True).all()
  351. @cache.memoize(timeout=max_integer)
  352. def get_permissions(self, exclude=None):
  353. """Returns a dictionary with all permissions the user has"""
  354. if exclude:
  355. exclude = set(exclude)
  356. else:
  357. exclude = set()
  358. exclude.update(['id', 'name', 'description'])
  359. perms = {}
  360. # Get the Guest group
  361. for group in self.groups:
  362. columns = set(group.__table__.columns.keys()) - set(exclude)
  363. for c in columns:
  364. perms[c] = getattr(group, c)
  365. return perms
  366. @classmethod
  367. def invalidate_cache(cls):
  368. """Invalidates this objects cached metadata."""
  369. cache.delete_memoized(cls.get_permissions, cls)