Beispiel #1
0
def csrf_validation(event):
    """ CSRF token validation Subscriber

        As of Pyramid 1.2a3, passing messages through HTTPForbidden broke,
        and don't appear to be exposed to exception handlers.

        It appears that we cannot decorate a view and have it affect an event
        until after the event has fired, so, temporarily we're going to
        have to use a value in the config to specify a list of paths that
        should not have CSRF validation.

        Ideally, we'll be able to do

        ::
            @no_csrf
            @view_config(route_name='test')
            def test(request):

        which would prevent CSRF tracking on that view. With the event hooks,
        our decorator is not read until AFTER the event, which makes this
        method fail at this point.

        Temporarily, we'll use a field in the development.ini:

        apex.no_csrf = routename1:routename2

    """
    if event.request.method == 'POST':
        token = event.request.POST.get('csrf_token') or event.request.GET.get('csrf_token')
        no_csrf = apex_settings('no_csrf', '').split(',')
        if (token is None or token != event.request.session.get_csrf_token()):
            if event.request.matched_route and event.request.matched_route.name not in no_csrf \
                and not event.request.matched_route.name.startswith('debugtoolbar.'):
                    raise HTTPForbidden(_('CSRF token is missing or invalid'))
Beispiel #2
0
def csrf_validation(event):
    """ CSRF token validation Subscriber

        As of Pyramid 1.2a3, passing messages through HTTPForbidden broke,
        and don't appear to be exposed to exception handlers.

        It appears that we cannot decorate a view and have it affect an event
        until after the event has fired, so, temporarily we're going to
        have to use a value in the config to specify a list of paths that
        should not have CSRF validation.

        Ideally, we'll be able to do

        ::
            @no_csrf
            @view_config(route_name='test')
            def test(request):

        which would prevent CSRF tracking on that view. With the event hooks,
        our decorator is not read until AFTER the event, which makes this
        method fail at this point.

        Temporarily, we'll use a field in the development.ini:

        apex.no_csrf = routename1:routename2

    """
    if event.request.method == 'POST':
        token = event.request.POST.get('csrf_token') or event.request.GET.get('csrf_token')
        no_csrf = apex_settings('no_csrf', '').split(':')
        if (token is None or token != event.request.session.get_csrf_token()):
            if event.request.matched_route and event.request.matched_route.name not in no_csrf:
                raise HTTPForbidden(_('CSRF token is missing or invalid'))
Beispiel #3
0
def csrf_validation(event):
    """ CSRF token validation Subscriber

        As of Pyramid 1.2a3, passing messages through HTTPForbidden broke,
        and don't appear to be exposed to exception handlers.

        It appears that we cannot decorate a view and have it affect an event
        until after the event has fired, so, temporarily we're going to
        have to use a value in the config to specify a list of paths that
        should not have CSRF validation.

        Ideally, we'll be able to do

        ::
            @no_csrf
            @view_config(route_name='test')
            def test(request):

        which would prevent CSRF tracking on that view. With the event hooks,
        our decorator is not read until AFTER the event, which makes this
        method fail at this point.

        Temporarily, we'll use a field in the development.ini:

        apex.no_csrf = routename1:routename2

        Disabled apex CSRF (20121118) - CSRF token not being passed
        through new Velruse

    """
    #import pdb; pdb.set_trace()
    if event.request.method == 'POST':
        # will never hit GET
        token = event.request.POST.get('csrf_token') \
            or event.request.GET.get('csrf_token') \
            or event.request.headers.get('X-CSRF-Token')
    #       or event.request.json_body.get('csrf_token') \

        no_csrf = apex_settings('no_csrf', '').split(',')
        if (token is None or token != event.request.session.get_csrf_token()):
            if event.request.matched_route and \
                event.request.matched_route.name not in no_csrf \
                and not event.request.matched_route.name.startswith('debugtoolbar.') \
                and not event.request.matched_route.name.startswith('apex_'):
                    log.debug('apex: CSRF token received %s didn\'t match %s' % \
                        (token, event.request.session.get_csrf_token()))
                    raise HTTPForbidden(_('CSRF token is missing or invalid'))
Beispiel #4
0
def csrf_validation(event):
    """ CSRF token validation Subscriber

        As of Pyramid 1.2a3, passing messages through HTTPForbidden broke,
        and don't appear to be exposed to exception handlers.

        It appears that we cannot decorate a view and have it affect an event
        until after the event has fired, so, temporarily we're going to
        have to use a value in the config to specify a list of paths that
        should not have CSRF validation.

        Ideally, we'll be able to do

        ::
            @no_csrf
            @view_config(route_name='test')
            def test(request):

        which would prevent CSRF tracking on that view. With the event hooks,
        our decorator is not read until AFTER the event, which makes this
        method fail at this point.

        Temporarily, we'll use a field in the development.ini:

        apex.no_csrf = routename1:routename2

        Disabled apex CSRF (20121118) - CSRF token not being passed 
        through new Velruse

    """
    if event.request.method == 'POST':
        # will never hit GET
        token = event.request.POST.get('csrf_token') \
            or event.request.GET.get('csrf_token') \
            or event.request.json_body.get('csrf_token') \
            or event.request.headers.get('X-CSRF-Token')

        no_csrf = apex_settings('no_csrf', '').split(',')
        if (token is None or token != event.request.session.get_csrf_token()):
            if event.request.matched_route and \
                event.request.matched_route.name not in no_csrf \
                and not event.request.matched_route.name.startswith('debugtoolbar.') \
                and not event.request.matched_route.name.startswith('apex_'):
                log.debug('apex: CSRF token received %s didn\'t match %s' % \
                    (token, event.request.session.get_csrf_token()))
                raise HTTPForbidden(_('CSRF token is missing or invalid'))
Beispiel #5
0
def create_user(**kwargs):
    """
::

    from apex.lib.libapex import create_user
    create_user(username='******', password='******', active='Y', group='group')
    Returns: AuthUser object
    """
    request = get_current_request()
    registry = get_current_registry()
    if 'registry' in kwargs:
        registry = kwargs['registry']
        del kwargs['registry']
    settings = registry.settings
    # map default groups
    groups = []
    if settings.has_key('apex.default_user_group'):
        group = DBSession.query(AuthGroup).filter(
            AuthGroup.name==settings['apex.default_user_group']).one()
        if not group in groups:
            groups.append(group)
    # add user to users groups
    qgroup = DBSession.query(AuthGroup).filter(
        AuthGroup.name=='users').first()
    if qgroup:
        if not qgroup in groups:
            groups.append(qgroup)
    # extra kw group
    if 'group' in kwargs:
        try:
            group = DBSession.query(AuthGroup).filter(
                AuthGroup.name==kwargs['group']).one()
            groups.append(group)
        except NoResultFound:
            pass
        del kwargs['group']
    # extra kw groups splitted on ','
    if 'groups' in kwargs:
        try:
            sgroups = kwargs['groups'].split(',')
            qgroups= DBSession.query(AuthGroup).filter(
                AuthGroup.name.in_(sgroups)).all()
            for group in qgroups:
                if not group in groups:
                    groups.append(group)
        except NoResultFound:
            pass
        del kwargs['groups']
    # register user
    user = AuthUser()
    for key, value in kwargs.items():
        setattr(user, key, value)
    DBSession.add(user)
    try:
        transaction.commit()
        DBSession.add(user)
        # link groups
        for group in groups:
            try:
                user.groups.append(group)
                transaction.commit()
            except Exception, e:
                error = _('Cant add user :%s to group: %s (%s)') % (user, group, e)
                logging.getLogger('apex.add_user_to_group').error(error)
                request.session.flash(error, 'error')
        transaction.commit()
        DBSession.add(user)
        # when request is not available fake it a bit
        class obj(object): pass
        class session:
            def flash(self, *args, **kwargs):pass
        obj.registry = registry
        obj.session = session()
        if request is None:
            request = obj()
        registry.notify(UserCreatedEvent(request, user))
        transaction.commit()
        DBSession.add(user)
Beispiel #6
0
def create_user(**kwargs):
    """
::

    from apex.lib.libapex import create_user
    create_user(username='******', password='******', active='Y', group='group')
    Returns: AuthUser object
    """
    request = get_current_request()
    registry = get_current_registry()
    if 'registry' in kwargs:
        registry = kwargs['registry']
        del kwargs['registry']
    settings = registry.settings
    # map default groups
    groups = []
    if settings.has_key('apex.default_user_group'):
        group = DBSession.query(AuthGroup).filter(
            AuthGroup.name == settings['apex.default_user_group']).one()
        if not group in groups:
            groups.append(group)
    # add user to users groups
    qgroup = DBSession.query(AuthGroup).filter(
        AuthGroup.name == 'users').first()
    if qgroup:
        if not qgroup in groups:
            groups.append(qgroup)
    # extra kw group
    if 'group' in kwargs:
        try:
            group = DBSession.query(AuthGroup).filter(
                AuthGroup.name == kwargs['group']).one()
            groups.append(group)
        except NoResultFound:
            pass
        del kwargs['group']
    # extra kw groups splitted on ','
    if 'groups' in kwargs:
        try:
            sgroups = kwargs['groups'].split(',')
            qgroups = DBSession.query(AuthGroup).filter(
                AuthGroup.name.in_(sgroups)).all()
            for group in qgroups:
                if not group in groups:
                    groups.append(group)
        except NoResultFound:
            pass
        del kwargs['groups']
    # register user
    user = AuthUser()
    for key, value in kwargs.items():
        setattr(user, key, value)
    DBSession.add(user)
    try:
        transaction.commit()
        DBSession.add(user)
        # link groups
        for group in groups:
            try:
                user.groups.append(group)
                transaction.commit()
            except Exception, e:
                error = _('Cant add user :%s to group: %s (%s)') % (user,
                                                                    group, e)
                logging.getLogger('apex.add_user_to_group').error(error)
                request.session.flash(error, 'error')
        transaction.commit()
        DBSession.add(user)

        # when request is not available fake it a bit
        class obj(object):
            pass

        class session:
            def flash(self, *args, **kwargs):
                pass

        obj.registry = registry
        obj.session = session()
        if request is None:
            request = obj()
        registry.notify(UserCreatedEvent(request, user))
        transaction.commit()
        DBSession.add(user)