How to add custom logic to endpoints

Hello friends,

I am coming from Strapi CMS. I am new to cockpit and quite fascinated about the simple yet powerful features of cockpit. Can someone help me on

  1. How can I add custom logic to endpoints?
  2. How to access other endpoints from these custom logic?

Any help will be much appreciated. Somehow, the documentation of official site is very insufficient for newcomers.

I had the same issue with documentation, but managed to figure out a few things.

In the “Permissions” section of a collection, you can add code to run for that collection (Create, Read, Update, Delete)

You can also create your own public endpoints in config/api/public.

The rest I kind of patched together from examples on this forum, these docs and reading the source. Not ideal :frowning:

1 Like

Thanks a lot. Great help! Do you have any idea how to generate and validate JWT tokens (access token and refresh token for persistent login) using cockpit? I see some access tokens are generated on cockpit dashboard. what I want is as follows:

a user sends username and password to an end point, say, /api/auth/local/login

then the server sends back the JWT access token and a refresh token. Access token which will be used in the Beaerer token in header for authorising access.

Next, since JWT tokens have an expiry, a refresh token will be sent as http-cookie just before expiry to an endpoint, say, /api/auth/renew and in return a new JWT access token will be sent to client.

Any suggestions in this regard?

No problem!

I think you may want to look at the Javascript SDK? https://github.com/ginetta/cockpit-sdk

My method of client authentication goes something like this:

Create a “Custom API Key” at https://yoursite.com/restadmin/index with the only rule being: /api/cockpit/authUser

This key can be safely sent with your client-side code since all it can be used for is call the authUser endpoint.

const cockpit = new CockpitSDK.default({
    host: "https://yoursite.com",
    accessToken: "accesscodeyoujustgenerated"
})
const data = await cockpit.authUser("clientusername", "clientpassword")

I’m sure you could wrap this in a custom endpoint to generate JWT tokens, but can’t help with the specifics…

Another workaround I’ve seen is to expose a public endpoint that wraps the authUser call. You can do this by creating a file at config/public/api/auth.php with the following contents:

<?php
/**
 * Provide a public endpoint for authorizing a web app
 */
return $this->invoke('Cockpit\\Controller\\RestApi', 'authUser');

This may be a good starting point for wrapping the account info in a JWT token?