Skip to main content

verfiyUserAPIKey

Use this to verify whether provided User API Key is valid and that it has not exceeded ratelimit.

Type signature of verifyUserAPIKey

async function verifyUserAPIKey(
userAPIKey: string,
endpointName: EndpointName,
variables?: Array<string>
): Promise<
| {
error: "authorizationHeaderNotPresent";
success: false;
reason: string;
}
| {
error: "apiTokenNotPresent";
success: false;
reason: string;
}
| {
error: "invalidAPIToken";
success: false;
reason: string;
}
| {
error: "invalidBody";
success: false;
reason: string;
}
| {
success: true;
keyValid: false;
ok: false;
}
| {
success: true;
keyValid: true;
ok: boolean;
remaining: number;
total: number;
reset: number;
}
>;

Parameters

Understanding variables

Lets say you are making todo list app and it has an api which allows users to get information about an task. It's url will be GET /api/v1/tasks/:id. It has ratelimit of 10 requests per 1min per id.

Which means user can make 10 requests to GET /api/v1/tasks/1 and 10 requests to GET /api/v1/tasks/2 in 1min. To model this use case we have use variables.

  1. First you will define endpoint in initKeyManager
import { initKeyManager } from "@niveth/key-manager";

export const { verifyUserAPIKey } = initKeyManager({
rootAPIKey: process.env.KEY_MANAGER_ROOT_KEY,
endpoints: {
GET_TASKS: {
default: { duration: 60_000, maxReq: 10 },
},
},
});
  1. Then you will pass id of task as an variable while calling verifyUserAPIKey
const res = await verifyUserAPIKey("user_xxx", "GET_TASKS", ["task_id"]);

if (res.success && res.ok) {
// Process the request
} else {
// Either ratelimit is passed or token is invalid check
// res.error more information
}

Should process request or not

To check whether to process request or not check success and ok key in return value of await verifyUserAPIKey

const res = await verifyUserAPIKey(...);

if (res.success && res.ok) {
// Process the request
} else if (res.success && !res.keyValid) {
// Provided user key is not valid
} else if (res.success && res.keyValid && !res.ok ) {
// Provided user key is valid but it exceeded ratelimit
} else if (!res.success) {
// verification failed with an error
}

How does key manager choose ratelimit

Once we have checked that User API Key is valid our next task is to figure out which ratelimit we should apply for User API Key, decision for this follows

  1. If User API Key roles is empty or does not match any roles in the definition of endpoint choose default ratelimit.
  2. If User API Key roles match only one roles of endpoint definition. Choose that role's ratelimit, even if it is lesser than default ratelimit.
  3. If User API Key roles match multiple roles of endpoint definition. Choose ratelimit which has higher maxReq / duration value even if it is lesser than default ratelimit.

Errors

If we are not able to verify User API Key, then verifyUserAPIKey will return an error. Check the Type signature for possible errors that can happen