#!/usr/bin/env python
# -*- coding: utf-8 -*-
import peewee
from flask import current_app,abort
from flask.ext.login import AnonymousUserMixin, UserMixin
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from peewee import Model, IntegerField, CharField,PrimaryKeyField
from website.app import db_wrapper, login_manager
from website.http.main_exception import MainException
from werkzeug.security import check_password_hash,generate_password_hash


class User(UserMixin, db_wrapper.Model):

    id = PrimaryKeyField()
    email = CharField(index=True)
    username = CharField(index=True)
    password_hash = CharField()
    role_id = IntegerField()
    confirmed = IntegerField()


    class Meta:
        db_table = 'users'

    def register(self,email,password,username):
        user = User(email=email, username=username, password_hash=generate_password_hash(password))
        try:
            user.save()
        except peewee.IntegrityError as err:
            print(err.args)
            if  err.args[0] == 1062:
                if 'ix_users_email' in err.args[1]:
                    raise MainException.DUPLICATE_EMAIL
                if 'ix_users_username' in err.args[1]:
                    raise MainException.DUPLICATE_USERNAME
        return user


    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)


    def generate_confirmation_token(self, expiration=3600):
        """生成验证邮箱的token"""
        s = Serializer(current_app.config['SECRET_KEY'], expiration)
        return s.dumps({'confirm': self.id})

    def confirm(self, token):
        """验证邮箱"""
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
            print(data)
        except:
            return False
        if data.get('confirm') != self.id:
            return False
        # 验证成功,写入数据库
        self.confirmed = True
        self.save()
        return True

    def generate_reset_token(self, expiration=3600):
        """生成重置密码的token"""
        s = Serializer(current_app.config['SECRET_KEY'], expiration)
        return s.dumps({'reset': self.id})

    def reset_password(self, token, new_password):
        """重置密码"""
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except:
            return False
        if data.get('reset') != self.id:
            return False
        # 验证成功,写入数据库
        self.password = new_password
        self.save()
        return True


"""
匿名用户
"""
class AnonymousUser(AnonymousUserMixin):
    def can(self, permissions):
        return False

    def is_administrator(self):
        return False

login_manager.anonymous_user = AnonymousUser


@login_manager.user_loader
def load_user(user_id):
    user = User.get(User.id == int(user_id))
    if not user:
        abort(404)
    else:
        return user




[((521, 538), 'peewee.PrimaryKeyField', 'PrimaryKeyField', ([], {}), '()\n', (536, 538), False, 'from peewee import Model, IntegerField, CharField, PrimaryKeyField\n'), ((551, 572), 'peewee.CharField', 'CharField', ([], {'index': '(True)'}), '(index=True)\n', (560, 572), False, 'from peewee import Model, IntegerField, CharField, PrimaryKeyField\n'), ((588, 609), 'peewee.CharField', 'CharField', ([], {'index': '(True)'}), '(index=True)\n', (597, 609), False, 'from peewee import Model, IntegerField, CharField, PrimaryKeyField\n'), ((630, 641), 'peewee.CharField', 'CharField', ([], {}), '()\n', (639, 641), False, 'from peewee import Model, IntegerField, CharField, PrimaryKeyField\n'), ((656, 670), 'peewee.IntegerField', 'IntegerField', ([], {}), '()\n', (668, 670), False, 'from peewee import Model, IntegerField, CharField, PrimaryKeyField\n'), ((687, 701), 'peewee.IntegerField', 'IntegerField', ([], {}), '()\n', (699, 701), False, 'from peewee import Model, IntegerField, CharField, PrimaryKeyField\n'), ((1343, 1392), 'werkzeug.security.check_password_hash', 'check_password_hash', (['self.password_hash', 'password'], {}), '(self.password_hash, password)\n', (1362, 1392), False, 'from werkzeug.security import check_password_hash, generate_password_hash\n'), ((1494, 1550), 'itsdangerous.TimedJSONWebSignatureSerializer', 'Serializer', (["current_app.config['SECRET_KEY']", 'expiration'], {}), "(current_app.config['SECRET_KEY'], expiration)\n", (1504, 1550), True, 'from itsdangerous import TimedJSONWebSignatureSerializer as Serializer\n'), ((1658, 1702), 'itsdangerous.TimedJSONWebSignatureSerializer', 'Serializer', (["current_app.config['SECRET_KEY']"], {}), "(current_app.config['SECRET_KEY'])\n", (1668, 1702), True, 'from itsdangerous import TimedJSONWebSignatureSerializer as Serializer\n'), ((2067, 2123), 'itsdangerous.TimedJSONWebSignatureSerializer', 'Serializer', (["current_app.config['SECRET_KEY']", 'expiration'], {}), "(current_app.config['SECRET_KEY'], expiration)\n", (2077, 2123), True, 'from itsdangerous import TimedJSONWebSignatureSerializer as Serializer\n'), ((2250, 2294), 'itsdangerous.TimedJSONWebSignatureSerializer', 'Serializer', (["current_app.config['SECRET_KEY']"], {}), "(current_app.config['SECRET_KEY'])\n", (2260, 2294), True, 'from itsdangerous import TimedJSONWebSignatureSerializer as Serializer\n'), ((2879, 2889), 'flask.abort', 'abort', (['(404)'], {}), '(404)\n', (2884, 2889), False, 'from flask import current_app, abort\n'), ((862, 894), 'werkzeug.security.generate_password_hash', 'generate_password_hash', (['password'], {}), '(password)\n', (884, 894), False, 'from werkzeug.security import check_password_hash, generate_password_hash\n')]