import base64
import binascii


def _parse_basic_auth(request):
    """
    Helper for basicauth. Extract password, username from Authorization Basic header.
    :returns: username, password as (str, str) or (None, None) if header not present or malformed.
    """
    if 'HTTP_AUTHORIZATION' in request.META:
        auth = request.META['HTTP_AUTHORIZATION'].split()
        if len(auth) == 2 and auth[0].lower() == "basic":
            try:
                auth_str = base64.b64decode(auth[1], validate=True).decode()
                uname_pwd = auth_str.split(':')
                if len(uname_pwd) == 2:
                    return tuple(uname_pwd)
            except binascii.Error:
                pass
            except UnicodeDecodeError:
                pass
    return (None, None)