import json
from flask_restful import Resource, abort
from models.token import TokenModel

class AuthResource(Resource):

    def __init__(self): 
        self.token = TokenModel()
        with open("clients.json", "r") as clients_file:
            self.clients = json.load(clients_file)

    def auth(self, request): 
        allow = False
        auth = request.headers.get('Authorization', False)
        if auth:
            token = auth.split(' ').pop()
            parsed = self.token.validate(token)
            if parsed['valid']:
                client = self.clients.get(parsed['client_id'])
                if client: 
                    self.client = client
                    allow = True
        if not allow:
            abort(403, message="Invalid token")
        return allow