models.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. from __future__ import print_function
  2. from flask_security import UserMixin, RoleMixin
  3. from flask_security.utils import encrypt_password
  4. from project import db
  5. roles_users = db.Table('roles_users',
  6. db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
  7. db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))
  8. class Role(RoleMixin, db.Model):
  9. """Based on Flask-Security quickstart Role"""
  10. id = db.Column(db.Integer(), primary_key=True)
  11. name = db.Column(db.String(255), unique=True)
  12. description = db.Column(db.String(255), default='')
  13. @classmethod
  14. def createrole(cls, session, name, description=None):
  15. """Creates a new role instance."""
  16. o = cls(
  17. name=name,
  18. description=description
  19. )
  20. session.add(o)
  21. return o
  22. def __repr__(self):
  23. return u"{0} ({1})".format(self.name, self.description or 'Role')
  24. class User(UserMixin, db.Model):
  25. """Based on Flask-Security quickstart User"""
  26. id = db.Column(db.Integer, primary_key=True)
  27. email = db.Column(db.String(255), unique=True)
  28. password = db.Column(db.String(255), default='')
  29. roles = db.relationship('Role', secondary=roles_users,
  30. backref=db.backref('users', lazy='dynamic'))
  31. def set_password(self, session, password):
  32. """Encrypts a plain-text user password."""
  33. self.password = encrypt_password(password)
  34. session.add(self)
  35. @classmethod
  36. def createuser(cls, session, email, password, roles=None):
  37. """Creates a new user instance."""
  38. o = cls(
  39. email=email,
  40. password=encrypt_password(password),
  41. roles=roles,
  42. )
  43. session.add(o)
  44. return o
  45. def __repr__(self):
  46. return self.email
  47. @property
  48. def active(self):
  49. return True
  50. @property
  51. def has_admin_privs(self):
  52. """Determines if this user has admin privileges."""
  53. return self.active and self.has_role('admin')