from __init__ import *
import random, string
from __init__ import *
from wtforms.validators import *

def validate_email(email):
    if Users.query.filter_by(email=email.data).first():
        raise ValidationError("Email already registered!")

def validate_uname(uname):
    if Users.query.filter_by(username=uname.data).first():
        raise ValidationError("Username already taken!")

def Token(user):
    # exp=datetime.now() + timedelta(hours=20)
    exp = timedelta(minutes=10000)
    data = dict(
        username=user.username,
        email=user.email,
        avatar=user.avatar,
        post=user.post,
        id=user.id,
        firstname=user.firstname,
        lastname=user.lastname
    )
    token = create_access_token(identity=data, fresh=True, expires_delta=exp)
    # token = jwt.encode(data, app.config['SECRET_KEY'], algorithm="HS256")
    return token, data

def token_required(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        token = None
        if 'Authorization' in request.headers:
            bearer = request.headers.get('Authorization')    # Bearer YourTokenHere
            token = bearer.split()[1]
            # print(token)
            if token:
                try:
                    data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"])
                    return f(data, *args, **kwargs)
                except Exception as e:
                    return jsonify({'message': str(e), 'success': False}), 401
            else:
                return jsonify({'message': 'Unauthenticated', 'success': False}), 401
        if not token:
            return jsonify({'message': 'Unauthenticated', 'success': False}), 401
    return decorated