models.py 16 KB

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