"""Utility interface for the handlers.""" import base64 from time import time from oto import response from oto.adaptors.flask import flaskify from owsrequest import flask_request from feature_fm.config import ENVIRONMENT from feature_fm.constants import error, header, ows_services from feature_fm.utils import token_verification def process_variables(request, timestamp, token): """Process variables for token based handlers. Args: request (flask.request): the flask request timestamp (str): the timestamp as string token (str): the sha-1 encrypted token Returns: tuple of strings: with variables signed_token, unencrypted_token, delta_time """ signed_token = bytes(base64.b64decode(token)) path = request.full_path token_query_param = 'token={0}'.format(request.args.get('token')) path = path.replace( token_query_param, '').replace('&&', '&').replace('?&', '?') if path.endswith('&'): path = path[:-1] unencrypted_token = bytes(path.encode('utf-8')) current_time = int(time()) delta_time = current_time - int(timestamp) return signed_token, unencrypted_token, delta_time def access_validation(request, account_type, account_id): """Get access validation for account_type and account_id. Args: request (flask.request): the flask request account_type (str): The account type (vendor or subaccount) account_id (int): The account id e.g. 123 Returns: response.Response: describes whether access is valid. """ if ((account_type not in header.GRASS_ACCOUNT_TYPES) or not account_id): return flaskify(response.create_error_response( code=error.ERROR_CODE_BAD_REQUEST, message=error.ERROR_MESSAGE_INVALID_ACCOUNT)) return flask_request.verify_grass_access( request, **{account_type: account_id}) def validate_token(request, timestamp, token): """Validate the token. Args: request (flask.request): the flask request timestamp (str): the timestamp as string token (str): the sha-1 encrypted token Returns: boolean: flag that confirms the token validation """ if not token: return False if not timestamp: return False signed_token, unencrypted_token, delta_time = process_variables( request, timestamp, token) if delta_time <= ows_services.TIMESTAMP_DELTA[ENVIRONMENT]: return token_verification.verify_token(unencrypted_token, signed_token) else: return False