'This function takes a WSGI environment and authenticates
the request returning authenticated user or error.'

def authenticate(self, environ):

    method = REQUEST_METHOD(environ)
    fullpath = (url_quote(SCRIPT_NAME(environ)) + url_quote(PATH_INFO(environ)))
    authorization = AUTHORIZATION(environ)
    if (not authorization):
        return self.build_authentication()
    (authmeth, auth) = authorization.split('    ', 1)
    if ('digest' != authmeth.lower()):
        return self.build_authentication()
    amap = dict(_auth_to_kv_pairs(auth))
    try:
        username = amap['username']
        authpath = amap['uri']
        nonce = amap['nonce']
        realm = amap['realm']
        response = amap['response']
        assert (authpath.split('?', 1)[0] in fullpath)
        assert (realm == self.realm)
        qop = amap.get('qop', '')
        cnonce = amap.get('cnonce', '')
        nc = amap.get('nc', '00000000')
        if qop:
            assert ('auth' == qop)
            assert (nonce and nc)
    except:
        return self.build_authentication()
    ha1 = self.authfunc(environ, realm, username)
    return self.compute(ha1, username, response, method, authpath, nonce, nc, cnonce, qop)
