70 lines
2.3 KiB
Python
70 lines
2.3 KiB
Python
import hashlib
|
|
import hmac
|
|
import secrets
|
|
from datetime import datetime, timedelta
|
|
|
|
from settings import db
|
|
|
|
|
|
def utcnow():
|
|
return datetime.utcnow()
|
|
|
|
|
|
class AccountToken(db.Model):
|
|
__tablename__ = "account_token"
|
|
|
|
PURPOSE_EMAIL_VERIFICATION = "email_verification"
|
|
PURPOSE_PASSWORD_RESET = "password_reset"
|
|
PURPOSES = {PURPOSE_EMAIL_VERIFICATION, PURPOSE_PASSWORD_RESET}
|
|
|
|
id = db.Column(db.Integer, primary_key=True)
|
|
user_id = db.Column(
|
|
db.Integer, db.ForeignKey("user.id"), nullable=False, index=True
|
|
)
|
|
purpose = db.Column(db.String(32), nullable=False, index=True)
|
|
token_hash = db.Column(db.String(64), nullable=False, unique=True)
|
|
created_at = db.Column(db.DateTime, nullable=False, default=utcnow)
|
|
expires_at = db.Column(db.DateTime, nullable=False, index=True)
|
|
used_at = db.Column(db.DateTime, nullable=True)
|
|
user = db.relationship("User")
|
|
|
|
@staticmethod
|
|
def hash_token(token, purpose):
|
|
return hashlib.sha256(f"{purpose}:{token}".encode()).hexdigest()
|
|
|
|
@classmethod
|
|
def issue(cls, user, purpose, lifetime):
|
|
if purpose not in cls.PURPOSES:
|
|
raise ValueError("Unsupported account token purpose")
|
|
cls.query.filter_by(user_id=user.id, purpose=purpose, used_at=None).update(
|
|
{"used_at": utcnow()}
|
|
)
|
|
raw_token = secrets.token_urlsafe(32)
|
|
token = cls(
|
|
user_id=user.id,
|
|
purpose=purpose,
|
|
token_hash=cls.hash_token(raw_token, purpose),
|
|
expires_at=utcnow() + lifetime,
|
|
)
|
|
db.session.add(token)
|
|
return token, raw_token
|
|
|
|
@classmethod
|
|
def find_valid(cls, raw_token, purpose):
|
|
if not isinstance(raw_token, str) or not raw_token or purpose not in cls.PURPOSES:
|
|
return None
|
|
candidate = cls.hash_token(raw_token, purpose)
|
|
token = cls.query.filter_by(token_hash=candidate, purpose=purpose).first()
|
|
if token is None or not hmac.compare_digest(token.token_hash, candidate):
|
|
return None
|
|
return token if token.is_valid else None
|
|
|
|
@property
|
|
def is_valid(self):
|
|
return self.used_at is None and self.expires_at > utcnow()
|
|
|
|
def consume(self):
|
|
if not self.is_valid:
|
|
raise ValueError("Token is invalid or expired")
|
|
self.used_at = utcnow()
|