models.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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. import logging
  10. from werkzeug.security import generate_password_hash, check_password_hash
  11. from flask import url_for
  12. from flask_login import UserMixin, AnonymousUserMixin
  13. from flaskbb.extensions import db, cache
  14. from flaskbb.exceptions import AuthenticationError
  15. from flaskbb.utils.helpers import time_utcnow
  16. from flaskbb.utils.settings import flaskbb_config
  17. from flaskbb.utils.database import CRUDMixin, UTCDateTime, make_comparable
  18. from flaskbb.forum.models import (Post, Topic, Forum, topictracker, TopicsRead,
  19. ForumsRead)
  20. from flaskbb.message.models import Conversation
  21. logger = logging.getLogger(__name__)
  22. groups_users = db.Table(
  23. 'groups_users',
  24. db.Column('user_id', db.Integer, db.ForeignKey('users.id'),
  25. nullable=False),
  26. db.Column('group_id', db.Integer, db.ForeignKey('groups.id'),
  27. nullable=False)
  28. )
  29. @make_comparable
  30. class Group(db.Model, CRUDMixin):
  31. __tablename__ = "groups"
  32. id = db.Column(db.Integer, primary_key=True)
  33. name = db.Column(db.String(255), unique=True, nullable=False)
  34. description = db.Column(db.Text, nullable=True)
  35. # Group types
  36. admin = db.Column(db.Boolean, default=False, nullable=False)
  37. super_mod = db.Column(db.Boolean, default=False, nullable=False)
  38. mod = db.Column(db.Boolean, default=False, nullable=False)
  39. guest = db.Column(db.Boolean, default=False, nullable=False)
  40. banned = db.Column(db.Boolean, default=False, nullable=False)
  41. # Moderator permissions (only available when the user a moderator)
  42. mod_edituser = db.Column(db.Boolean, default=False, nullable=False)
  43. mod_banuser = db.Column(db.Boolean, default=False, nullable=False)
  44. # User permissions
  45. editpost = db.Column(db.Boolean, default=True, nullable=False)
  46. deletepost = db.Column(db.Boolean, default=False, nullable=False)
  47. deletetopic = db.Column(db.Boolean, default=False, nullable=False)
  48. posttopic = db.Column(db.Boolean, default=True, nullable=False)
  49. postreply = db.Column(db.Boolean, default=True, nullable=False)
  50. viewhidden = db.Column(db.Boolean, default=False, nullable=False)
  51. makehidden = db.Column(db.Boolean, default=False, nullable=False)
  52. # Methods
  53. def __repr__(self):
  54. """Set to a unique key specific to the object in the database.
  55. Required for cache.memoize() to work across requests.
  56. """
  57. return "<{} {} {}>".format(self.__class__.__name__, self.id, self.name)
  58. @classmethod
  59. def selectable_groups_choices(cls):
  60. return Group.query.order_by(Group.name.asc()).with_entities(
  61. Group.id, Group.name
  62. ).all()
  63. @classmethod
  64. def get_guest_group(cls):
  65. return cls.query.filter(cls.guest == True).first()
  66. @classmethod
  67. def get_member_group(cls):
  68. """Returns the first member group."""
  69. # This feels ugly..
  70. return cls.query.filter(cls.admin == False, cls.super_mod == False,
  71. cls.mod == False, cls.guest == False,
  72. cls.banned == False).first()
  73. class User(db.Model, UserMixin, CRUDMixin):
  74. __tablename__ = "users"
  75. id = db.Column(db.Integer, primary_key=True)
  76. username = db.Column(db.String(200), unique=True, nullable=False)
  77. email = db.Column(db.String(200), unique=True, nullable=False)
  78. _password = db.Column('password', db.String(120), nullable=False)
  79. date_joined = db.Column(UTCDateTime(timezone=True), default=time_utcnow,
  80. nullable=False)
  81. lastseen = db.Column(UTCDateTime(timezone=True), default=time_utcnow,
  82. nullable=True)
  83. birthday = db.Column(db.DateTime, nullable=True)
  84. gender = db.Column(db.String(10), nullable=True)
  85. website = db.Column(db.String(200), nullable=True)
  86. location = db.Column(db.String(100), nullable=True)
  87. signature = db.Column(db.Text, nullable=True)
  88. avatar = db.Column(db.String(200), nullable=True)
  89. notes = db.Column(db.Text, nullable=True)
  90. last_failed_login = db.Column(UTCDateTime(timezone=True), nullable=True)
  91. login_attempts = db.Column(db.Integer, default=0, nullable=False)
  92. activated = db.Column(db.Boolean, default=False, nullable=False)
  93. theme = db.Column(db.String(15), nullable=True)
  94. language = db.Column(db.String(15), default="en", nullable=True)
  95. posts = db.relationship("Post", backref="user", lazy="dynamic", primaryjoin="User.id == Post.user_id")
  96. topics = db.relationship("Topic", backref="user", lazy="dynamic", primaryjoin="User.id == Topic.user_id")
  97. post_count = db.Column(db.Integer, default=0)
  98. primary_group_id = db.Column(db.Integer, db.ForeignKey('groups.id'),
  99. nullable=False)
  100. primary_group = db.relationship('Group', lazy="joined",
  101. backref="user_group", uselist=False,
  102. foreign_keys=[primary_group_id])
  103. secondary_groups = \
  104. db.relationship('Group',
  105. secondary=groups_users,
  106. primaryjoin=(groups_users.c.user_id == id),
  107. backref=db.backref('users', lazy='dynamic'),
  108. lazy='dynamic')
  109. tracked_topics = \
  110. db.relationship("Topic", secondary=topictracker,
  111. primaryjoin=(topictracker.c.user_id == id),
  112. backref=db.backref("topicstracked", lazy="dynamic"),
  113. lazy="dynamic")
  114. # Properties
  115. @property
  116. def is_active(self):
  117. """Returns the state of the account.
  118. If the ``ACTIVATE_ACCOUNT`` option has been disabled, it will always
  119. return ``True``. Is the option activated, it will, depending on the
  120. state of the account, either return ``True`` or ``False``.
  121. """
  122. if flaskbb_config["ACTIVATE_ACCOUNT"]:
  123. if self.activated:
  124. return True
  125. return False
  126. return True
  127. @property
  128. def last_post(self):
  129. """Returns the latest post from the user."""
  130. return Post.query.filter(Post.user_id == self.id).\
  131. order_by(Post.date_created.desc()).first()
  132. @property
  133. def url(self):
  134. """Returns the url for the user."""
  135. return url_for("user.profile", username=self.username)
  136. @property
  137. def permissions(self):
  138. """Returns the permissions for the user."""
  139. return self.get_permissions()
  140. @property
  141. def groups(self):
  142. """Returns the user groups."""
  143. return self.get_groups()
  144. @property
  145. def unread_messages(self):
  146. """Returns the unread messages for the user."""
  147. return self.get_unread_messages()
  148. @property
  149. def unread_count(self):
  150. """Returns the unread message count for the user."""
  151. return len(self.unread_messages)
  152. @property
  153. def days_registered(self):
  154. """Returns the amount of days the user is registered."""
  155. days_registered = (time_utcnow() - self.date_joined).days
  156. if not days_registered:
  157. return 1
  158. return days_registered
  159. @property
  160. def topic_count(self):
  161. """Returns the thread count."""
  162. return Topic.query.filter(Topic.user_id == self.id).count()
  163. @property
  164. def posts_per_day(self):
  165. """Returns the posts per day count."""
  166. return round((float(self.post_count) / float(self.days_registered)), 1)
  167. @property
  168. def topics_per_day(self):
  169. """Returns the topics per day count."""
  170. return round(
  171. (float(self.topic_count) / float(self.days_registered)), 1
  172. )
  173. # Methods
  174. def __repr__(self):
  175. """Set to a unique key specific to the object in the database.
  176. Required for cache.memoize() to work across requests.
  177. """
  178. return "<{} {}>".format(self.__class__.__name__, self.username)
  179. def _get_password(self):
  180. """Returns the hashed password."""
  181. return self._password
  182. def _set_password(self, password):
  183. """Generates a password hash for the provided password."""
  184. if not password:
  185. return
  186. self._password = generate_password_hash(password)
  187. # Hide password encryption by exposing password field only.
  188. password = db.synonym('_password',
  189. descriptor=property(_get_password,
  190. _set_password))
  191. def check_password(self, password):
  192. """Check passwords. If passwords match it returns true, else false."""
  193. if self.password is None:
  194. return False
  195. return check_password_hash(self.password, password)
  196. @classmethod
  197. def authenticate(cls, login, password):
  198. """A classmethod for authenticating users.
  199. It returns the user object if the user/password combination is ok.
  200. If the user has entered too often a wrong password, he will be locked
  201. out of his account for a specified time.
  202. :param login: This can be either a username or a email address.
  203. :param password: The password that is connected to username and email.
  204. """
  205. user = cls.query.filter(db.or_(User.username == login,
  206. User.email == login)).first()
  207. if user is not None:
  208. if user.check_password(password):
  209. # reset them after a successful login attempt
  210. user.login_attempts = 0
  211. user.save()
  212. return user
  213. # user exists, wrong password
  214. # never had a bad login before
  215. if user.login_attempts is None:
  216. user.login_attempts = 1
  217. else:
  218. user.login_attempts += 1
  219. user.last_failed_login = time_utcnow()
  220. user.save()
  221. # protection against account enumeration timing attacks
  222. check_password_hash("dummy password", password)
  223. raise AuthenticationError
  224. def recalculate(self):
  225. """Recalculates the post count from the user."""
  226. post_count = Post.query.filter_by(user_id=self.id).count()
  227. self.post_count = post_count
  228. self.save()
  229. return self
  230. def all_topics(self, page, viewer):
  231. """Returns a paginated result with all topics the user has created.
  232. :param page: The page which should be displayed.
  233. :param viewer: The user who is viewing this user. It will return a
  234. list with topics that the *viewer* has access to and
  235. thus it will not display all topics from
  236. the requested user.
  237. """
  238. group_ids = [g.id for g in viewer.groups]
  239. topics = Topic.query.\
  240. filter(Topic.user_id == self.id,
  241. Forum.id == Topic.forum_id,
  242. Forum.groups.any(Group.id.in_(group_ids))).\
  243. paginate(page, flaskbb_config['TOPICS_PER_PAGE'], False)
  244. return topics
  245. def all_posts(self, page, viewer):
  246. """Returns a paginated result with all posts the user has created.
  247. :param page: The page which should be displayed.
  248. :param viewer: The user who is viewing this user. It will return a
  249. list with posts that the *viewer* has access to and
  250. thus it will not display all posts from
  251. the requested user.
  252. """
  253. group_ids = [g.id for g in viewer.groups]
  254. posts = Post.query.\
  255. filter(Post.user_id == self.id,
  256. Post.topic_id == Topic.id,
  257. Topic.forum_id == Forum.id,
  258. Forum.groups.any(Group.id.in_(group_ids))).\
  259. paginate(page, flaskbb_config['TOPICS_PER_PAGE'], False)
  260. return posts
  261. def track_topic(self, topic):
  262. """Tracks the specified topic.
  263. :param topic: The topic which should be added to the topic tracker.
  264. """
  265. if not self.is_tracking_topic(topic):
  266. self.tracked_topics.append(topic)
  267. return self
  268. def untrack_topic(self, topic):
  269. """Untracks the specified topic.
  270. :param topic: The topic which should be removed from the
  271. topic tracker.
  272. """
  273. if self.is_tracking_topic(topic):
  274. self.tracked_topics.remove(topic)
  275. return self
  276. def is_tracking_topic(self, topic):
  277. """Checks if the user is already tracking this topic.
  278. :param topic: The topic which should be checked.
  279. """
  280. return self.tracked_topics.filter(
  281. topictracker.c.topic_id == topic.id).count() > 0
  282. def add_to_group(self, group):
  283. """Adds the user to the `group` if he isn't in it.
  284. :param group: The group which should be added to the user.
  285. """
  286. if not self.in_group(group):
  287. self.secondary_groups.append(group)
  288. return self
  289. def remove_from_group(self, group):
  290. """Removes the user from the `group` if he is in it.
  291. :param group: The group which should be removed from the user.
  292. """
  293. if self.in_group(group):
  294. self.secondary_groups.remove(group)
  295. return self
  296. def in_group(self, group):
  297. """Returns True if the user is in the specified group.
  298. :param group: The group which should be checked.
  299. """
  300. return self.secondary_groups.filter(
  301. groups_users.c.group_id == group.id).count() > 0
  302. @cache.memoize()
  303. def get_groups(self):
  304. """Returns all the groups the user is in."""
  305. return [self.primary_group] + list(self.secondary_groups)
  306. @cache.memoize()
  307. def get_permissions(self, exclude=None):
  308. """Returns a dictionary with all permissions the user has"""
  309. if exclude:
  310. exclude = set(exclude)
  311. else:
  312. exclude = set()
  313. exclude.update(['id', 'name', 'description'])
  314. perms = {}
  315. # Get the Guest group
  316. for group in self.groups:
  317. columns = set(group.__table__.columns.keys()) - set(exclude)
  318. for c in columns:
  319. perms[c] = getattr(group, c) or perms.get(c, False)
  320. return perms
  321. @cache.memoize()
  322. def get_unread_messages(self):
  323. """Returns all unread messages for the user."""
  324. unread_messages = Conversation.query.\
  325. filter(Conversation.unread, Conversation.user_id == self.id).all()
  326. return unread_messages
  327. def invalidate_cache(self, permissions=True, messages=True):
  328. """Invalidates this objects cached metadata.
  329. :param permissions_only: If set to ``True`` it will only invalidate
  330. the permissions cache. Otherwise it will
  331. also invalidate the user's unread message
  332. cache.
  333. """
  334. if messages:
  335. cache.delete_memoized(self.get_unread_messages, self)
  336. if permissions:
  337. cache.delete_memoized(self.get_permissions, self)
  338. cache.delete_memoized(self.get_groups, self)
  339. def ban(self):
  340. """Bans the user. Returns True upon success."""
  341. if not self.get_permissions()['banned']:
  342. banned_group = Group.query.filter(
  343. Group.banned == True
  344. ).first()
  345. self.primary_group = banned_group
  346. self.save()
  347. self.invalidate_cache()
  348. return True
  349. return False
  350. def unban(self):
  351. """Unbans the user. Returns True upon success."""
  352. if self.get_permissions()['banned']:
  353. member_group = Group.query.filter(
  354. Group.admin == False,
  355. Group.super_mod == False,
  356. Group.mod == False,
  357. Group.guest == False,
  358. Group.banned == False
  359. ).first()
  360. self.primary_group = member_group
  361. self.save()
  362. self.invalidate_cache()
  363. return True
  364. return False
  365. def save(self, groups=None):
  366. """Saves a user. If a list with groups is provided, it will add those
  367. to the secondary groups from the user.
  368. :param groups: A list with groups that should be added to the
  369. secondary groups from user.
  370. """
  371. if groups is not None:
  372. # TODO: Only remove/add groups that are selected
  373. secondary_groups = self.secondary_groups.all()
  374. for group in secondary_groups:
  375. self.remove_from_group(group)
  376. db.session.commit()
  377. for group in groups:
  378. # Do not add the primary group to the secondary groups
  379. if group == self.primary_group:
  380. continue
  381. self.add_to_group(group)
  382. self.invalidate_cache()
  383. db.session.add(self)
  384. db.session.commit()
  385. return self
  386. def delete(self):
  387. """Deletes the User."""
  388. # This isn't done automatically...
  389. Conversation.query.filter_by(user_id=self.id).delete()
  390. ForumsRead.query.filter_by(user_id=self.id).delete()
  391. TopicsRead.query.filter_by(user_id=self.id).delete()
  392. # This should actually be handeld by the dbms.. but dunno why it doesnt
  393. # work here
  394. from flaskbb.forum.models import Forum
  395. last_post_forums = Forum.query.\
  396. filter_by(last_post_user_id=self.id).all()
  397. for forum in last_post_forums:
  398. forum.last_post_user_id = None
  399. forum.save()
  400. db.session.delete(self)
  401. db.session.commit()
  402. return self
  403. class Guest(AnonymousUserMixin):
  404. @property
  405. def permissions(self):
  406. return self.get_permissions()
  407. @property
  408. def groups(self):
  409. return self.get_groups()
  410. @cache.memoize()
  411. def get_groups(self):
  412. return Group.query.filter(Group.guest == True).all()
  413. @cache.memoize()
  414. def get_permissions(self, exclude=None):
  415. """Returns a dictionary with all permissions the user has"""
  416. if exclude:
  417. exclude = set(exclude)
  418. else:
  419. exclude = set()
  420. exclude.update(['id', 'name', 'description'])
  421. perms = {}
  422. # Get the Guest group
  423. for group in self.groups:
  424. columns = set(group.__table__.columns.keys()) - set(exclude)
  425. for c in columns:
  426. perms[c] = getattr(group, c) or perms.get(c, False)
  427. return perms
  428. @classmethod
  429. def invalidate_cache(cls):
  430. """Invalidates this objects cached metadata."""
  431. cache.delete_memoized(cls.get_permissions, cls)