models.py 17 KB

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