from password_manager.encrypt import DefaultCipher, random_key


def generate_temporary_key(user, password, valid_for_seconds=120):
    """
    NOTE: The key generated by this method, is VERY POWERFUL once it can unveil
    user's password. So, key MUST NEVER be stored. It can only be kept in RAM
    memory.
    """
    from password_manager.models import TemporaryKey
    from django.utils import timezone
    import datetime

    assert user.check_password(password), 'Invalid user password'

    key = random_key(32)
    cipher = DefaultCipher(key)
    now = timezone.now()
    expires_at = now + datetime.timedelta(seconds=valid_for_seconds)
    encrypted_password = cipher.encrypt(password)

    TemporaryKey.objects.filter(user=user).delete()
    TemporaryKey.objects.create(
        user=user,
        encrypted_password=encrypted_password,
        expires_at=expires_at
    )
    return key
