models.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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 datetime import datetime, timedelta
  11. from werkzeug.security import generate_password_hash, check_password_hash
  12. from flask import url_for
  13. from flask_login import UserMixin, AnonymousUserMixin
  14. from flaskbb._compat import max_integer
  15. from flaskbb.extensions import db, cache
  16. from flaskbb.exceptions import AuthenticationError, LoginAttemptsExceeded
  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, 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(db.DateTime, default=datetime.utcnow())
  68. lastseen = db.Column(db.DateTime, default=datetime.utcnow())
  69. birthday = db.Column(db.DateTime)
  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(db.DateTime)
  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 = (datetime.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. # check for the login attempts first
  195. login_timeout = datetime.utcnow() - timedelta(
  196. minutes=flaskbb_config["LOGIN_TIMEOUT"]
  197. )
  198. if user.login_attempts >= flaskbb_config["LOGIN_ATTEMPTS"] and \
  199. user.last_failed_login > login_timeout:
  200. raise LoginAttemptsExceeded
  201. if user.check_password(password):
  202. if user.login_attempts >= flaskbb_config["LOGIN_ATTEMPTS"]:
  203. # reset them after a successful login attempt
  204. user.login_attempts = 0
  205. user.save()
  206. return user
  207. # user exists, wrong password
  208. user.login_attempts += 1
  209. user.last_failed_login = datetime.utcnow()
  210. user.save()
  211. # protection against account enumeration timing attacks
  212. dummy_password = os.urandom(15).encode("base-64")
  213. check_password_hash(dummy_password, password)
  214. raise AuthenticationError
  215. def recalculate(self):
  216. """Recalculates the post count from the user."""
  217. post_count = Post.query.filter_by(user_id=self.id).count()
  218. self.post_count = post_count
  219. self.save()
  220. return self
  221. def all_topics(self, page):
  222. """Returns a paginated result with all topics the user has created."""
  223. return Topic.query.filter(Topic.user_id == self.id).\
  224. filter(Post.topic_id == Topic.id).\
  225. order_by(Post.id.desc()).\
  226. paginate(page, flaskbb_config['TOPICS_PER_PAGE'], False)
  227. def all_posts(self, page):
  228. """Returns a paginated result with all posts the user has created."""
  229. return Post.query.filter(Post.user_id == self.id).\
  230. paginate(page, flaskbb_config['TOPICS_PER_PAGE'], False)
  231. def track_topic(self, topic):
  232. """Tracks the specified topic.
  233. :param topic: The topic which should be added to the topic tracker.
  234. """
  235. if not self.is_tracking_topic(topic):
  236. self.tracked_topics.append(topic)
  237. return self
  238. def untrack_topic(self, topic):
  239. """Untracks the specified topic.
  240. :param topic: The topic which should be removed from the
  241. topic tracker.
  242. """
  243. if self.is_tracking_topic(topic):
  244. self.tracked_topics.remove(topic)
  245. return self
  246. def is_tracking_topic(self, topic):
  247. """Checks if the user is already tracking this topic.
  248. :param topic: The topic which should be checked.
  249. """
  250. return self.tracked_topics.filter(
  251. topictracker.c.topic_id == topic.id).count() > 0
  252. def add_to_group(self, group):
  253. """Adds the user to the `group` if he isn't in it.
  254. :param group: The group which should be added to the user.
  255. """
  256. if not self.in_group(group):
  257. self.secondary_groups.append(group)
  258. return self
  259. def remove_from_group(self, group):
  260. """Removes the user from the `group` if he is in it.
  261. :param group: The group which should be removed from the user.
  262. """
  263. if self.in_group(group):
  264. self.secondary_groups.remove(group)
  265. return self
  266. def in_group(self, group):
  267. """Returns True if the user is in the specified group.
  268. :param group: The group which should be checked.
  269. """
  270. return self.secondary_groups.filter(
  271. groups_users.c.group_id == group.id).count() > 0
  272. @cache.memoize(timeout=max_integer)
  273. def get_groups(self):
  274. """Returns all the groups the user is in."""
  275. return [self.primary_group] + list(self.secondary_groups)
  276. @cache.memoize(timeout=max_integer)
  277. def get_permissions(self, exclude=None):
  278. """Returns a dictionary with all permissions the user has"""
  279. if exclude:
  280. exclude = set(exclude)
  281. else:
  282. exclude = set()
  283. exclude.update(['id', 'name', 'description'])
  284. perms = {}
  285. # Get the Guest group
  286. for group in self.groups:
  287. columns = set(group.__table__.columns.keys()) - set(exclude)
  288. for c in columns:
  289. perms[c] = getattr(group, c) or perms.get(c, False)
  290. return perms
  291. @cache.memoize(timeout=max_integer)
  292. def get_unread_messages(self):
  293. """Returns all unread messages for the user."""
  294. unread_messages = Conversation.query.\
  295. filter(Conversation.unread, Conversation.user_id == self.id).all()
  296. return unread_messages
  297. def invalidate_cache(self, permissions=True, messages=True):
  298. """Invalidates this objects cached metadata.
  299. :param permissions_only: If set to ``True`` it will only invalidate
  300. the permissions cache. Otherwise it will
  301. also invalidate the user's unread message
  302. cache.
  303. """
  304. if messages:
  305. cache.delete_memoized(self.get_unread_messages, self)
  306. if permissions:
  307. cache.delete_memoized(self.get_permissions, self)
  308. cache.delete_memoized(self.get_groups, self)
  309. def ban(self):
  310. """Bans the user. Returns True upon success."""
  311. if not self.get_permissions()['banned']:
  312. banned_group = Group.query.filter(
  313. Group.banned == True
  314. ).first()
  315. self.primary_group_id = banned_group.id
  316. self.save()
  317. self.invalidate_cache()
  318. return True
  319. return False
  320. def unban(self):
  321. """Unbans the user. Returns True upon success."""
  322. if self.get_permissions()['banned']:
  323. member_group = Group.query.filter(
  324. Group.admin == False,
  325. Group.super_mod == False,
  326. Group.mod == False,
  327. Group.guest == False,
  328. Group.banned == False
  329. ).first()
  330. self.primary_group_id = member_group.id
  331. self.save()
  332. self.invalidate_cache()
  333. return True
  334. return False
  335. def save(self, groups=None):
  336. """Saves a user. If a list with groups is provided, it will add those
  337. to the secondary groups from the user.
  338. :param groups: A list with groups that should be added to the
  339. secondary groups from user.
  340. """
  341. if groups is not None:
  342. # TODO: Only remove/add groups that are selected
  343. secondary_groups = self.secondary_groups.all()
  344. for group in secondary_groups:
  345. self.remove_from_group(group)
  346. db.session.commit()
  347. for group in groups:
  348. # Do not add the primary group to the secondary groups
  349. if group.id == self.primary_group_id:
  350. continue
  351. self.add_to_group(group)
  352. self.invalidate_cache()
  353. db.session.add(self)
  354. db.session.commit()
  355. return self
  356. def delete(self):
  357. """Deletes the User."""
  358. # This isn't done automatically...
  359. Conversation.query.filter_by(user_id=self.id).delete()
  360. ForumsRead.query.filter_by(user_id=self.id).delete()
  361. TopicsRead.query.filter_by(user_id=self.id).delete()
  362. # This should actually be handeld by the dbms.. but dunno why it doesnt
  363. # work here
  364. from flaskbb.forum.models import Forum
  365. last_post_forums = Forum.query.\
  366. filter_by(last_post_user_id=self.id).all()
  367. for forum in last_post_forums:
  368. forum.last_post_user_id = None
  369. forum.save()
  370. db.session.delete(self)
  371. db.session.commit()
  372. return self
  373. class Guest(AnonymousUserMixin):
  374. @property
  375. def permissions(self):
  376. return self.get_permissions()
  377. @property
  378. def groups(self):
  379. return self.get_groups()
  380. @cache.memoize(timeout=max_integer)
  381. def get_groups(self):
  382. return Group.query.filter(Group.guest == True).all()
  383. @cache.memoize(timeout=max_integer)
  384. def get_permissions(self, exclude=None):
  385. """Returns a dictionary with all permissions the user has"""
  386. if exclude:
  387. exclude = set(exclude)
  388. else:
  389. exclude = set()
  390. exclude.update(['id', 'name', 'description'])
  391. perms = {}
  392. # Get the Guest group
  393. for group in self.groups:
  394. columns = set(group.__table__.columns.keys()) - set(exclude)
  395. for c in columns:
  396. perms[c] = getattr(group, c) or perms.get(c, False)
  397. return perms
  398. @classmethod
  399. def invalidate_cache(cls):
  400. """Invalidates this objects cached metadata."""
  401. cache.delete_memoized(cls.get_permissions, cls)