models.py 18 KB

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