from functools import wraps from flask import request, make_response, jsonify import os class AuthError(Exception): def __init__(self, error, status_code): self.error = error self.status_code = status_code def get_token_auth_header(): """Obtains the access token from the Authorization Header """ auth = request.headers.get("Authorization", None) if not auth: raise AuthError({"code": "authorization_header_missing", "description": "Authorization header is expected"}, 401) parts = auth.split() if parts[0].lower() != "bearer": raise AuthError({"code": "invalid_header", "description": "Authorization header must start with" " Bearer"}, 401) elif len(parts) == 1: raise AuthError({"code": "invalid_header", "description": "Token not found"}, 401) elif len(parts) > 2: raise AuthError({"code": "invalid_header", "description": "Authorization header must be" " Bearer token"}, 401) token = parts[1] return token def requires_auth(f): """Determines if the access token is valid """ @wraps(f) def decorated(*args, **kwargs): token = get_token_auth_header() valid_token = os.environ.get('AUTHTOKEN', 'krishna') print (valid_token) print (token) if (token != valid_token): raise AuthError({"code": "invalid_token", "description": "invalid token"}, 401) return f(*args, **kwargs) return decorated