Python base64.b64decode() Examples

The following are 30 code examples of base64.b64decode(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module base64 , or try the search function .
Example #1
Source File: angrysearch.py    From ANGRYsearch with GNU General Public License v2.0 11 votes vote down vote up
def get_tray_icon(self):
        base64_data = '''iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAABHN
                         CSVQICAgIfAhkiAAAAQNJREFUOI3t1M9KAlEcxfHPmP0xU6Ogo
                         G0teoCiHjAIfIOIepvKRUE9R0G0KNApfy0c8hqKKUMrD9zVGc4
                         9nPtlsgp5n6qSVSk7cBG8CJ6sEX63UEcXz4jE20YNPbygPy25Q
                         o6oE+fEPXFF7A5yA9Eg2sQDcU3sJd6k89O4iiMcYKVol3rH2Mc
                         a1meZ4hMdNPCIj+SjHHfFZU94/0Nwlv4rWoY7vhrdeLNoO86bG
                         lym/ge3lsHDdI2fojbBG6sUtzOiQ1wQOwk6GwWKHeJyHtxOcFi
                         0TpFaxmnhNcyIW45bQ6RS3Hq4MeB7Ltyahki9Gd2xidWiwG9va
                         nCZqi7xlZGVHfwN6+5nU/ccBUYAAAAASUVORK5CYII='''

        pm = Qg.QPixmap()
        pm.loadFromData(base64.b64decode(base64_data))
        i = Qg.QIcon()
        i.addPixmap(pm)
        return i

    # OFF BY DEFAULT
    # 0.2 SEC DELAY TO LET USER FINISH TYPING BEFORE INPUT BECOMES A DB QUERY 
Example #2
Source File: git.py    From aegea with Apache License 2.0 7 votes vote down vote up
def __init__(self, blob):
        super(Blob, self).__init__(blob)
        self._api = blob.get('url', '')

        #: Raw content of the blob.
        self.content = blob.get('content').encode()

        #: Encoding of the raw content.
        self.encoding = blob.get('encoding')

        #: Decoded content of the blob.
        self.decoded = self.content
        if self.encoding == 'base64':
            self.decoded = b64decode(self.content)

        #: Size of the blob in bytes
        self.size = blob.get('size')
        #: SHA1 of the blob
        self.sha = blob.get('sha') 
Example #3
Source File: auth.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def get_username_password(userpass):
    """
    Please note: username and password can either be presented in plain text
    such as "admin:password" or base64 encoded such as "YWRtaW46cGFzc3dvcmQ=".
    Both forms should be returned from this function.
    """
    plaintext = base64.b64decode(userpass)

    segments = plaintext.split(':')
    count = len(segments)
    if count == 1:
        return segments[0], ''
    elif count == 2:
        return segments
    else:
        raise Exception('There should be at most two segments!') 
Example #4
Source File: bwh_ctr.py    From BandwagongVPS_controller with GNU General Public License v3.0 6 votes vote down vote up
def lan_event(self):
        '''变更语言的方法'''
        #读取本地配置文件
        num = 0
        with open(".\data.ini",'rb') as f:
            self.lan_data = f.readlines()
        with open(".\data.ini",'wb') as f:
            for line in self.lan_data:
                if num == self.dual_host_view.currentRow() + 1:
                    data = base64.b64decode(line)
                    data = json.loads(data.decode())
                    data['lan'] = self.lan_input.currentIndex()
                    f.write(base64.b64encode(json.dumps(data).encode()))
                    f.write('\n'.encode())
                else:
                    f.write(line)
                num += 1

        a = QMessageBox()
        #写入成功提示
        a.information(a,self.tr("Success"),self.tr("Language will be changed after resrart the application")) 
Example #5
Source File: json_serializers.py    From dustmaps with GNU General Public License v2.0 6 votes vote down vote up
def deserialize_ndarray(d):
    """
    Deserializes a JSONified :obj:`numpy.ndarray`. Can handle arrays serialized
    using any of the methods in this module: :obj:`"npy"`, :obj:`"b64"`,
    :obj:`"readable"`.

    Args:
        d (`dict`): A dictionary representation of an :obj:`ndarray` object.

    Returns:
        An :obj:`ndarray` object.
    """
    if 'data' in d:
        x = np.fromstring(
            base64.b64decode(d['data']),
            dtype=d['dtype'])
        x.shape = d['shape']
        return x
    elif 'value' in d:
        return np.array(d['value'], dtype=d['dtype'])
    elif 'npy' in d:
        return deserialize_ndarray_npy(d)
    else:
        raise ValueError('Malformed np.ndarray encoding.') 
Example #6
Source File: wikipathway.py    From bioservices with GNU General Public License v3.0 6 votes vote down vote up
def getColoredPathway(self, pathwayId, filetype="svg", revision=0,
            color=None, graphId=None):
        """Get a colored image version of the pathway.

        :param str pwId: The pathway identifier.
        :param int revision: The revision number of the pathway (use '0' for most recent version).
        :param str fileType:  The image type (One of 'svg', 'pdf' or 'png'). Not
            yet implemented. svg is returned for now.
        :returns: Binary form of the image.

        .. todo:: graphId, color parameters
        """

        url = self.url + "getColoredPathway?pwId={}".format(pathwayId)
        if revision:
            url += "&revision={}".format(revision)
        url += "&format=json"
        request = self.http_get(url)
        try:
            data = request['data']  
            return base64.b64decode(data)
        except:
            return request 
Example #7
Source File: chemspider.py    From bioservices with GNU General Public License v3.0 6 votes vote down vote up
def image(self, Id):
        """ Return string containing PNG binary image data of 2D structure image

        ::

            >>> from bioservices import *
            >>> s = ChemSpider()
            >>> ret = s.image(1020)
            >>> with open("test.png", "w") as f:
            ...     f.write(ret)
            >>> s.on_web("test.png")
        """
        url = "Search.asmx/GetCompoundThumbnail?id=%s&token=%s" % (Id, self._token)
        res = self.http_get(url, frmt="xml")
        res = self.easyXML(res)
        #TODO python3 compatible !
        import base64
        image = base64.b64decode(res.root.text)
        return image 
Example #8
Source File: sm4.py    From pysm4 with MIT License 6 votes vote down vote up
def decrypt_ecb(cipher_text, key):
    """
    SM4(ECB)解密
    :param cipher_text: 密文
    :param key: 密钥, 小于等于16字节
    """
    cipher_text = b64decode(cipher_text)
    cipher_hex = _hex(cipher_text)

    # 密码检验
    key = _key_iv_check(key_iv=key)
    plain_hex_list = []
    for i in _range(len(cipher_text) // BLOCK_BYTE):
        sub_hex = cipher_hex[i * BLOCK_HEX:(i + 1) * BLOCK_HEX]
        plain = decrypt(cipher_num=int(sub_hex, 16),
                        mk=int(_hex(key), 16))
        plain_hex_list.append(num2hex(num=plain, width=BLOCK_HEX))

    plain_text = _padding(_unhex(''.join(plain_hex_list)),
                          mode=SM4_DECRYPT)
    return plain_text if PY2 else plain_text.decode(E_FMT)


# 密码块链接(CBC) 
Example #9
Source File: metadata.py    From sfdclib with MIT License 6 votes vote down vote up
def retrieve_zip(self, async_process_id):
        """ Retrieves ZIP file """
        result = self._retrieve_retrieve_result(async_process_id, 'true')
        state = result.find('mt:status', self._XML_NAMESPACES).text
        error_message = result.find('mt:errorMessage', self._XML_NAMESPACES)
        if error_message is not None:
            error_message = error_message.text

        # Check if there are any messages
        messages = []
        message_list = result.findall('mt:details/mt:messages', self._XML_NAMESPACES)
        for message in message_list:
            messages.append({
                'file': message.find('mt:fileName', self._XML_NAMESPACES).text,
                'message': message.find('mt:problem', self._XML_NAMESPACES).text
            })

        # Retrieve base64 encoded ZIP file
        zipfile_base64 = result.find('mt:zipFile', self._XML_NAMESPACES).text
        zipfile = b64decode(zipfile_base64)

        return state, error_message, messages, zipfile 
Example #10
Source File: firefox_decrypt.py    From firefox_decrypt with GNU General Public License v3.0 6 votes vote down vote up
def decode(self, data64):
        data = b64decode(data64)
        inp = self.SECItem(0, data, len(data))
        out = self.SECItem(0, None, 0)

        e = self._PK11SDR_Decrypt(inp, out, None)
        LOG.debug("Decryption of data returned %s", e)
        try:
            if e == -1:
                LOG.error("Password decryption failed. Passwords protected by a Master Password!")
                self.handle_error()
                raise Exit(Exit.NEED_MASTER_PASSWORD)

            res = ct.string_at(out.data, out.len).decode(LIB_ENCODING)
        finally:
            # Avoid leaking SECItem
            self._SECITEM_ZfreeItem(out, 0)

        return res 
Example #11
Source File: msch.py    From mindustry-modding with GNU General Public License v3.0 6 votes vote down vote up
def load(data, encoding="utf8"):
    """ Loads a base64 encoded schematic `str` object, 
    or a non-base65 encoded `bytes` object; returns a 
    Schematics object containing a Schematic, and it's 
    metadata, like width, height and tags."""
    if isinstance(data, str):
        base64header = "bXNjaAB"
        if not data.startswith(base64header):
            raise ValueError(f"String should start with: {base64header}")
        data = bytes(data, encoding)
        data = b64decode(data)

    if isinstance(data, bytes):
        data = msch.parse(data)
        return data
    else:
        raise ValueError(f"Unknown or unsupported type: {type(data)}")

########################################
## Writer
######################################## 
Example #12
Source File: WXBizMsgCrypt_py3.py    From TaskBot with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, key):
        # self.key = base64.b64decode(key+"=")
        self.key = key
        # 设置加解密模式为AES的CBC模式
        self.mode = AES.MODE_CBC 
Example #13
Source File: test_send_voice.py    From selfmailbot with MIT License 5 votes vote down vote up
def voice():
    """1 sec ogg file without speech in base64"""
    ogg_b64 = 'T2dnUwACAAAAAAAAAACfq5k2AAAAANaJ8cABE09wdXNIZWFkAQE4AYA+AAAAAABPZ2dTAAAAAAAAAAAAAJ+rmTYBAAAAUkVZJwP///5PcHVzVGFncxUAAABsaWJvcHVzIHVua25vd24tZml4ZWQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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QT2dnUwAAAOEAAAAAAACfq5k2FQAAAJWNjegBWFgLzHcQILiZ7UAuaBwijON/pszPxf3Hinot/XDBCQf53kowO3CoO3sx5p0QEC80kxZEg87SSxDcwwpE147dSBCCnf6WO4WACP4BZ9RiK8Qn5mNZuV2yWUBPZ2dTAABA7AAAAAAAAJ+rmTYWAAAAC6C2XAFiWAvMbXyXwG/dWjYxCaEGGIOAvo6oldhIi+zKQ39bm9a5hdOB/fgCY59U9gwpd1aH17JqWivRm/Yquj4K2MSeme98L5jf5VBQ9th3Mn0hM2V4JRypyLzYoUIQnmkNLgWOxhJPZ2dTAACA9wAAAAAAAJ+rmTYXAAAAnDavowFiWGvMjmpudD+DvqVeORbl+aylJ751Sa/6dF9eDXiqzRP9bBmzEyYi3HcmiwkuIwiFbs+ZRnx8nkqg7xLkMxSUp9uw3YsaceGyNfqCNvu3V748QgS2h1LJ3f3jxUuV37cgriBPZ2dTAADAAgEAAAAAAJ+rmTYYAAAAmRWs9wFYWAxJnrk892FAan/x8/l3cYyh5uRAuOmKgb2rpskJ2tDasgmiCJkuO1dZTTBh8gZ5Wug9jgAGjeEaEPLlMjtMAEmcevgQih/gfwVLRXSjLiM9dD8k4dukoE9nZ1MABPgJAQAAAAAAn6uZNhkAAADIV65cAUNYC8ycITEYQt3Bxy2qOTH9Gl/eH3HvarcrT85NuQwXVJ3JyPfaHuzAi7QFjEehNQF7WdjVQQLMfIT7ROKgR1vyt7vy'
    return base64.b64decode(ogg_b64) 
Example #14
Source File: utils.py    From zun with Apache License 2.0 5 votes vote down vote up
def decode_file_data(data):
    # Py3 raises binascii.Error instead of TypeError as in Py27
    try:
        return base64.b64decode(data)
    except (TypeError, binascii.Error):
        raise exception.Base64Exception() 
Example #15
Source File: map.py    From hadrian with Apache License 2.0 5 votes vote down vote up
def fromKey(self, key, avroType):
        bytes = io.BytesIO(base64.b64decode(key))
        reader = DatumReader(avroType.schema)
        return reader.read(BinaryDecoder(bytes)) 
Example #16
Source File: _encoded_words.py    From verge3d-blender-addon with GNU General Public License v3.0 5 votes vote down vote up
def decode_b(encoded):
    defects = []
    pad_err = len(encoded) % 4
    if pad_err:
        defects.append(errors.InvalidBase64PaddingDefect())
        padded_encoded = encoded + b'==='[:4-pad_err]
    else:
        padded_encoded = encoded
    try:
        # The validate kwarg to b64decode is not supported in Py2.x
        if not re.match(b'^[A-Za-z0-9+/]*={0,2}$', padded_encoded):
            raise binascii.Error('Non-base64 digit found')
        return base64.b64decode(padded_encoded), defects
    except binascii.Error:
        # Since we had correct padding, this must an invalid char error.
        defects = [errors.InvalidBase64CharactersDefect()]
        # The non-alphabet characters are ignored as far as padding
        # goes, but we don't know how many there are.  So we'll just
        # try various padding lengths until something works.
        for i in 0, 1, 2, 3:
            try:
                return base64.b64decode(encoded+b'='*i), defects
            except (binascii.Error, TypeError):    # Py2 raises a TypeError
                if i==0:
                    defects.append(errors.InvalidBase64PaddingDefect())
        else:
            # This should never happen.
            raise AssertionError("unexpected binascii.Error") 
Example #17
Source File: ContentFile.py    From gist-alfred with MIT License 5 votes vote down vote up
def decoded_content(self):
        assert self.encoding == "base64", "unsupported encoding: %s" % self.encoding
        if atLeastPython3:
            content = bytearray(self.content, "utf-8")  # pragma no cover (covered by tests with Python 3.2)
        else:
            content = self.content
        return base64.b64decode(content) 
Example #18
Source File: b64.py    From Matrix-NEB with Apache License 2.0 5 votes vote down vote up
def cmd_decode(self, event, *args):
        """Decode from base64. 'b64 decode <base64>'"""
        # use the body directly so quotes are parsed correctly.
        return base64.b64decode(event["content"]["body"][12:]) 
Example #19
Source File: aws_classes.py    From gryphon with MIT License 5 votes vote down vote up
def get_authorization():
    authorization = ecr.get_authorization_token()["authorizationData"][0]
    encoded_token = authorization["authorizationToken"]
    token = base64.b64decode(encoded_token).decode("utf-8")
    proxy = authorization["proxyEndpoint"]
    index = token.find(":")
    username = token[:index]
    password = token[index + 1 :]
    return {"username": username, "password": password, "endpoint": proxy} 
Example #20
Source File: reader.py    From hadrian with Apache License 2.0 5 votes vote down vote up
def _readBase64(data, dot):
    if isinstance(data, basestring):
        return base64.b64decode(data)
    else:
        raise PFASyntaxException("expected base64 data, not " + _trunc(repr(data)), dot) 
Example #21
Source File: WXBizMsgCrypt_py3.py    From TaskBot with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, sToken, sEncodingAESKey, sAppId):
        try:
            self.key = base64.b64decode(sEncodingAESKey + "=")
            assert len(self.key) == 32
        except Exception:
            throw_exception("[error]: EncodingAESKey unvalid !", FormatException)
            # return ierror.WXBizMsgCrypt_IllegalAesKey)
        self.token = sToken.encode()
        self.appid = sAppId.encode() 
Example #22
Source File: WXBizMsgCrypt_py3.py    From TaskBot with GNU General Public License v3.0 5 votes vote down vote up
def decrypt(self, text, appid):
        """对解密后的明文进行补位删除
        @param text: 密文
        @return: 删除填充补位后的明文
        """
        try:
            cryptor = AES.new(self.key, self.mode, self.key[:16])
            # 使用BASE64对密文进行解码,然后AES-CBC解密
            plain_text = cryptor.decrypt(base64.b64decode(text))
        except Exception as e:
            print(e)
            return ierror.WXBizMsgCrypt_DecryptAES_Error, None
        try:
            # pad = ord(plain_text[-1])
            pad = plain_text[-1]
            # 去掉补位字符串
            # pkcs7 = PKCS7Encoder()
            # plain_text = pkcs7.encode(plain_text)
            # 去除16位随机字符串
            content = plain_text[16:-pad]
            xml_len = socket.ntohl(struct.unpack("I", content[: 4])[0])
            xml_content = content[4: xml_len + 4]
            from_appid = content[xml_len + 4:]
        except Exception as e:
            return ierror.WXBizMsgCrypt_IllegalBuffer, None
        if from_appid != appid:
            return ierror.WXBizMsgCrypt_ValidateAppid_Error, None
        return 0, xml_content.decode() 
Example #23
Source File: test_push.py    From operator-courier with Apache License 2.0 5 votes vote down vote up
def test_create_base64_bundle(bundle_dir):
    with TemporaryDirectory() as scratch:
        directory_name = "directory-abcd"
        # make a subdirectory with a known name so that the bundle is always the same
        inpath = os.path.join(scratch, directory_name)
        os.mkdir(inpath)

        copy_tree(bundle_dir, inpath)
        out = PushCmd()._create_base64_bundle(inpath, "repo")

        outpath = os.path.join(scratch, "out")
        os.mkdir(outpath)

        # write the output tar
        tardata = base64.b64decode(out)
        tarfile_name = os.path.join(outpath, "bundle.tar.gz")
        with open(tarfile_name, "wb") as bundle:
            bundle.write(tardata)

        # uncompress the bundle
        with tarfile.open(tarfile_name) as bundle:
            bundle.extractall(path=outpath)

        outfiles = os.listdir(outpath)

        # ensure the surrouding directory was packed into the tar archive
        assert directory_name in outfiles 
Example #24
Source File: zbxdb.py    From zbxdb with GNU General Public License v3.0 5 votes vote down vote up
def decrypted(pw_enc):
    """return decrypted password"""

    return base64.b64decode(pw_enc).decode("utf-8", "ignore") 
Example #25
Source File: tag.py    From quart with MIT License 5 votes vote down vote up
def to_python(self, value: str) -> bytes:
        return b64decode(value) 
Example #26
Source File: mailslurper_import.py    From sarlacc with MIT License 5 votes vote down vote up
def main():
    config = ConfigParser()
    config.read("./smtpd.cfg")


    store = storage.StorageControl(config)

    cnx = mysql.connector.connect(
            user="root", password="root",
            host="localhost",
            database="sarlacc")

    mysql_cursor = cnx.cursor()

    mysql_cursor.execute("SELECT dateSent, fromAddress, toAddressList, subject, body FROM mailitem;")

    for (dateSent, fromAddress, toAddressList, subject, body) in mysql_cursor:
        # tidy up fromAddress
        fromAddress = cleanupAddress(re.findall(r"<(.*?)>", fromAddress)[0])

        # tidy up toaAdressList
        toAddressList = re.findall(r"<(.*?)>", toAddressList)

        body = str(b64decode(body))

        store.store_email(subject, toAddressList, fromAddress, body, dateSent, [])

    mysql_cursor.close()
    cnx.close() 
Example #27
Source File: __init__.py    From aws-ops-automator with Apache License 2.0 5 votes vote down vote up
def get_item_resource_data(item, context):
    global _kms_client
    resource_data = item.get(TASK_TR_RESOURCES, "{}")
    if item.get(TASK_TR_ENCRYPTED_RESOURCES):
        if _kms_client is None:
            _kms_client = boto_retry.get_client_with_retries("kms", ["decrypt"], context=context)
        resource_data = _kms_client.decrypt(CiphertextBlob=base64.b64decode(resource_data))["Plaintext"]
    return resource_data if type(resource_data) in [dict, list] else json.loads(resource_data) 
Example #28
Source File: sm4.py    From pysm4 with MIT License 5 votes vote down vote up
def decrypt_cbc(cipher_text, key, iv):
    """
    SM4(CBC)解密
    :param cipher_text: 密文
    :param key: 密钥 小于等于16字节
    :param iv: 初始化向量 小于等于16字节
    """
    cipher_text = b64decode(cipher_text)
    cipher_hex = _hex(cipher_text)

    # 密钥检测
    key = _key_iv_check(key_iv=key)
    # 初始化向量检测
    iv = _key_iv_check(key_iv=iv)
    ivs = [int(_hex(iv), 16)]
    plain_hex_list = []
    for i in _range(len(cipher_text) // BLOCK_BYTE):
        sub_hex = cipher_hex[i * BLOCK_HEX:(i + 1) * BLOCK_HEX]
        cipher = int(sub_hex, 16)
        plain = (ivs[i] ^ decrypt(cipher_num=cipher,
                                  mk=int(_hex(key), 16)))
        ivs.append(cipher)
        plain_hex_list.append(num2hex(num=plain, width=BLOCK_HEX))

    plain_text = _padding(_unhex(''.join(plain_hex_list)),
                          mode=SM4_DECRYPT)
    return plain_text if PY2 else plain_text.decode(E_FMT) 
Example #29
Source File: Tools.py    From joeecc with GNU General Public License v3.0 5 votes vote down vote up
def load_pem_data(filename, specifier):
	"""Loads the PEM payload, designated with a BEGIN and END specifier, from a
	file given by its filename."""
	data = None
	with open(filename, "r") as f:
		spec_begin = "-----BEGIN " + specifier + "-----"
		spec_end = "-----END " + specifier + "-----"
		for line in f:
			line = line.rstrip()
			if (data is None) and (line == spec_begin):
				data = [ ]
			elif (data is not None) and (line == spec_end):
				break
			elif data is not None:
				data.append(line)
	if data is None:
		raise Exception("Trying to parse PEM file with specifier '%s', but no such block in file found." % (specifier))
	data = base64.b64decode("".join(data).encode("utf-8"))
	return data 
Example #30
Source File: permissions.py    From gazetteer with MIT License 5 votes vote down vote up
def user_has_perms(self, request):
        '''
            Check if user has permissions for the URL path and method in the request.
        '''
        path, user, method = (request.path, request.user, request.method,)
        #If it is not an API call, always return True
        if not path.startswith(API_BASE):
            return True
        #Return True for all GET requests
        if method == 'GET':
            return True
        #If request is POST, PUT or DELETE, check if user is authenticated. More fine-grained permissions checks can be handled here
        if method in ['POST', 'PUT', 'DELETE']:

            if not user.is_authenticated():
                #If user is not authenticated by session var, check for http basic
                if 'HTTP_AUTHORIZATION' in request.META:
                    auth = request.META['HTTP_AUTHORIZATION'].split()
                    if len(auth) == 2:
                        if auth[0].lower() == "basic":
                            uname, passwd = base64.b64decode(auth[1]).split(':')
                            user = authenticate(username=uname, password=passwd)
                            if user is not None:
                                if user.is_active:
                                    login(request, user)
                                    request.user = user
                                    return True
                return False
            else:
                return True
        #Ideally, should never reach here. #QUESTION: perhaps we want to return False by default?
        return True