"""Basic utils.""" import base64 import binascii from collections import namedtuple import hashlib import hmac import json from users import constants Pagination = namedtuple('Pagination', ['offset', 'limit']) def sign_token(token, shared_secret): """Sign token with secret key. Args: token (bytes): the token to be signed shared_secret (bytes): the secret key to sign the token Returns: bytes: The signed token represented as hex """ token = hmac.new(shared_secret, token, hashlib.sha1).digest() return base64.b64encode(binascii.hexlify(token)) def get_pagination(request): """Parse pagination information. Args: request (Flask.request): The request object. Returns: Pagination (namedtuple): pagination information. """ page_offset = request.args.get('page_offset', constants.PAGE_OFFSET_DEFAULT) page_offset = _get_int(page_offset, constants.PAGE_OFFSET_DEFAULT) page_limit = request.args.get('page_limit', constants.PAGE_LIMIT_DEFAULT) page_limit = _get_int(page_limit, constants.PAGE_LIMIT_DEFAULT) return Pagination(page_offset, page_limit) def _get_int(value, default_value): """Methos to covert value in int. Args: value (str or int): The value to convert to int. default_value (int): The default value to use if value cannot be converted. Returns: int: value converted to int. """ try: return int(value) except Exception: return default_value def get_mock_response(profile_id, action_name): """Get mock response for this profile_id from json files.""" filename = f'{profile_id}_{action_name}.json' json_file = f'{constants.MOCK_RESPONSE_FOLDER}{filename}' with open(json_file) as json_file: data = json.load(json_file) return data