Advertisement
Guest User

Untitled

a guest
Aug 27th, 2016
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. ## User-Model
  2. class User(UserMixin, SurrogatePK, Model):
  3. """A user of the app."""
  4.  
  5. __tablename__ = 'users'
  6. username = Column(db.String(80), unique=True, nullable=False)
  7. email = Column(db.String(80), unique=True, nullable=False)
  8. #: The hashed password
  9. password = Column(db.String(128), nullable=True)
  10. created_at = Column(db.DateTime, nullable=False,
  11. default=datetime.datetime.utcnow)
  12. first_name = Column(db.String(30), nullable=True)
  13. last_name = Column(db.String(30), nullable=True)
  14. active = Column(db.Boolean(), default=False)
  15. is_admin = Column(db.Boolean(), default=False)
  16.  
  17. def __init__(self, username="", email="", password=None, **kwargs):
  18. """Create instance."""
  19. db.Model.__init__(self, username=username, email=email, **kwargs)
  20. if password:
  21. self.set_password(password)
  22. else:
  23. self.password = None
  24.  
  25. def __str__(self):
  26. """String representation of the user. Shows the users email address."""
  27. return self.email
  28.  
  29. def set_password(self, password):
  30. """Set password"""
  31. self.password = bcrypt.generate_password_hash(password)
  32.  
  33. def check_password(self, value):
  34. """Check password."""
  35. return bcrypt.check_password_hash(self.password, value)
  36.  
  37. def get_id(self):
  38. """Return the email address to satisfy Flask-Login's requirements"""
  39. return self.id
  40.  
  41. @property
  42. def full_name(self):
  43. """Full user name."""
  44. return "{0} {1}".format(self.first_name, self.last_name)
  45.  
  46. @property
  47. def is_active(self):
  48. """Active or non active user (required by flask-login)"""
  49. return self.active
  50.  
  51. @property
  52. def is_authenticated(self):
  53. """Return True if the user is authenticated."""
  54. if isinstance(self, AnonymousUserMixin):
  55. if isinstance(self, AnonymousUserMixin):
  56. return False
  57. else:
  58. return True
  59.  
  60. @property
  61. def is_anonymous(self):
  62. """False, as anonymous users aren't supported."""
  63. return False
  64.  
  65.  
  66. ## Flask-Admin UserView
  67. class UserView(MyModelView):
  68. """Flask user model view."""
  69. create_modal = True
  70. edit_modal = True
  71.  
  72. def on_model_change(self, form, User, is_created):
  73. if form.password.data is not None:
  74. User.set_password(form.password.data)
  75. else:
  76. del form.password
  77.  
  78. def on_form_prefill(self, form, id):
  79. form.password.data = ''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement