Пример #1
0
def _validate_tiddler_list(environ, tiddlers):
    """
    Do Etag and Last modified checks on the
    collection of tiddlers.

    If ETag testing is done, no last modified handling
    is done, even if the ETag testing fails.

    If no 304 is raised, then just return last-modified
    and ETag for the caller to use in constructing
    its HTTP response.
    """
    last_modified_string = http_date_from_timestamp(tiddlers.modified)
    last_modified = ('Last-Modified', last_modified_string)

    username = environ.get('tiddlyweb.usersign', {}).get('name', '')

    try:
        _, mime_type = get_serialize_type(environ)
        mime_type = mime_type.split(';', 1)[0].strip()
    except TypeError:
        mime_type = ''
    etag_string = '"%s:%s"' % (tiddlers.hexdigest(),
                               sha('%s:%s' %
                                   (username, mime_type)).hexdigest())
    etag = ('Etag', etag_string)

    incoming_etag = check_incoming_etag(environ,
                                        etag_string,
                                        last_modified=last_modified_string)
    if not incoming_etag:  # only check last modified when no etag
        check_last_modified(environ, last_modified_string, etag=etag_string)

    return last_modified, etag
Пример #2
0
def code_expired(registration):
    """
    Return true if this registration is out of date.
    """
    timestamp = registration.created
    created_time = datetime_from_http_date(http_date_from_timestamp(timestamp))
    return created_time < (datetime.utcnow() - timedelta(minutes=1))
Пример #3
0
def validate_tiddler_headers(environ, tiddler):
    """
    Check ETAG and last modified information to
    see if a) the client can use its cached tiddler
    b) we have edit contention when trying to write.
    """
    request_method = environ['REQUEST_METHOD']
    tiddlers_etag = tiddler_etag(environ, tiddler)

    LOGGER.debug('attempting to validate %s with revision %s',
            tiddler.title.encode('utf-8'), tiddler.revision)

    etag = None
    last_modified = None
    if request_method == 'GET':
        incoming_etag = check_incoming_etag(environ, tiddlers_etag)
        if not incoming_etag:  # only check last-modified if no etag
            last_modified_string = http_date_from_timestamp(
                    tiddler.modified)
            last_modified = ('Last-Modified', last_modified_string)
            check_last_modified(environ, last_modified_string)

    else:
        incoming_etag = environ.get('HTTP_IF_MATCH', None)
        LOGGER.debug('attempting to validate incoming etag(PUT):'
            '%s against %s', incoming_etag, tiddlers_etag)
        if incoming_etag and not _etag_write_match(incoming_etag,
                tiddlers_etag):
            raise HTTP412('Provided ETag does not match. '
                'Server content probably newer.')
    etag = ('Etag', '%s' % tiddlers_etag)
    return last_modified, etag
Пример #4
0
def code_expired(registration):
    """
    Return true if this registration is out of date.
    """
    timestamp = registration.created
    created_time = datetime_from_http_date(http_date_from_timestamp(timestamp))
    return created_time < (datetime.utcnow() - timedelta(minutes=1))
Пример #5
0
def _validate_tiddler(environ, tiddler):
    """
    Check ETAG and last modified information to
    see if a) the client can use its cached tiddler
    b) we have edit contention when trying to write.
    """
    request_method = environ['REQUEST_METHOD']
    tiddler_etag = _tiddler_etag(tiddler)

    logging.debug('attempting to validate %s with revision %s' %
            (tiddler.title, tiddler.revision))

    etag = None
    last_modified = None
    if request_method == 'GET':
        incoming_etag = environ.get('HTTP_IF_NONE_MATCH', None)
        if incoming_etag == tiddler_etag:
            raise HTTP304(incoming_etag)
        last_modified_string = web.http_date_from_timestamp(tiddler.modified)
        last_modified = ('Last-Modified', last_modified_string)
        incoming_modified = environ.get('HTTP_IF_MODIFIED_SINCE', None)
        if incoming_modified and \
                (web.datetime_from_http_date(incoming_modified) >=
                        web.datetime_from_http_date(last_modified_string)):
            raise HTTP304('')

    else:
        incoming_etag = environ.get('HTTP_IF_MATCH', None)
        logging.debug('attempting to validate incoming etag: %s against %s' %
                (incoming_etag, tiddler_etag))
        if incoming_etag and incoming_etag != tiddler_etag:
            raise HTTP412('Provided ETag does not match. Server content probably newer.')
    etag = ('Etag', tiddler_etag)
    return last_modified, etag
Пример #6
0
def _validate_tiddler_list(environ, tiddlers):
    """
    Do Etag and Last modified checks on the
    collection of tiddlers.

    If ETag testing is done, no last modified handling
    is done, even if the ETag testing fails.

    If no 304 is raised, then just return last-modified
    and ETag for the caller to use in constructing
    its HTTP response.
    """
    last_modified_string = http_date_from_timestamp(tiddlers.modified)
    last_modified = ('Last-Modified', last_modified_string)

    username = environ.get('tiddlyweb.usersign', {}).get('name', '')

    try:
        _, mime_type = get_serialize_type(environ)
        mime_type = mime_type.split(';', 1)[0].strip()
    except TypeError:
        mime_type = ''
    etag_string = '"%s:%s"' % (tiddlers.hexdigest(),
            sha('%s:%s' % (username.encode('utf-8'), mime_type)).hexdigest())
    etag = ('Etag', etag_string)

    incoming_etag = check_incoming_etag(environ, etag_string)
    if not incoming_etag:  # only check last modified when no etag
        check_last_modified(environ, last_modified_string)

    return last_modified, etag
Пример #7
0
def _validate_tiddler_list(environ, bag):
    """
    Calculate the Last modified and ETag for
    the tiddlers in bag. If the ETag matches an
    incoming If-None-Match, then raise a 304 and
    don't send the tiddler content. If the modified
    string in an If-Modified-Since is newer than the
    last-modified on the tiddlers, raise 304.

    If ETag testing is done, no last modified handling
    is done, even if the ETag testing fails.

    If no 304 is raised, then just return last-modified
    and ETag for the caller to use in constructing
    its HTTP response.
    """
    last_modified_number = _last_modified_tiddler(bag)
    last_modified = None
    if last_modified_number:
        last_modified_string = http_date_from_timestamp(last_modified_number)
        last_modified = ("Last-Modified", last_modified_string)

    username = environ.get("tiddlyweb.usersign", {}).get("name", "")

    try:
        serialize_type, mime_type = get_serialize_type(environ)
        mime_type = mime_type.split(";", 1)[0].strip()
    except TypeError:
        mime_type = ""
    etag_string = '"%s:%s;%s"' % (
        _sha_tiddler_titles(bag),
        last_modified_number,
        sha("%s:%s" % (username, mime_type)).hexdigest(),
    )
    etag = ("Etag", etag_string)

    incoming_etag = environ.get("HTTP_IF_NONE_MATCH", None)
    if incoming_etag:
        if incoming_etag == etag_string:
            raise HTTP304(incoming_etag)
    else:
        incoming_modified = environ.get("HTTP_IF_MODIFIED_SINCE", None)
        if incoming_modified and (
            datetime_from_http_date(incoming_modified) >= datetime_from_http_date(last_modified_string)
        ):
            raise HTTP304("")

    return last_modified, etag
Пример #8
0
def test_put_tiddler_json():
    http = httplib2.Http()

    json = simplejson.dumps(
        dict(text='i fight for the users',
             tags=['tagone', 'tagtwo'],
             modifier=''))

    response, content = http.request(
        'http://our_test_domain:8001/bags/bag0/tiddlers/TestTwo',
        method='PUT',
        headers={
            'Content-Type': 'application/json',
            'Content-Length': '0'
        },
        body='')
    assert response['status'] == '400'
    assert 'unable to make json into' in content

    response, content = http.request(
        'http://our_test_domain:8001/bags/bag0/tiddlers/TestTwo',
        method='PUT',
        headers={'Content-Type': 'application/json'},
        body='{"text": "}')
    assert response['status'] == '400'
    assert 'unable to make json into' in content

    response, content = http.request(
        'http://our_test_domain:8001/bags/bag0/tiddlers/TestTwo',
        method='PUT',
        headers={'Content-Type': 'application/json'},
        body=json)

    assert response['status'] == '204'
    tiddler_url = response['location']
    assert (tiddler_url ==
            'http://our_test_domain:8001/bags/bag0/tiddlers/TestTwo')

    response, content = http.request(tiddler_url,
                                     headers={'Accept': 'application/json'})
    info = simplejson.loads(content)
    now_time = http_date_from_timestamp('')
    assert response['last-modified'].split(':',
                                           1)[0] == now_time.split(':', 1)[0]
    assert info['title'] == 'TestTwo'
    assert info['text'] == 'i fight for the users'
    assert info['uri'] == tiddler_url
Пример #9
0
def validate_tiddler_headers(environ, tiddler):
    """
    Check ETag and last modified header information to
    see if a) on ``GET`` the user agent can use its cached tiddler
    b) on ``PUT`` we have edit contention.
    """
    request_method = environ['REQUEST_METHOD']
    this_tiddlers_etag = tiddler_etag(environ, tiddler)

    LOGGER.debug('attempting to validate %s with revision %s', tiddler.title,
                 tiddler.revision)

    etag = None
    last_modified = None
    if request_method == 'GET':
        last_modified_string = http_date_from_timestamp(tiddler.modified)
        last_modified = ('Last-Modified', last_modified_string)
        cache_header = 'no-cache'
        if CACHE_CONTROL_FIELD in tiddler.fields:
            try:
                cache_header = 'max-age=%s' % int(
                    tiddler.fields[CACHE_CONTROL_FIELD])
            except ValueError:
                pass  # if the value is not an int use default header
        incoming_etag = check_incoming_etag(environ,
                                            this_tiddlers_etag,
                                            last_modified=last_modified_string,
                                            cache_control=cache_header)
        if not incoming_etag:  # only check last-modified if no etag
            check_last_modified(environ,
                                last_modified_string,
                                etag=this_tiddlers_etag,
                                cache_control=cache_header)

    else:
        incoming_etag = environ.get('HTTP_IF_MATCH', None)
        LOGGER.debug(
            'attempting to validate incoming etag(PUT):'
            '%s against %s', incoming_etag, this_tiddlers_etag)
        if incoming_etag and not _etag_write_match(incoming_etag,
                                                   this_tiddlers_etag):
            raise HTTP412('Provided ETag does not match. '
                          'Server content probably newer.')
    etag = ('ETag', '%s' % this_tiddlers_etag)
    return last_modified, etag
Пример #10
0
def _validate_tiddler_headers(environ, tiddler):
    """
    Check ETAG and last modified information to
    see if a) the client can use its cached tiddler
    b) we have edit contention when trying to write.
    """
    request_method = environ['REQUEST_METHOD']
    tiddler_etag = web.tiddler_etag(environ, tiddler)

    logging.debug('attempting to validate %s with revision %s', tiddler.title,
                  tiddler.revision)

    etag = None
    last_modified = None
    if request_method == 'GET':
        incoming_etag = environ.get('HTTP_IF_NONE_MATCH', None)
        if incoming_etag:
            logging.debug(
                'attempting to validate incoming etag(GET):'
                '%s against %s', incoming_etag, tiddler_etag)
            if incoming_etag == tiddler_etag:
                raise HTTP304(incoming_etag)
        else:
            last_modified_string = web.http_date_from_timestamp(
                tiddler.modified)
            last_modified = ('Last-Modified', last_modified_string)
            incoming_modified = environ.get('HTTP_IF_MODIFIED_SINCE', None)
            if incoming_modified and \
                    (web.datetime_from_http_date(incoming_modified) >=
                            web.datetime_from_http_date(last_modified_string)):
                raise HTTP304('')

    else:
        incoming_etag = environ.get('HTTP_IF_MATCH', None)
        logging.debug(
            'attempting to validate incoming etag(PUT):'
            '%s against %s', incoming_etag, tiddler_etag)
        if incoming_etag and not _etag_write_match(incoming_etag,
                                                   tiddler_etag):
            raise HTTP412('Provided ETag does not match. '
                          'Server content probably newer.')
    etag = ('Etag', '%s' % tiddler_etag)
    return last_modified, etag
Пример #11
0
def validate_tiddler_headers(environ, tiddler):
    """
    Check ETag and last modified header information to
    see if a) on ``GET`` the user agent can use its cached tiddler
    b) on ``PUT`` we have edit contention.
    """
    request_method = environ['REQUEST_METHOD']
    this_tiddlers_etag = tiddler_etag(environ, tiddler)

    LOGGER.debug('attempting to validate %s with revision %s',
            tiddler.title, tiddler.revision)

    etag = None
    last_modified = None
    if request_method == 'GET':
        last_modified_string = http_date_from_timestamp(tiddler.modified)
        last_modified = ('Last-Modified', last_modified_string)
        cache_header = 'no-cache'
        if CACHE_CONTROL_FIELD in tiddler.fields:
            try:
                cache_header = 'max-age=%s' % int(
                        tiddler.fields[CACHE_CONTROL_FIELD])
            except ValueError:
                pass  # if the value is not an int use default header
        incoming_etag = check_incoming_etag(environ, this_tiddlers_etag,
                last_modified=last_modified_string,
                cache_control=cache_header)
        if not incoming_etag:  # only check last-modified if no etag
            check_last_modified(environ, last_modified_string,
                    etag=this_tiddlers_etag,
                    cache_control=cache_header)

    else:
        incoming_etag = environ.get('HTTP_IF_MATCH', None)
        LOGGER.debug('attempting to validate incoming etag(PUT):'
            '%s against %s', incoming_etag, this_tiddlers_etag)
        if incoming_etag and not _etag_write_match(incoming_etag,
                this_tiddlers_etag):
            raise HTTP412('Provided ETag does not match. '
                'Server content probably newer.')
    etag = ('ETag', '%s' % this_tiddlers_etag)
    return last_modified, etag
Пример #12
0
def _validate_tiddler_list(environ, tiddlers):
    last_modified_number = _last_modified_tiddler(tiddlers)
    last_modified_string = http_date_from_timestamp(last_modified_number)
    last_modified = ('Last-Modified', last_modified_string)

    etag_string = '%s:%s' % (_sha_tiddler_titles(tiddlers), last_modified_number)
    etag = ('Etag', etag_string)

    incoming_etag = environ.get('HTTP_IF_NONE_MATCH', None)
    if incoming_etag:
        if incoming_etag == etag_string:
            raise HTTP304(incoming_etag)
    else:
        incoming_modified = environ.get('HTTP_IF_MODIFIED_SINCE', None)
        if incoming_modified and \
                (datetime_from_http_date(incoming_modified) >= \
                datetime_from_http_date(last_modified_string)):
            raise HTTP304('')

    return last_modified, etag
Пример #13
0
def test_put_tiddler_json():
    http = httplib2.Http()

    json = simplejson.dumps(dict(text="i fight for the users", tags=["tagone", "tagtwo"], modifier=""))

    response, content = http.request(
        "http://our_test_domain:8001/bags/bag0/tiddlers/TestTwo",
        method="PUT",
        headers={"Content-Type": "application/json", "Content-Length": "0"},
        body="",
    )
    assert response["status"] == "400"
    assert "unable to make json into" in content

    response, content = http.request(
        "http://our_test_domain:8001/bags/bag0/tiddlers/TestTwo",
        method="PUT",
        headers={"Content-Type": "application/json"},
        body='{"text": "}',
    )
    assert response["status"] == "400"
    assert "unable to make json into" in content

    response, content = http.request(
        "http://our_test_domain:8001/bags/bag0/tiddlers/TestTwo",
        method="PUT",
        headers={"Content-Type": "application/json"},
        body=json,
    )

    assert response["status"] == "204"
    tiddler_url = response["location"]
    assert tiddler_url == "http://our_test_domain:8001/bags/bag0/tiddlers/TestTwo"

    response, content = http.request(tiddler_url, headers={"Accept": "application/json"})
    info = simplejson.loads(content)
    now_time = http_date_from_timestamp("")
    assert response["last-modified"].split(":", 1)[0] == now_time.split(":", 1)[0]
    assert info["title"] == "TestTwo"
    assert info["text"] == "i fight for the users"
    assert info["uri"] == tiddler_url
Пример #14
0
def _validate_tiddler_list(environ, tiddlers):
    """
    Do Etag and Last modified checks on the
    collection of tiddlers.

    If ETag testing is done, no last modified handling
    is done, even if the ETag testing fails.

    If no 304 is raised, then just return last-modified
    and ETag for the caller to use in constructing
    its HTTP response.
    """
    last_modified_number = tiddlers.modified
    last_modified_string = http_date_from_timestamp(last_modified_number)
    last_modified = ('Last-Modified', last_modified_string)

    username = environ.get('tiddlyweb.usersign', {}).get('name', '')

    try:
        _, mime_type = get_serialize_type(environ)
        mime_type = mime_type.split(';', 1)[0].strip()
    except TypeError:
        mime_type = ''
    etag_string = '"%s:%s;%s"' % (tiddlers.hexdigest(),
                                  str(last_modified_number),
                                  sha('%s:%s' %
                                      (username, mime_type)).hexdigest())
    etag = ('Etag', etag_string)

    incoming_etag = environ.get('HTTP_IF_NONE_MATCH', None)
    if incoming_etag:
        if incoming_etag == etag_string:
            raise HTTP304(incoming_etag)
    else:
        incoming_modified = environ.get('HTTP_IF_MODIFIED_SINCE', None)
        if incoming_modified and \
                (datetime_from_http_date(incoming_modified) >= \
                datetime_from_http_date(last_modified_string)):
            raise HTTP304('')

    return last_modified, etag
Пример #15
0
def test_put_tiddler_json():
    http = httplib2.Http()

    json = simplejson.dumps(dict(text='i fight for the users',
        tags=['tagone','tagtwo'], modifier=''))

    response, content = http.request(
            'http://our_test_domain:8001/bags/bag0/tiddlers/TestTwo',
            method='PUT',
            headers={'Content-Type': 'application/json',
                'Content-Length': '0'},
            body='')
    assert response['status'] == '400'
    assert 'unable to make json into' in content

    response, content = http.request(
            'http://our_test_domain:8001/bags/bag0/tiddlers/TestTwo',
            method='PUT',
            headers={'Content-Type': 'application/json'},
            body='{"text": "}')
    assert response['status'] == '400'
    assert 'unable to make json into' in content

    response, content = http.request(
            'http://our_test_domain:8001/bags/bag0/tiddlers/TestTwo',
            method='PUT', headers={'Content-Type': 'application/json'},
            body=json)

    assert response['status'] == '204'
    tiddler_url = response['location']
    assert (tiddler_url ==
            'http://our_test_domain:8001/bags/bag0/tiddlers/TestTwo')

    response, content = http.request(tiddler_url,
            headers={'Accept': 'application/json'})
    info = simplejson.loads(content)
    now_time = http_date_from_timestamp('')
    assert response['last-modified'].split(':', 1)[0] == now_time.split(':', 1)[0]
    assert info['title'] == 'TestTwo'
    assert info['text'] == 'i fight for the users'
    assert info['uri'] == tiddler_url
Пример #16
0
def _validate_tiddler_list(environ, tiddlers):
    """
    Do Etag and Last modified checks on the
    collection of tiddlers.

    If ETag testing is done, no last modified handling
    is done, even if the ETag testing fails.

    If no 304 is raised, then just return last-modified
    and ETag for the caller to use in constructing
    its HTTP response.
    """
    last_modified_number = tiddlers.modified
    last_modified_string = http_date_from_timestamp(last_modified_number)
    last_modified = ('Last-Modified', last_modified_string)

    username = environ.get('tiddlyweb.usersign', {}).get('name', '')

    try:
        _, mime_type = get_serialize_type(environ)
        mime_type = mime_type.split(';', 1)[0].strip()
    except TypeError:
        mime_type = ''
    etag_string = '"%s:%s;%s"' % (tiddlers.hexdigest(),
            str(last_modified_number), sha('%s:%s' %
                (username, mime_type)).hexdigest())
    etag = ('Etag', etag_string)

    incoming_etag = environ.get('HTTP_IF_NONE_MATCH', None)
    if incoming_etag:
        if incoming_etag == etag_string:
            raise HTTP304(incoming_etag)
    else:
        incoming_modified = environ.get('HTTP_IF_MODIFIED_SINCE', None)
        if incoming_modified and \
                (datetime_from_http_date(incoming_modified) >= \
                datetime_from_http_date(last_modified_string)):
            raise HTTP304('')

    return last_modified, etag
Пример #17
0
def format_modified(modified_string):
    """Translate a tiddler modified or created string into an http date."""
    return http_date_from_timestamp(modified_string)
Пример #18
0
def format_modified(modified_string):
    """Translate a tiddlywiki modified_string into a http date."""
    return http_date_from_timestamp(modified_string)
Пример #19
0
def format_modified(modified_string):
    """Translate a tiddlywiki modified_string into a http date."""
    return http_date_from_timestamp(modified_string)