models.py 16 KB

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