Exemplo n.º 1
0
def test_get_request_user(dummy_user, mocker, monkeypatch):
    _lookup_request_user = mocker.patch('indico.web.util._lookup_request_user', return_value=(dummy_user, 'whatever'))
    monkeypatch.setattr('indico.web.util._check_request_user', lambda user, source: (user, source))
    assert get_request_user() == (dummy_user, 'whatever')
    _lookup_request_user.assert_called_once()
    assert get_request_user() == (dummy_user, 'whatever')
    assert _lookup_request_user.call_count == 2
Exemplo n.º 2
0
def test_get_request_user_lookup_failure(mocker, monkeypatch):
    _lookup_request_user = mocker.patch('indico.web.util._lookup_request_user', side_effect=Exception('kaboom'))
    monkeypatch.setattr('indico.web.util._check_request_user', lambda user, source: (user, source))
    with pytest.raises(Exception) as exc_info:
        get_request_user()
    assert str(exc_info.value) == 'kaboom'
    _lookup_request_user.assert_called_once()
    # after a failure, we always return None
    assert get_request_user() == (None, None)
    # the lookup should not be done again once a failure is cached
    _lookup_request_user.assert_called_once()
Exemplo n.º 3
0
def test_get_request_user_check_failure(dummy_user, mocker):
    _lookup_request_user = mocker.patch('indico.web.util._lookup_request_user', return_value=(dummy_user, 'whatever'))
    _check_request_user = mocker.patch('indico.web.util._check_request_user', side_effect=Exception('kaboom'))
    with pytest.raises(Exception) as exc_info:
        get_request_user()
    assert str(exc_info.value) == 'kaboom'
    _lookup_request_user.assert_called_once()
    _check_request_user.assert_called_once()
    # after a failure, we always return None
    assert get_request_user() == (None, None)
    # the lookup/check should not be done again once a failure is cached
    _lookup_request_user.assert_called_once()
    _check_request_user.assert_called_once()
Exemplo n.º 4
0
 def _check_csrf(self):
     if get_request_user()[1] in ('oauth', 'signed_url'):
         # no csrf checks needed since both of these auth methods require secrets
         # not available to a malicious site (and if they were, they wouldn't have
         # to use CSRF to abuse them)
         return
     token = request.headers.get('X-CSRF-Token') or request.form.get('csrf_token')
     if token is None:
         # Might be a WTForm with a prefix. In that case the field name is '<prefix>-csrf_token'
         token = next((v for k, v in request.form.items() if k.endswith('-csrf_token')), None)
     if self.CSRF_ENABLED and request.method != 'GET' and token != session.csrf_token:
         msg = _("It looks like there was a problem with your current session. Please use your browser's back "
                 "button, reload the page and try again.")
         raise BadRequest(msg)
Exemplo n.º 5
0
    def set_session_user(self, user):
        """Set the user logged in via this session."""
        if not current_app.testing:
            # Sanity check since logging in via the session during a request authenticated
            # via token/oauth never makes sense. Disabled during testing since we usually
            # know what we're doing there.
            current_user, source = get_request_user()
            if current_user is not None and source != 'session':
                raise Exception('Cannot set session user while authenticated using other means')

        if user is None:
            self.pop('_user_id', None)
        else:
            self['_user_id'] = user.id
        self._refresh_sid = True
Exemplo n.º 6
0
    def __init__(self, *args, **kwargs):
        csrf_enabled = kwargs.pop('csrf_enabled', None)
        if has_request_context() and get_request_user()[1] in ('oauth',
                                                               'signed_url'):
            # no csrf checks needed since oauth/token/signature auth requires a secret that's not available
            # to a malicious site, and even if it was, they wouldn't have to use CSRF to abuse it.
            csrf_enabled = False

        if csrf_enabled is not None:
            # This is exactly what FlaskForm already does, but without
            # a deprecation warning.
            # Being able to set ``csrf_enabled=False`` is much nicer
            # than ``meta={'csrf': False}`` and if we ever need to
            # change it for some reason we can always replace it everywhere
            kwargs['meta'] = kwargs.get('meta') or {}
            kwargs['meta'].setdefault('csrf', csrf_enabled)
        super().__init__(*args, **kwargs)
        self.ajax_response = None
Exemplo n.º 7
0
 def filter(self, record):
     user = get_request_user()[0] if has_request_context() else None
     record.user_id = str(session.user.id) if user else '-'
     return True
Exemplo n.º 8
0
 def _process(self):
     user, source = get_request_user()
     assert session.user == user
     if not user:
         return 'none'
     return f'{user.id}|{source}'
 def user(self):
     return get_request_user()[0]