Exemplo n.º 1
0
    def has_permission(self, request, view):
        payload = getattr(request, "jwt_payload", None)
        if not payload:
            payload = get_jwt_payload(get_jwt_from_request(request))

        if not payload:
            return False

        get_scopes_from_payload = get_imported_setting(
            "GET_SCOPES_FROM_PAYLOAD_HANDLER")
        payload_scopes = get_scopes_from_payload(payload)
        role = get_role_for(request.method.lower(),
                            getattr(view, "action", None))
        scope = get_view_role(view, role)
        return scope in payload_scopes
def test_api_scope_permissions(admin_user, authenticated):
    shop = factories.get_default_shop()
    api_access_permission = APIScopePermission()
    factory = APIRequestFactory()

    user = admin_user if authenticated else AnonymousUser()

    def get_request_view(jwt, shop):
        request = factory.get('/api/shuup/shop/')
        request.META["HTTP_AUTHORIZATION"] = "JWT %s" % jwt
        request.shop = shop
        request.user = user
        view = ShopViewSet(action="list", method="get")
        return request, view

    # no API Key
    jwt = jwt_encode_handler({})
    request, view = get_request_view(jwt, shop)
    assert api_access_permission.has_permission(request, view) is False

    # no scopes for anonymous user
    api_access = create_random_api_access()
    payload = jwt_payload_handler(user, api_access, shop=shop)
    assert payload["scopes"] == []
    request, view = get_request_view(jwt_encode_handler(payload), shop)
    assert api_access_permission.has_permission(request, view) is False

    # add the permission for ShopViewSet.list on anonymous, OK
    api_access = create_random_api_access(enabled=False)
    scope = get_view_role(ShopViewSet, get_role_for("get", "list"))

    permission = APIPermissionScope.objects.get_or_create(identifier=scope)[0]
    if authenticated:
        group = Group.objects.create(name="g1")
        admin_user.groups.add(group)
        api_permission_groups = APIPermissionGroups.objects.create(
            name="schema 1")
        api_permission_groups.groups.add(group)
        api_permission_groups.permissions.add(permission)
        api_access.permissions_groups.add(api_permission_groups)
    else:
        api_access.anonymous_permissions.add(permission)

    payload = jwt_payload_handler(user, api_access, shop=shop)
    assert len(payload["scopes"]) == 1
    assert payload["scopes"][0] == scope
    request, view = get_request_view(jwt_encode_handler(payload), shop)
    assert api_access_permission.has_permission(request, view)
Exemplo n.º 3
0
def test_get_view_role():
    assert get_view_role(BasicView, "method1") == "{}:{}".format(
        slugify(BasicView.__name__), "method1")
    assert get_view_role(BasicView(), "method2") == "{}:{}".format(
        slugify(BasicView.__name__), "method2")

    assert get_view_role(ViewWithClassMethod, "method3") == "{}:{}".format(
        slugify("MyViewID_InClassMethod"), "method3")
    assert get_view_role(ViewWithClassMethod(), "method4") == "{}:{}".format(
        slugify("MyViewID_InClassMethod"), "method4")
    assert get_view_role(ViewWithInstanceMethod, "method5") == "{}:{}".format(
        slugify("MyViewID_InstanceMethod"), "method5")
    assert get_view_role(ViewWithInstanceMethod(),
                         "method6") == "{}:{}".format(
                             slugify("MyViewID_InstanceMethod"), "method6")

    assert get_view_role(ViewWithAnything, "method9") == "{}:{}".format(
        slugify(ViewWithAnything.__name__), "method9")
    assert get_view_role(ViewWithAnything(), "method10") == "{}:{}".format(
        slugify(ViewWithAnything.__name__), "method10")
def test_api_scope_permission_multiple_groups(admin_user):
    shop = factories.get_default_shop()
    api_access_permission = APIScopePermission()
    factory = APIRequestFactory()

    def get_request_view(jwt, shop):
        request = factory.get('/api/shuup/shop/')
        request.META["HTTP_AUTHORIZATION"] = "JWT %s" % jwt
        request.shop = shop
        request.user = admin_user
        view = ShopViewSet(action="list", method="get")
        return request, view

    api_access = create_random_api_access()

    scope = get_view_role(ShopViewSet, get_role_for("get", "list"))
    permission = APIPermissionScope.objects.get_or_create(identifier=scope)[0]

    group1 = Group.objects.create(name="g1")
    group2 = Group.objects.create(name="g2")

    admin_user.groups.add(group1)
    admin_user.groups.add(group2)

    api_permission_groups1 = APIPermissionGroups.objects.create(
        name="schema 1")
    api_permission_groups2 = APIPermissionGroups.objects.create(
        name="schema 2")

    api_permission_groups1.groups.add(group1)
    api_permission_groups2.groups.add(group2)

    # only add permission on group2
    api_permission_groups2.permissions.add(permission)

    api_access.permissions_groups.add(api_permission_groups1)
    api_access.permissions_groups.add(api_permission_groups2)

    payload = jwt_payload_handler(admin_user, api_access, shop=shop)
    assert len(payload["scopes"]) == 1
    assert payload["scopes"][0] == scope
    request, view = get_request_view(jwt_encode_handler(payload), shop)
    assert api_access_permission.has_permission(request, view)
Exemplo n.º 5
0
def test_open_api():
    """
    Test whether open API's (without authentication) can be accessed
    """
    shop = factories.get_default_shop()
    client = APIClient()

    response = client.get("/api/shuup/shop/%d/" % shop.id)
    assert response.status_code == status.HTTP_403_FORBIDDEN

    api_access = create_random_api_access()
    response = client.post("/api/auth/",
                           format="json",
                           data={
                               "api_key": api_access.key,
                               "api_secret": api_access.secret
                           })
    assert response.status_code == status.HTTP_200_OK
    jwt = response.data["token"]

    client.credentials(HTTP_AUTHORIZATION="JWT " + jwt)

    # no permission for shop API
    response = client.get("/api/shuup/shop/%d/" % shop.id)
    assert response.status_code == status.HTTP_401_UNAUTHORIZED

    # add permission for anonymous
    scope = get_view_role(ShopViewSet, get_role_for("get", "retrieve"))
    api_access.anonymous_permissions.add(
        APIPermissionScope.objects.get_or_create(identifier=scope)[0])

    # refresh the token to include the new permission
    response = client.post("/api/auth/refresh/",
                           format="json",
                           data={"token": jwt})
    assert response.status_code == status.HTTP_200_OK
    jwt = response.data["token"]
    client.credentials(HTTP_AUTHORIZATION="JWT " + jwt)

    response = client.get("/api/shuup/shop/%d/" % shop.id)
    assert response.status_code == status.HTTP_200_OK
    assert response.data["id"] == shop.id
Exemplo n.º 6
0
def test_api_token():
    """
    Test whether the API returns the access token correctly
    """
    shop = factories.get_default_shop()
    user = factories.create_random_user()
    password = "******"
    user.set_password(password)
    user.save()
    group = Group.objects.create(name="group 1")

    client = APIClient()

    api_access = create_random_api_access()
    # try logging without the api access credentials
    response = client.post("/api/auth/",
                           format="json",
                           data={
                               "username": user.username,
                               "password": password
                           })
    assert response.status_code == status.HTTP_400_BAD_REQUEST

    response = client.post("/api/auth/",
                           format="json",
                           data={
                               "username": user.username,
                               "password": password,
                               "api_key": api_access.key,
                               "api_secret": api_access.secret
                           })
    assert response.status_code == status.HTTP_200_OK
    jwt = response.data["token"]

    client.credentials(HTTP_AUTHORIZATION="JWT " + jwt)

    # add permission for the user group
    scope = get_view_role(FrontUserViewSet, get_role_for("get", "retrieve"))
    permission_groups = APIPermissionGroups.objects.create(
        name="special group")
    permission_groups.groups.add(group)
    permission_groups.permissions.add(
        APIPermissionScope.objects.get_or_create(identifier=scope)[0])
    user.groups.add(group)
    api_access.permissions_groups.add(permission_groups)

    # refresh the token to include the new permission
    response = client.post("/api/auth/refresh/",
                           format="json",
                           data={"token": jwt})
    assert response.status_code == status.HTTP_200_OK
    jwt = response.data["token"]
    client.credentials(HTTP_AUTHORIZATION="JWT " + jwt)

    # fetch user data
    response = client.get("/api/shuup/front/user/me/", format="json")
    assert response.status_code == status.HTTP_200_OK
    assert response.data["id"] == user.id

    # verify token
    client.credentials(HTTP_AUTHORIZATION="")
    response = client.post("/api/auth/verify/",
                           format="json",
                           data={"token": jwt})
    assert response.status_code == status.HTTP_200_OK

    # disable the key
    api_access.enabled = False
    api_access.save()

    client.credentials(HTTP_AUTHORIZATION="JWT " + jwt)
    response = client.get("/api/shuup/front/user/me/", format="json")
    assert response.status_code == status.HTTP_403_FORBIDDEN