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