import json
from util import load_env


class AuthProvider(object):
    @staticmethod
    def from_environment():
        auth = load_env("AUTH", None)

        return AuthProvider(auth)

    def __init__(self, auth_token_config):
        if auth_token_config == "":
            self.auth_token_pool = []
            print("Service started without Authentication")
            return

        try:
            self.auth_token_pool = json.loads(auth_token_config)
        except ValueError as e:
            raise ValueError("Authentication configuration could not be parsed") from e

    def validate_token(self, token):
        """Validate a token for fabrication functions"""
        if token in self.auth_token_pool or not self.auth_token_pool:
            return True

        return False

    def user_for_token(self, token):
        return self.auth_token_pool.get(token)