Esempio n. 1
0
def set_cookie(cookies, key, value, expires=None, httponly=True, path=b'/'):
    cookies[key] = value
    cookie = cookies[key]
    if expires:
        if isinstance(expires, timedelta):
            expires += utcnow()
        if isinstance(expires, datetime):
            expires = to_rfc822(expires).encode('ascii')
        cookie[b'expires'] = expires
    if httponly:
        cookie[b'httponly'] = True
    if path:
        cookie[b'path'] = path
    if gratipay.use_secure_cookies:
        cookie[b'secure'] = True
Esempio n. 2
0
def set_cookie(cookies, key, value, expires=None, httponly=True, path=b'/'):
    cookies[key] = value
    cookie = cookies[key]
    if expires:
        if isinstance(expires, timedelta):
            expires += utcnow()
        if isinstance(expires, datetime):
            expires = to_rfc822(expires).encode('ascii')
        cookie[b'expires'] = expires
    if httponly:
        cookie[b'httponly'] = True
    if path:
        cookie[b'path'] = path
    if gratipay.canonical_scheme == 'https':
        cookie[b'secure'] = True
Esempio n. 3
0
def outbound(response):
    """Set outbound auth cookie.
    """
    if 'user' not in response.request.context:
        # XXX When does this happen? When auth.inbound_early hasn't run, eh?
        raise  # XXX raise what?

    user = response.request.context['user']
    if not isinstance(user, auth.User):
        raise Exception("If you define 'user' in a simplate it has to be an "
                        "instance of an aspen.auth.User.")

    if NAME not in response.request.headers.cookie:
        # no cookie in the request, don't set one on response
        return
    elif user.ANON:
        # user is anonymous, instruct browser to delete any auth cookie
        cookie_value = ''
        cookie_expires = THE_PAST
    else:
        # user is authenticated, keep it rolling for them
        cookie_value = user.token
        cookie_expires = to_rfc822(utcnow() + TIMEOUT)


    # Configure outgoing cookie.
    # ==========================

    response.headers.cookie[NAME] = cookie_value  # creates a cookie object?
    cookie = response.headers.cookie[NAME]          # loads a cookie object?

    cookie['expires'] = cookie_expires

    if DOMAIN is not None:
        # Browser default is the domain of the resource requested.
        # Aspen default is the browser default.
        cookie['domain'] = DOMAIN

    if PATH is not None:
        # XXX What's the browser default? Probably /? Or current dir?
        # Aspen default is "/".
        cookie['path'] = PATH

    if HTTPONLY is not None:
        # Browser default is to allow access from JavaScript.
        # Aspen default is to prevent access from JavaScript.
        cookie['httponly'] = HTTPONLY
Esempio n. 4
0
def set_cookie(cookies, key, value, expires=None, httponly=True, path='/'):
    cookies[key] = value
    cookie = cookies[key]
    if expires:
        if isinstance(expires, datetime):
            pass
        elif isinstance(expires, timedelta):
            expires += utcnow()
        else:
            raise TypeError('`expires` should be a `datetime` or `timedelta`')
        cookie['expires'] = str(to_rfc822(expires))
    if httponly:
        cookie['httponly'] = True
    if path:
        cookie['path'] = path
    if gittip.canonical_scheme == 'https':
        cookie['secure'] = True
Esempio n. 5
0
def set_cookie(cookies, key, value, expires=None, httponly=True, path=b'/'):
    cookies[key] = value
    cookie = cookies[key]
    if expires:
        if isinstance(expires, timedelta):
            expires += utcnow()
        if isinstance(expires, datetime):
            expires = to_rfc822(expires).encode('ascii')
        cookie[b'expires'] = expires
    if httponly:
        cookie[b'httponly'] = True
    if path:
        cookie[b'path'] = path
    if website.canonical_domain:
        cookie[b'domain'] = website.canonical_domain
    if website.canonical_scheme == 'https':
        cookie[b'secure'] = True
Esempio n. 6
0
def set_cookie(cookies, key, value, expires=None, httponly=True, path='/'):
    cookies[key] = value
    cookie = cookies[key]
    if expires:
        if isinstance(expires, datetime):
            pass
        elif isinstance(expires, timedelta):
            expires += utcnow()
        else:
            raise TypeError('`expires` should be a `datetime` or `timedelta`')
        cookie['expires'] = str(to_rfc822(expires))
    if httponly:
        cookie['httponly'] = True
    if path:
        cookie['path'] = path
    if gratipay.canonical_scheme == 'https':
        cookie['secure'] = True
Esempio n. 7
0
def set_cookie(cookies, key, value, expires=None, httponly=True, path="/"):
    cookies[key] = value
    cookie = cookies[key]
    if expires:
        if isinstance(expires, datetime):
            pass
        elif isinstance(expires, timedelta):
            expires += utcnow()
        else:
            raise TypeError("`expires` should be a `datetime` or `timedelta`")
        cookie["expires"] = str(to_rfc822(expires))
    if httponly:
        cookie["httponly"] = True
    if path:
        cookie["path"] = path
    if gratipay.canonical_scheme == "https":
        cookie["secure"] = True
Esempio n. 8
0
# encoding: utf8

from __future__ import absolute_import, division, print_function, unicode_literals

from datetime import datetime, timedelta

from aspen import Response, json
from aspen.utils import to_rfc822, utcnow
from dependency_injection import resolve_dependencies
from postgres.cursors import SimpleCursorBase

import gratipay


BEGINNING_OF_EPOCH = to_rfc822(datetime(1970, 1, 1)).encode('ascii')

# Difference between current time and credit card expiring date when
# card is considered as expiring
EXPIRING_DELTA = timedelta(days = 30)


def dict_to_querystring(mapping):
    if not mapping:
        return u''

    arguments = []
    for key, values in mapping.iteritems():
        for val in values:
            arguments.append(u'='.join([key, val]))

    return u'?' + u'&'.join(arguments)
Esempio n. 9
0
+++++++++++++
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import datetime
import os

from algorithm import Algorithm
from aspen.configuration import Configurable
from aspen.utils import to_rfc822, utc

# 2006-11-17 was the first release of aspen - v0.3
THE_PAST = to_rfc822(datetime.datetime(2006, 11, 17, tzinfo=utc))


class Website(Configurable):
    """Represent a website.

    This object holds configuration information, and also knows how to start
    and stop a server, *and* how to handle HTTP requests (per WSGI). It is
    available to user-developers inside of their simplates and hooks.

    """

    def __init__(self, argv=None, server_algorithm=None):
        """Takes an argv list, without the initial executable name.
        """
        self.server_algorithm = server_algorithm
Esempio n. 10
0
"""Defines website authentication helpers.
"""
from datetime import datetime

from aspen.utils import to_rfc822
from gratipay.security import csrf
from gratipay.security.user import User, SESSION

BEGINNING_OF_EPOCH = to_rfc822(datetime(1970, 1, 1))


def get_auth_from_request(request):
    """Authenticate from a cookie or an API key in basic auth.
    """
    user = None
    if request.line.uri.startswith('/assets/'):
        pass
    elif 'Authorization' in request.headers:
        header = request.headers['authorization']
        if header.startswith('Basic '):
            creds = header[len('Basic '):].decode('base64')
            token, ignored = creds.split(':')
            user = User.from_api_key(token)

            # We don't require CSRF if they basically authenticated.
            csrf_token = csrf._get_new_csrf_key()
            request.headers.cookie['csrf_token'] = csrf_token
            request.headers['X-CSRF-TOKEN'] = csrf_token
            if 'Referer' not in request.headers:
                request.headers['Referer'] = \
                                        'https://%s/' % csrf._get_host(request)
Esempio n. 11
0
# encoding: utf8
from __future__ import absolute_import, division, print_function, unicode_literals

import fnmatch
import random
import os
from base64 import urlsafe_b64encode, urlsafe_b64decode
from datetime import datetime, timedelta

from aspen import Response, json
from aspen.utils import to_rfc822, utcnow
from postgres.cursors import SimpleCursorBase

import gratipay

BEGINNING_OF_EPOCH = to_rfc822(datetime(1970, 1, 1)).encode('ascii')

# Difference between current time and credit card expiring date when
# card is considered as expiring
EXPIRING_DELTA = timedelta(days=30)


def dict_to_querystring(mapping):
    if not mapping:
        return u''

    arguments = []
    for key, values in mapping.iteritems():
        for val in values:
            arguments.append(u'='.join([key, val]))
Esempio n. 12
0
def test_to_rfc822():
    expected = 'Thu, 01 Jan 1970 00:00:00 GMT'
    actual = to_rfc822(datetime(1970, 1, 1))
    assert actual == expected
Esempio n. 13
0
"""Defines website authentication helpers.
"""
from datetime import datetime

from aspen.utils import to_rfc822
from gratipay.security import csrf
from gratipay.security.user import User, SESSION

BEGINNING_OF_EPOCH = to_rfc822(datetime(1970, 1, 1))

def get_auth_from_request(request):
    """Authenticate from a cookie or an API key in basic auth.
    """
    user = None
    if request.line.uri.startswith('/assets/'):
        pass
    elif 'Authorization' in request.headers:
        header = request.headers['authorization']
        if header.startswith('Basic '):
            creds = header[len('Basic '):].decode('base64')
            token, ignored = creds.split(':')
            user = User.from_api_key(token)

            # We don't require CSRF if they basically authenticated.
            csrf_token = csrf._get_new_csrf_key()
            request.headers.cookie['csrf_token'] = csrf_token
            request.headers['X-CSRF-TOKEN'] = csrf_token
            if 'Referer' not in request.headers:
                request.headers['Referer'] = \
                                        'https://%s/' % csrf._get_host(request)
    elif SESSION in request.headers.cookie:
Esempio n. 14
0
import datetime
import os
import sys
import traceback
from os.path import join, isfile

import aspen
from aspen import gauntlet, resources, sockets
from aspen.http.request import Request
from aspen.http.response import Response
from aspen.configuration import Configurable
from aspen.utils import to_rfc822, utc


THE_PAST = to_rfc822(datetime.datetime(1955, 11, 05, tzinfo=utc))


class Website(Configurable):
    """Represent a website.

    This object holds configuration information, and also knows how to start
    and stop a server, *and* how to handle HTTP requests (per WSGI). It is
    available to user-developers inside of their resources and hooks.

    """

    def __init__(self, argv=None):
        """Takes an argv list, without the initial executable name.
        """
        self.configure(argv)
Esempio n. 15
0
import datetime
import os
import sys
import traceback
from os.path import join, isfile
from first import first

import aspen
from aspen import dispatcher, resources, sockets
from aspen.http.request import Request
from aspen.http.response import Response
from aspen.configuration import Configurable
from aspen.utils import to_rfc822, utc

# 2006-11-17 was the first release of aspen - v0.3
THE_PAST = to_rfc822(datetime.datetime(2006, 11, 17, tzinfo=utc))


class Website(Configurable):
    """Represent a website.

    This object holds configuration information, and also knows how to start
    and stop a server, *and* how to handle HTTP requests (per WSGI). It is
    available to user-developers inside of their resources and hooks.

    """

    def __init__(self, argv=None):
        """Takes an argv list, without the initial executable name.
        """
        self.configure(argv)