2019-07-08 11:55:56 +00:00
|
|
|
from flask import current_app
|
2019-07-05 12:47:35 +00:00
|
|
|
from flask_login import UserMixin
|
2019-07-08 11:55:56 +00:00
|
|
|
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
|
2019-07-05 12:47:35 +00:00
|
|
|
from werkzeug.security import generate_password_hash, check_password_hash
|
|
|
|
from . import db
|
|
|
|
from . import login_manager
|
|
|
|
|
|
|
|
|
|
|
|
class Role(db.Model):
|
|
|
|
__tablename__ = 'roles'
|
|
|
|
id = db.Column(db.Integer, primary_key=True)
|
|
|
|
name = db.Column(db.String(64), unique=True)
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return '<Role %r>' % self.name
|
|
|
|
|
|
|
|
|
|
|
|
class User(UserMixin, db.Model):
|
|
|
|
__tablename__ = 'users'
|
|
|
|
id = db.Column(db.Integer, primary_key=True)
|
|
|
|
email = db.Column(db.String(64), unique=True, index=True)
|
|
|
|
username = db.Column(db.String(64), unique=True, index=True)
|
|
|
|
password_hash = db.Column(db.String(128))
|
|
|
|
role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
|
2019-07-08 13:59:15 +00:00
|
|
|
confirmed = db.Column(db.Boolean, default=False)
|
2019-07-05 12:47:35 +00:00
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return '<User %r>' % self.username
|
|
|
|
|
2019-07-08 13:59:15 +00:00
|
|
|
def generate_confirmation_token(self, expiration=3600):
|
|
|
|
s = Serializer(current_app.config['SECRET_KEY'], expiration)
|
|
|
|
return s.dumps({'confirm': self.id}).decode('utf-8')
|
2019-07-05 12:47:35 +00:00
|
|
|
|
2019-07-08 11:55:56 +00:00
|
|
|
def generate_reset_token(self, expiration=3600):
|
|
|
|
s = Serializer(current_app.config['SECRET_KEY'], expiration)
|
|
|
|
return s.dumps({'reset': self.id}).decode('utf-8')
|
|
|
|
|
2019-07-08 13:59:15 +00:00
|
|
|
def confirm(self, token):
|
|
|
|
s = Serializer(current_app.config['SECRET_KEY'])
|
|
|
|
try:
|
|
|
|
data = s.loads(token.encode('utf-8'))
|
|
|
|
except:
|
|
|
|
return False
|
|
|
|
if data.get('confirm') != self.id:
|
|
|
|
return False
|
|
|
|
self.confirmed = True
|
|
|
|
db.session.add(self)
|
|
|
|
return True
|
|
|
|
|
2019-07-05 12:47:35 +00:00
|
|
|
@property
|
|
|
|
def password(self):
|
|
|
|
raise AttributeError('password is not a readable attribute')
|
|
|
|
|
|
|
|
@password.setter
|
|
|
|
def password(self, password):
|
|
|
|
self.password_hash = generate_password_hash(password)
|
|
|
|
|
|
|
|
def verify_password(self, password):
|
|
|
|
return check_password_hash(self.password_hash, password)
|
|
|
|
|
|
|
|
|
|
|
|
@login_manager.user_loader
|
|
|
|
def load_user(user_id):
|
|
|
|
return User.query.get(int(user_id))
|