# Path: daimaduan/models/base.py
# class User(BaseDocument):
#     username = db.StringField(required=True)
#     email = db.StringField(required=True)
#     password = db.StringField()
#     salt = db.StringField()
#     is_email_confirmed = db.BooleanField(default=False)
#     email_confirmed_on = db.DateTimeField(default=None)
#     number = db.IntField(default=0, unique=True)
#     description = db.StringField(default=u"这个家伙很懒, TA什么都没写...")
# 
#     oauths = db.ListField(db.ReferenceField(UserOauth))
# 
#     likes = db.ListField(db.ReferenceField('Paste'))
#     followings = db.ListField(db.ReferenceField('User'))
# 
#     @property
#     def pastes(self):
#         return Paste.objects(user=self)
# 
#     @property
#     def pastes_count(self):
#         return len(self.pastes)
# 
#     @property
#     def comments_count(self):
#         return len(Comment.objects(user=self))
# 
#     @property
#     def private_pastes_count(self):
#         return len(self.pastes(is_private=True))
# 
#     @property
#     def public_pastes_count(self):
#         return len(self.pastes) - len(self.pastes(is_private=True))
# 
#     @property
#     def public_bookmarks(self):
#         return Bookmark.objects(user=self, is_private=False)
# 
#     @property
#     def public_bookmarks_count(self):
#         return Bookmark.objects(user=self, is_private=False).count()
# 
#     @property
#     def unread_messages_count(self):
#         return Message.objects(user=self, is_read=False).count()
# 
#     def save(self, *args, **kwargs):
#         if not self.salt:
#             self.salt = hashlib.sha1(str(time.time())).hexdigest()
#             self.password = self.generate_password(self.password)
#             number = User.objects().count() + 1
#             while(User.objects(number=number).first()):
#                 number += 1
#             self.number = number
#         super(User, self).save(*args, **kwargs)
# 
#     def owns_record(self, record):
#         return record.user == self
# 
#     def generate_password(self, string):
#         return hashlib.sha1('%s%s' % (string, self.salt)).hexdigest()
# 
#     def check_login(self, password):
#         return self.generate_password(password) == self.password
# 
#     @classmethod
#     def find_by_oauth(cls, provider, openid):
#         """Find user that has oauth info with given provider and openid"""
#         oauth = UserOauth.objects(provider=provider, openid=openid).first()
# 
#         if oauth and oauth.user:
#             return oauth.user
# 
#     def is_following(self, user):
#         return user in self.followings
# 
#     @property
#     def followers(self):
#         return User.objects(followings=self)
# 
# Path: daimaduan/tasks/celery.py
# @celery.task
# def send_email(config, user_email, subject, content):
#     envelope = email(sender=SENDER,
#                      receivers=[user_email],
#                      subject=subject,
#                      content=content)
# 
#     postman = Postman(host=config['host'],
#                       port=int(config['port']),
#                       middlewares=[TLS(force=True),
#                                    Auth(username=config['username'], password=config['password'])])
# 
#     postman.send(envelope)


from itsdangerous import URLSafeTimedSerializer
from daimaduan.models.base import User
from daimaduan.tasks.celery import send_email
                port=config['EMAIL']['port'],
                username=config['EMAIL']['username'],
                password=config['EMAIL']['password'])


def generate_confirmation_token(config, email):
    """generate confirmation token using user's email via itsdangerous"""
    serializer = URLSafeTimedSerializer(config['SECRET_KEY'])
    return serializer.dumps(email, salt=config['EMAIL']['salt'])


def validate_token(config, token, expire_time=3600):
    """from token and expire_time to confirm user's email"""
    serializer = URLSafeTimedSerializer(config['SECRET_KEY'])
    try:
        confirmed_email = serializer.loads(token, max_age=expire_time, salt=config['EMAIL']['salt'])
    except Exception:
        return False
    return confirmed_email


def send_confirm_email(config, user_email):
    token = generate_confirmation_token(config, user_email)
    user = User.objects(email=user_email).first()
    content = CONFIRMATION_CONTENT % (user.username, config['DOMAIN'], token, config['DOMAIN'], token)
    send_email.delay(get_email_config(config), user_email, CONFIRMATION_SUBJECT, content)


def send_reset_password_email(config, user_email):
    token = generate_confirmation_token(config, user_email)

# Path: daimaduan/models/base.py
# class User(BaseDocument):
#     username = db.StringField(required=True)
#     email = db.StringField(required=True)
#     password = db.StringField()
#     salt = db.StringField()
#     is_email_confirmed = db.BooleanField(default=False)
#     email_confirmed_on = db.DateTimeField(default=None)
#     number = db.IntField(default=0, unique=True)
#     description = db.StringField(default=u"这个家伙很懒, TA什么都没写...")
# 
#     oauths = db.ListField(db.ReferenceField(UserOauth))
# 
#     likes = db.ListField(db.ReferenceField('Paste'))
#     followings = db.ListField(db.ReferenceField('User'))
# 
#     @property
#     def pastes(self):
#         return Paste.objects(user=self)
# 
#     @property
#     def pastes_count(self):
#         return len(self.pastes)
# 
#     @property
#     def comments_count(self):
#         return len(Comment.objects(user=self))
# 
#     @property
#     def private_pastes_count(self):
#         return len(self.pastes(is_private=True))
# 
#     @property
#     def public_pastes_count(self):
#         return len(self.pastes) - len(self.pastes(is_private=True))
# 
#     @property
#     def public_bookmarks(self):
#         return Bookmark.objects(user=self, is_private=False)
# 
#     @property
#     def public_bookmarks_count(self):
#         return Bookmark.objects(user=self, is_private=False).count()
# 
#     @property
#     def unread_messages_count(self):
#         return Message.objects(user=self, is_read=False).count()
# 
#     def save(self, *args, **kwargs):
#         if not self.salt:
#             self.salt = hashlib.sha1(str(time.time())).hexdigest()
#             self.password = self.generate_password(self.password)
#             number = User.objects().count() + 1
#             while(User.objects(number=number).first()):
#                 number += 1
#             self.number = number
#         super(User, self).save(*args, **kwargs)
# 
#     def owns_record(self, record):
#         return record.user == self
# 
#     def generate_password(self, string):
#         return hashlib.sha1('%s%s' % (string, self.salt)).hexdigest()
# 
#     def check_login(self, password):
#         return self.generate_password(password) == self.password
# 
#     @classmethod
#     def find_by_oauth(cls, provider, openid):
#         """Find user that has oauth info with given provider and openid"""
#         oauth = UserOauth.objects(provider=provider, openid=openid).first()
# 
#         if oauth and oauth.user:
#             return oauth.user
# 
#     def is_following(self, user):
#         return user in self.followings
# 
#     @property
#     def followers(self):
#         return User.objects(followings=self)
# 
# Path: daimaduan/tasks/celery.py
# @celery.task
# def send_email(config, user_email, subject, content):
#     envelope = email(sender=SENDER,
#                      receivers=[user_email],
#                      subject=subject,
#                      content=content)
# 
#     postman = Postman(host=config['host'],
#                       port=int(config['port']),
#                       middlewares=[TLS(force=True),
#                                    Auth(username=config['username'], password=config['password'])])
# 
#     postman.send(envelope)


# Path: daimaduan/utils/email_confirmation.py
from itsdangerous import URLSafeTimedSerializer
from daimaduan.models.base import User
from daimaduan.tasks.celery import send_email

                port=config['EMAIL']['port'],
                username=config['EMAIL']['username'],
                password=config['EMAIL']['password'])


def generate_confirmation_token(config, email):
    """generate confirmation token using user's email via itsdangerous"""
    serializer = URLSafeTimedSerializer(config['SECRET_KEY'])
    return serializer.dumps(email, salt=config['EMAIL']['salt'])


def validate_token(config, token, expire_time=3600):
    """from token and expire_time to confirm user's email"""
    serializer = URLSafeTimedSerializer(config['SECRET_KEY'])
    try:
        confirmed_email = serializer.loads(token, max_age=expire_time, salt=config['EMAIL']['salt'])
    except Exception:
        return False
    return confirmed_email


def send_confirm_email(config, user_email):
    token = generate_confirmation_token(config, user_email)
    user = User.objects(email=user_email).first()
    content = CONFIRMATION_CONTENT % (user.username, config['DOMAIN'], token, config['DOMAIN'], token)
    send_email.delay(get_email_config(config), user_email, CONFIRMATION_SUBJECT, content)


def send_reset_password_email(config, user_email):
    token = generate_confirmation_token(config, user_email)

    user = User.objects(email=user_email).first()