user.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. from sqlalchemy import Column, Integer, String
  2. from werkzeug.security import generate_password_hash, check_password_hash
  3. from app.libs.error_code import AuthFailed
  4. from app.models.base import Base, db
  5. class User(Base):
  6. id = Column(Integer, primary_key=True)
  7. email = Column(String(24), unique=True, nullable=False)
  8. nickname = Column(String(24), unique=True)
  9. _password = Column('password', String(225))
  10. def keys(self):
  11. return ['id', 'email', 'nickname']
  12. @property
  13. def password(self):
  14. return self._password
  15. @password.setter
  16. def password(self, raw):
  17. self._password = generate_password_hash(raw)
  18. @staticmethod
  19. def register_by_email(nickname, account, secret):
  20. with db.auto_commit():
  21. user = User()
  22. user.nickname = nickname
  23. user.email = account
  24. user.password = secret
  25. db.session.add(user)
  26. @staticmethod
  27. def verify(email, password):
  28. user = User.query.filter_by(email=email).first_or_404()
  29. if not user.check_password(password):
  30. raise AuthFailed()
  31. return {'uid': user.id}
  32. def check_password(self, raw):
  33. if not self._password:
  34. return False
  35. return check_password_hash(self._password, raw)
  36. # def _set_fields(self):
  37. # # self._exclude = ['_password']
  38. # self._fields = ['_password', 'nickname']