Esempio n. 1
0
def get_or_create_csrf_token(request):
	token = request.META.get('CSRF_COOKIE', None)
	if token is None:
		token = csrf._get_new_csrf_token()
		request.META['CSRF_COOKIE'] = token
	request.META['CSRF_COOKIE_USED'] = True
	return token
def test_deactivate_all_user_token_refresh_token(api_client, user_api_client,
                                                 customer_user):
    user_api_client.token = create_access_token(customer_user)
    create_refresh_token(customer_user)
    csrf_token = _get_new_csrf_token()
    refresh_token = create_refresh_token(customer_user,
                                         {"csrfToken": csrf_token})

    response = user_api_client.post_graphql(
        MUTATION_DEACTIVATE_ALL_USER_TOKENS)
    content = get_graphql_content(response)
    errors = content["data"]["tokensDeactivateAll"]["accountErrors"]
    assert not errors

    variables = {"token": refresh_token, "csrf_token": csrf_token}
    response = api_client.post_graphql(MUTATION_TOKEN_REFRESH, variables)
    content = get_graphql_content(response)

    data = content["data"]["tokenRefresh"]
    errors = data["accountErrors"]

    assert data["token"] is None
    assert len(errors) == 1

    assert errors[0]["code"] == AccountErrorCode.JWT_INVALID_TOKEN.name
    def test_post_form_session_auth_passing_csrf(self):
        """
        Ensure POSTing form over session authentication with CSRF token succeeds.
        Regression test for #6088
        """
        # Remove this shim when dropping support for Django 2.2.
        if django.VERSION < (3, 0):
            from django.middleware.csrf import _get_new_csrf_token
        else:
            from django.middleware.csrf import (
                _get_new_csrf_string, _mask_cipher_secret
            )

            def _get_new_csrf_token():
                return _mask_cipher_secret(_get_new_csrf_string())

        self.csrf_client.login(username=self.username, password=self.password)

        # Set the csrf_token cookie so that CsrfViewMiddleware._get_token() works
        token = _get_new_csrf_token()
        self.csrf_client.cookies[settings.CSRF_COOKIE_NAME] = token

        # Post the token matching the cookie value
        response = self.csrf_client.post('/session/', {
            'example': 'example',
            'csrfmiddlewaretoken': token,
        })
        assert response.status_code == status.HTTP_200_OK
Esempio n. 4
0
def before_request():
    # Reuse token if already set
    csrf_token = _get_token()
    if not csrf_token or g.get('csrf_cookie_needs_reset', False):
        csrf_token = _get_new_csrf_token()
    # Store csrf_token on g so that it can be used in
    # server-rendered forms
    g.csrf_token = csrf_token
Esempio n. 5
0
def before_request():
    # Reuse token if already set
    csrf_token = _get_token()
    if not csrf_token or g.get('csrf_cookie_needs_reset', False):
        csrf_token = _get_new_csrf_token()
    # Store csrf_token on g so that it can be used in
    # server-rendered forms
    g.csrf_token = csrf_token
Esempio n. 6
0
 def test_contributor_can_get_their_contribution(self):
     refresh_token = ContributorRefreshToken.for_contributor(
         self.contributor_user.uuid)
     self.client.cookies[
         "Authorization"] = refresh_token.long_lived_access_token
     self.client.cookies["csrftoken"] = csrf._get_new_csrf_token()
     my_contribution = self.contributor_user.contribution_set.first()
     self.assert_contributor_can_get(
         self.contribution_detail_url(my_contribution.pk))
Esempio n. 7
0
    def fake_request(self, path='/', user=None, method='GET', ajax=False, **kwargs):
        csrf = kwargs.get('csrf', django_csrf._get_new_csrf_token())

        request = WSGIRequest( { 'REQUEST_METHOD': method.upper(),
                                 'PATH_INFO': path,
                                 'wsgi.input': StringIO(),
                                 'CSRF_COOKIE': csrf,
                                 'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest' if ajax else None})
        request.user = AnonymousUser() if user is None else user
        return request
Esempio n. 8
0
 def test_contributor_cannot_get_others_contribution(self):
     refresh_token = ContributorRefreshToken.for_contributor(
         self.contributor_user.uuid)
     self.client.cookies[
         "Authorization"] = refresh_token.long_lived_access_token
     self.client.cookies["csrftoken"] = csrf._get_new_csrf_token()
     not_my_contribution = Contribution.objects.exclude(
         contributor=self.contributor_user).first()
     self.assert_contributor_cannot_get(
         self.contribution_detail_url(not_my_contribution.pk),
         expected_status_code=status.HTTP_404_NOT_FOUND)
Esempio n. 9
0
    def setUp(self):
        factory = RequestFactory(enforce_csrf_checks=True)
        self.request = factory.post(
            reverse("donationpage-detail", kwargs={"pk": 1}))
        self.user = user_model.objects.create_user(email="*****@*****.**",
                                                   password="******")
        self.request.user = self.user
        self.request._dont_enforce_csrf_checks = False

        valid_token_obj = AccessToken().for_user(self.user)
        self.valid_jwt = jwt.encode(valid_token_obj.payload,
                                    settings.SECRET_KEY,
                                    algorithm="HS256")
        self.invalid_jwt = "notavalidhmac"
        self.csrf_token = csrf._get_new_csrf_token()
Esempio n. 10
0
    def _login(self) -> Dict[str, str]:

        # Ideally, we'd migrate this to use API auth instead of
        # stealing cookies, but this works for now.
        auth_backend = settings.AUTHENTICATION_BACKENDS[0]
        session_auth_hash = self.user_profile.get_session_auth_hash()
        engine = import_module(settings.SESSION_ENGINE)
        session = engine.SessionStore()  # type: ignore # import_module
        session[SESSION_KEY] = self.user_profile._meta.pk.value_to_string(self.user_profile)
        session[BACKEND_SESSION_KEY] = auth_backend
        session[HASH_SESSION_KEY] = session_auth_hash
        session.save()
        return {
            settings.SESSION_COOKIE_NAME: session.session_key,
            settings.CSRF_COOKIE_NAME: _get_new_csrf_token()}
Esempio n. 11
0
def test_access_token_used_as_a_refresh_token(api_client, customer_user):
    csrf_token = _get_new_csrf_token()
    access_token = create_access_token(customer_user, {"csrfToken": csrf_token})

    variables = {"token": access_token, "csrf_token": csrf_token}
    response = api_client.post_graphql(MUTATION_TOKEN_REFRESH, variables)
    content = get_graphql_content(response)

    data = content["data"]["tokenRefresh"]
    errors = data["errors"]

    token = data.get("token")
    assert not token

    assert len(errors) == 1
    assert errors[0]["code"] == AccountErrorCode.JWT_INVALID_TOKEN.name
Esempio n. 12
0
 def perform_mutation(cls, root, info, **data):
     user = cls.get_user(info, data)
     access_token = create_access_token(user)
     csrf_token = _get_new_csrf_token()
     refresh_token = create_refresh_token(user, {"csrfToken": csrf_token})
     info.context.refresh_token = refresh_token
     info.context._cached_user = user
     user.last_login = timezone.now()
     user.save(update_fields=["last_login"])
     return cls(
         errors=[],
         user=user,
         token=access_token,
         refresh_token=refresh_token,
         csrf_token=csrf_token,
     )
Esempio n. 13
0
def test_refresh_token_get_token_incorrect_csrf_token(api_client, customer_user):
    csrf_token = _get_new_csrf_token()
    refresh_token = create_refresh_token(customer_user, {"csrfToken": csrf_token})
    variables = {"token": None, "csrf_token": "csrf_token"}
    api_client.cookies[JWT_REFRESH_TOKEN_COOKIE_NAME] = refresh_token
    api_client.cookies[JWT_REFRESH_TOKEN_COOKIE_NAME]["httponly"] = True
    response = api_client.post_graphql(MUTATION_TOKEN_REFRESH, variables)
    content = get_graphql_content(response)

    data = content["data"]["tokenRefresh"]
    errors = data["errors"]

    token = data.get("token")
    assert not token

    assert len(errors) == 1
    assert errors[0]["code"] == AccountErrorCode.JWT_INVALID_CSRF_TOKEN.name
Esempio n. 14
0
    def _login(self) -> Dict[str, str]:

        # Ideally, we'd migrate this to use API auth instead of
        # stealing cookies, but this works for now.
        auth_backend = settings.AUTHENTICATION_BACKENDS[0]
        session_auth_hash = self.user_profile.get_session_auth_hash()
        engine = import_module(settings.SESSION_ENGINE)
        session = engine.SessionStore()  # type: ignore # import_module
        session[SESSION_KEY] = self.user_profile._meta.pk.value_to_string(
            self.user_profile)
        session[BACKEND_SESSION_KEY] = auth_backend
        session[HASH_SESSION_KEY] = session_auth_hash
        session.save()
        return {
            settings.SESSION_COOKIE_NAME: session.session_key,
            settings.CSRF_COOKIE_NAME: _get_new_csrf_token()
        }
Esempio n. 15
0
def test_refresh_token_when_user_deactivated_token(api_client, customer_user):
    csrf_token = _get_new_csrf_token()
    refresh_token = create_refresh_token(customer_user, {"csrfToken": csrf_token})
    customer_user.jwt_token_key = "new_key"
    customer_user.save()
    variables = {"token": None, "csrf_token": csrf_token}
    api_client.cookies[JWT_REFRESH_TOKEN_COOKIE_NAME] = refresh_token
    api_client.cookies[JWT_REFRESH_TOKEN_COOKIE_NAME]["httponly"] = True

    response = api_client.post_graphql(MUTATION_TOKEN_REFRESH, variables)
    content = get_graphql_content(response)

    data = content["data"]["tokenRefresh"]
    errors = data["errors"]

    assert not data["token"]
    assert len(errors) == 1
    assert errors[0]["code"] == AccountErrorCode.JWT_INVALID_TOKEN.name
Esempio n. 16
0
def test_deactivate_all_user_tokens(customer_user, user_api_client):
    token = create_access_token(customer_user)
    jwt_key = customer_user.jwt_token_key

    csrf_token = _get_new_csrf_token()
    refresh_token = create_refresh_token(customer_user, {"csrfToken": csrf_token})

    user_api_client.token = token
    user_api_client.post_graphql(MUTATION_DEACTIVATE_ALL_USER_TOKENS)
    customer_user.refresh_from_db()

    new_token = create_access_token(customer_user)
    new_refresh_token = create_refresh_token(customer_user, {"csrfToken": csrf_token})
    # the mutation changes the parameter of jwt token, which confirms if jwt token is
    # valid or not
    assert jwt_decode(token)["token"] != jwt_decode(new_token)["token"]
    assert jwt_decode(refresh_token)["token"] != jwt_decode(new_refresh_token)["token"]
    assert jwt_key != customer_user.jwt_token_key
Esempio n. 17
0
    def test_post_form_session_auth_passing_csrf(self):
        """
        Ensure POSTing form over session authentication with CSRF token succeeds.
        Regression test for #6088
        """
        from django.middleware.csrf import _get_new_csrf_token

        self.csrf_client.login(username=self.username, password=self.password)

        # Set the csrf_token cookie so that CsrfViewMiddleware._get_token() works
        token = _get_new_csrf_token()
        self.csrf_client.cookies[settings.CSRF_COOKIE_NAME] = token

        # Post the token matching the cookie value
        response = self.csrf_client.post('/session/', {
            'example': 'example',
            'csrfmiddlewaretoken': token,
        })
        assert response.status_code == status.HTTP_200_OK
    def test_post_form_session_auth_passing_csrf(self):
        """
        Ensure POSTing form over session authentication with CSRF token succeeds.
        Regression test for #6088
        """
        from django.middleware.csrf import _get_new_csrf_token

        self.csrf_client.login(username=self.username, password=self.password)

        # Set the csrf_token cookie so that CsrfViewMiddleware._get_token() works
        token = _get_new_csrf_token()
        self.csrf_client.cookies[settings.CSRF_COOKIE_NAME] = token

        # Post the token matching the cookie value
        response = self.csrf_client.post('/session/', {
            'example': 'example',
            'csrfmiddlewaretoken': token,
        })
        assert response.status_code == status.HTTP_200_OK
Esempio n. 19
0
def test_create_token_sets_cookie(api_client, customer_user, settings, monkeypatch):
    csrf_token = _get_new_csrf_token()
    monkeypatch.setattr(
        "polygon.graphql.account.mutations.jwt._get_new_csrf_token", lambda: csrf_token
    )
    variables = {"email": customer_user.email, "password": customer_user._password}
    response = api_client.post_graphql(MUTATION_CREATE_TOKEN, variables)

    expected_refresh_token = create_refresh_token(
        customer_user, {"csrfToken": csrf_token}
    )
    refresh_token = response.cookies["refreshToken"]
    assert refresh_token.value == expected_refresh_token
    expected_expires = datetime.utcnow() + settings.JWT_TTL_REFRESH
    expected_expires += timedelta(seconds=1)
    expires = datetime.strptime(refresh_token["expires"], "%a, %d %b %Y  %H:%M:%S %Z")
    assert expires == expected_expires
    assert refresh_token["httponly"]
    assert refresh_token["secure"]
Esempio n. 20
0
def create_tokens_from_oauth_payload(
    token_data: dict,
    user: User,
    claims: CodeIDToken,
    permissions: Optional[List[str]],
    owner: str,
):
    refresh_token = token_data.get("refresh_token")
    access_token = token_data.get("access_token", "")

    tokens = {
        "token": create_jwt_token(claims, user, access_token, permissions,
                                  owner),
    }
    if refresh_token:
        csrf_token = _get_new_csrf_token()
        tokens["refresh_token"] = create_jwt_refresh_token(
            user, refresh_token, csrf_token, owner)
        tokens["csrf_token"] = csrf_token
    return tokens
Esempio n. 21
0
def test_refresh_token_get_token_from_input(api_client, customer_user,
                                            settings):
    csrf_token = _get_new_csrf_token()
    refresh_token = create_refresh_token(customer_user,
                                         {"csrfToken": csrf_token})
    variables = {"token": refresh_token, "csrf_token": None}
    response = api_client.post_graphql(MUTATION_TOKEN_REFRESH, variables)
    content = get_graphql_content(response)

    data = content["data"]["tokenRefresh"]
    errors = data["accountErrors"]

    assert not errors
    token = data.get("token")
    assert token
    payload = jwt_decode(token)
    assert payload["email"] == customer_user.email
    assert datetime.fromtimestamp(payload["iat"]) == datetime.utcnow()
    assert (datetime.fromtimestamp(payload["exp"]) == datetime.utcnow() +
            settings.JWT_TTL_ACCESS)
    assert payload["type"] == JWT_ACCESS_TYPE
Esempio n. 22
0
def test_refresh_token_when_expired(api_client, customer_user):
    with freeze_time("2018-05-31 12:00:01"):
        csrf_token = _get_new_csrf_token()
        refresh_token = create_refresh_token(customer_user, {"csrfToken": csrf_token})

    variables = {"token": None, "csrf_token": csrf_token}
    api_client.cookies[JWT_REFRESH_TOKEN_COOKIE_NAME] = refresh_token
    api_client.cookies[JWT_REFRESH_TOKEN_COOKIE_NAME]["httponly"] = True

    response = api_client.post_graphql(MUTATION_TOKEN_REFRESH, variables)

    content = get_graphql_content(response)

    data = content["data"]["tokenRefresh"]
    errors = data["errors"]

    token = data.get("token")
    assert not token

    assert len(errors) == 1
    assert errors[0]["code"] == AccountErrorCode.JWT_SIGNATURE_EXPIRED.name
Esempio n. 23
0
    def test_contributor_can_list_their_contributions(self):
        refresh_token = ContributorRefreshToken.for_contributor(
            self.contributor_user.uuid)
        self.client.cookies[
            "Authorization"] = refresh_token.long_lived_access_token
        self.client.cookies["csrftoken"] = csrf._get_new_csrf_token()

        def _ensure_all_contributions_belong_to_contributor(results):
            contribution_ids = [result["id"] for result in results]
            self.assertTrue(
                set(contribution_ids).issubset(
                    set(
                        self.contributor_user.contribution_set.values_list(
                            "id", flat=True))))

        expected_count = Contribution.objects.filter(
            contributor=self.contributor_user).count()
        self.assert_contributor_user_can_list(
            self.list_url,
            expected_count,
            assert_all=_ensure_all_contributions_belong_to_contributor)
Esempio n. 24
0
 def perform_mutation(cls, root, info, **data):
     zalouser = "******" % data['user']
     user = cls._retrieve_user_from_zalo_credentials(zalouser, data["zalotoken"])
     
     access_token = create_access_token(user)
     csrf_token = _get_new_csrf_token()
     refresh_token = create_refresh_token(user, {"csrfToken": csrf_token})
     info.context.refresh_token = refresh_token
     info.context._cached_user = user
     user.last_login = timezone.now()
     if user.pk is None:
         user.save()
     else:    
         user.save(update_fields=["last_login"])
     return cls(
         errors=[],
         user=user,
         token=access_token,
         refresh_token=refresh_token,
         csrf_token=csrf_token,
     )
Esempio n. 25
0
def test_refresh_token_get_token_from_cookie(api_client, customer_user,
                                             settings):
    csrf_token = _get_new_csrf_token()
    refresh_token = create_refresh_token(customer_user,
                                         {"csrfToken": csrf_token})
    variables = {"token": None, "csrf_token": csrf_token}
    api_client.cookies[JWT_REFRESH_TOKEN_COOKIE_NAME] = refresh_token
    api_client.cookies[JWT_REFRESH_TOKEN_COOKIE_NAME]["httponly"] = True
    response = api_client.post_graphql(MUTATION_TOKEN_REFRESH, variables)
    content = get_graphql_content(response)

    data = content["data"]["tokenRefresh"]
    errors = data["accountErrors"]

    assert not errors
    token = data.get("token")
    assert token
    payload = decode(token, settings.SECRET_KEY, algorithms=JWT_ALGORITHM)
    assert payload["email"] == customer_user.email
    assert datetime.fromtimestamp(payload["iat"]) == datetime.utcnow()
    assert (datetime.fromtimestamp(payload["exp"]) == datetime.utcnow() +
            settings.JWT_TTL_ACCESS)
    assert payload["type"] == JWT_ACCESS_TYPE
    assert payload["token"] == customer_user.jwt_token_key
Esempio n. 26
0
 def csrf_token(self):
     return str(csrf._get_new_csrf_token())
Esempio n. 27
0
from nose.tools import nottest

from .util import MinimalQuery, FakeChangeRecord
from ..models import SemanticField, SearchWord, Lexeme
from ..serializers import SemanticFieldSerializer
from lib import util
from lib.testutil import wipd

user_model = get_user_model()


def _make_test_url(sf):
    return "http://testserver" + sf.detail_url


FAKE_CSRF = _get_new_csrf_token()


class _Mixin(object):
    def setUp(self):
        super(_Mixin, self).setUp()
        translation.activate('en-us')

    # This exists so that we can use setUpTestData and setUp later.
    @classmethod
    def create_data_for(cls, whom):
        whom.noperm = user_model.objects.create(username="******", password="******")
        whom.perm = user_model.objects.create(username="******", password="******")
        whom.perm.user_permissions.add(
            Permission.objects.get(
                content_type=ContentType.objects.get_for_model(SemanticField),
Esempio n. 28
0
from django.middleware.csrf import _get_new_csrf_token
from cms.test_utils.testcases import BaseCMSTestCase
from nose.tools import nottest

from .util import MinimalQuery, FakeChangeRecord
from ..models import SemanticField, SearchWord, Lexeme
from ..serializers import SemanticFieldSerializer
from lib import util
from lib.testutil import wipd

user_model = get_user_model()

def _make_test_url(sf):
    return "http://testserver" + sf.detail_url

FAKE_CSRF = _get_new_csrf_token().encode("utf-8")

class _Mixin(object):

    def setUp(self):
        super(_Mixin, self).setUp()
        translation.activate('en-us')

    # This exists so that we can use setUpTestData and setUp later.
    @classmethod
    def create_data_for(cls, whom):
        whom.noperm = user_model.objects.create(username="******", password="******")
        whom.perm = user_model.objects.create(username="******", password="******")
        whom.perm.user_permissions.add(Permission.objects.get(
            content_type=ContentType.objects.get_for_model(SemanticField),
            codename="add_semanticfield"))
Esempio n. 29
0
def get_auth_token(request):
    new_auth_token = _get_new_csrf_token()
    new_user = UserTokens.create(new_auth_token)
    return ResponseModelJson.success(auth_tok=new_user.key)