from werkzeug.security import safe_str_cmp
from user import User

"""
users = [
    {
        'id': 1,
        'username': 'josep',
        'password': '1965',
    }
]

username_mapping = {'josep': {
        'id': 1,
        'username': 'josep',
        'password': '1965',
    }
}

userid_mapping = {1: {
        'id': 1,
        'username': 'josep',
        'password': '1965',
    }
}
"""

# replace previous dictionaries by user.py and the following lines of code

users = [
    User(1, 'josep', '1965'),
    User(2, 'jetro', '4100'),
]

username_mapping = {u.username: u for u in users}
userid_mapping = {u.id: u for u in users}


def authenticate(username, password):
    """returns None if the username is not found"""
    user = username_mapping.get(username, None)
    # if user and user.password == password:
    if user and safe_str_cmp(user.password, password):
        return user


def identity(payload):
    user_id = payload['identity']
    return userid_mapping.get(user_id, None)
