Advertisement
Guest User

Untitled

a guest
Oct 7th, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. class User(Base):
  2. __tablename__ = "users"
  3. __table_args__ = {'mysql_engine': "InnoDB", 'mysql_charset': "utf8"}
  4.  
  5. id = Column(Integer, primary_key=True)
  6. username = Column(Unicode(50), unique=True, nullable=False)
  7. first_name = Column(Unicode(20), default=u"")
  8. last_name = Column(Unicode(20), default=u"")
  9. _password = Column("password", Unicode(100), nullable=False)
  10. enabled = Column(Boolean, nullable=False, default=True)
  11. is_staff = Column(Boolean, nullable=False, default=False)
  12. role_id = Column(
  13. Integer,
  14. ForeignKey("roles.id", ondelete="CASCADE"),
  15. nullable=False
  16. )
  17.  
  18. role = relationship(Role, backref="users")
  19. _role_slug = None
  20.  
  21. def has_role(self, *args):
  22. return bool(self.role_slug in args)
  23.  
  24. @property
  25. def name_and_role(self):
  26. return self.name + " - " + self.role.name
  27.  
  28. @property
  29. def name(self):
  30. return "%s %s" % (self.first_name, self.last_name)
  31.  
  32. @property
  33. def password(self):
  34. return self._password
  35.  
  36. @property
  37. def role_slug(self):
  38. if not self._role_slug:
  39. self._role_slug = self.role.name
  40. return self._role_slug
  41.  
  42. @password.setter
  43. def password(self, password):
  44. if not isinstance(password, (str, unicode, basestring)):
  45. raise Exception('Invalid type. Password must be a string.')
  46.  
  47. hashed_password = password
  48.  
  49. if isinstance(password, unicode):
  50. password_8bit = password.encode('UTF-8')
  51. else:
  52. password_8bit = password
  53.  
  54. salt = sha1()
  55. salt.update(os.urandom(60))
  56. hash = sha1()
  57. hash.update(password_8bit + salt.hexdigest())
  58. hashed_password = salt.hexdigest() + hash.hexdigest()
  59.  
  60. if not isinstance(hashed_password, unicode):
  61. hashed_password = hashed_password.decode('UTF-8')
  62.  
  63. self._password = hashed_password
  64.  
  65. def validate_password(self, password):
  66. hashed_pass = sha1()
  67. hashed_pass.update(password + self._password[:40])
  68. return self._password[40:] == hashed_pass.hexdigest()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement