Skip to content

Need way to call endpoints as admin, optionally masquerading as a given user #1009

Closed as not planned

Description

@lukehutch

Is your feature request related to a problem? Please describe.

I need a way to run a script to call endpoints as a user with admin role. The purpose of this is to automate the creation of test data in the database.

Describe the solution you'd like

I was going to create a new login method that allowed a user to log in as an admin if they provided the correct Postgres password to the server. Then they could call any API endpoint as an admin.

However, I think a better solution could probably be created. I need to be able to also call any endpoint as an admin, masquerading as any user (i.e. I would have to be logged in already, then I would supply an additional userId parameter to any endpoint request, to call that endpoint as that user.

This would be very helpful in unit testing too, by the way...

Describe alternatives you've considered

Writing direct to Postgres. However it is much better to go through the endpoints, to avoid duplicating that functionality, and to maximally exercise the endpoints.

Activity

  1. added
    enhancement
    on Jun 9, 2023
  2. lukehutch commented on Oct 2, 2023

    @lukehutch
    ContributorAuthor

    This is what I came up with for calling endpoints within the server. (This is a toplevel or static method. No auth is performed, I stripped that part out.) This really needs to be packaged up for shipping with Serverpod.

    Future<dynamic> callMethod(Serverpod pod, String endpointName,
        String methodName, Map<String, dynamic> paramMap) async {
      // Find correct connector
      var connector = pod.server.endpoints.getConnectorByName(endpointName);
      if (connector == null) {
        throw 'Endpoint $endpointName does not exist';
      }
      Session session = InternalSession(server: pod.server);
      try {
        var method = connector.methodConnectors[methodName];
        if (method == null) {
          throw 'Method $methodName not found';
        }
        return await method.call(session, paramMap);
      } finally {
        await session.close();
      }
    }
  3. lukehutch commented on Oct 6, 2023

    @lukehutch
    ContributorAuthor

    A quick snippet for calling an endpoint from within another endpoint:

    // result is null if endpoint or method wasn't found
    Future<dynamic>? result = session.server.endpoints
          .getConnectorByName(endpointName)
          ?.methodConnectors[methodName]
          ?.call(session, paramMap);

    However I'd much rather have available something like

    Future<MyReturnType> result = Endpoints.myEndpointName.myMethodName(session, myParams...);
  4. vlidholt commented on Oct 10, 2023

    @vlidholt
    Collaborator

    Yes, this would be a nice to have!

  5. lukehutch commented on Mar 12, 2024

    @lukehutch
    ContributorAuthor

    I'm getting around to creating unit tests for my server, because the complexity now is becoming too great to manually test everything (and in the long run, having unit tests will be critical).

    To revise what I was proposing above, I really need to be able to call endpoints on the server in exactly the same way as I call endpoints on the client. This is critical for easily developing unit tests that function the same way as code would function on the client. I would expect to be able to do something like:

    final client = ServersideClient(serverPodInstance: pod, asUserId: testUserId1);

    And then I would call an endpoint the same was as I do in the app:

    client.myEndpoint.myEndpointMethod(...)

    The current mechanism I am using to call endpoints, shown in previous comments, is prone to breakage, because no error is shown in the IDE if I rename a parameter of an endpoint method, etc. -- not to mention that it is a lot of complex boilerplate just to make a single API call. I also need to be able to set up a session as an user, by userId, mocking a user of that userId being logged in. Currently I have to set up an InternalSession and then manually call await session.auth.signInUser(userInfo.id!, 'server'). It would be nice to be able to just pass the asUserId param in to the client constructor, as shown above.

    Now that I'm getting around to writing unit tests, I would say that supporting this sort of ServersideClient should be high priority for Serverpod 2.0, because testing is so important, as you have stated with regards to your own development of Serverpod!

  6. SalahAnwer commented on Apr 2, 2024

    @SalahAnwer

    Can I just do this:

    class FirstEndpoint extends Endpoint {
      Future<String> getExample(Session session, String name) async {
        return 'Hello $name';
      }
    }
    
    extension SessionX on Session {
      FirstEndpoint get firstEndpoint {
        final firstEndpoint = (server.endpoints
            .getConnectorByName('FirstEndpoint')
            ?.endpoint as FirstEndpoint?);
        if (firstEndpoint == null) {
          throw Exception('FirstEndpoint not found');
        }
        return firstEndpoint;
      }
    }
    
    class SecondEndpoint extends Endpoint {
      Future<String> getExampleFromFirstEndpoint(
          Session session, String name) async {
        return session.firstEndpoint.getExample(session, name);
      }
    }
  7. SandPod commented on Aug 21, 2024

    @SandPod
    Contributor

    This should be possible with the server-side testing framework.

    It should be possible both to seed the database and to act as different users in the system when accessing endpoints.
    Closing as a subrequirement for #2494

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions