@adonisjs/auth
Version:
Official authentication provider for Adonis framework
71 lines (70 loc) • 2.09 kB
JavaScript
import { t as debug_default } from "../../../debug-CrTUB4zl.js";
import { ApiClient, ApiRequest } from "@japa/api-client";
//#region src/plugins/japa/api_client.ts
/**
* Auth API client to authenticate users when making
* HTTP requests using the Japa API client
*
* @param app - The AdonisJS application service instance
*
* @example
* import { authApiClient } from '@adonisjs/auth/plugins/japa/api_client'
*
* export const plugins: PluginFn[] = [
* authApiClient(app)
* ]
*/
const authApiClient = (app) => {
const pluginFn = function() {
debug_default("installing auth api client plugin");
/**
* Login a user using the default authentication guard
* when making an API call
*/
ApiRequest.macro("loginAs", function(user, ...args) {
this.authData = {
guard: "__default__",
args: [user, ...args]
};
return this;
});
/**
* Define the authentication guard for login
*/
ApiRequest.macro("withGuard", function(guard) {
return { loginAs: (...args) => {
this.authData = {
guard,
args
};
return this;
} };
});
/**
* Hook into the request and login the user
*/
ApiClient.setup(async (request) => {
const auth = await app.container.make("auth.manager");
const authData = request["authData"];
if (!authData) return;
const client = auth.createAuthenticatorClient();
const requestData = await (authData.guard === "__default__" ? client.use() : client.use(authData.guard)).authenticateAsClient(...authData.args);
/* c8 ignore next 13 */
if (requestData.headers) {
debug_default("defining headers with api client request %O", requestData.headers);
request.headers(requestData.headers);
}
if (requestData.session) {
debug_default("defining session with api client request %O", requestData.session);
request.withSession(requestData.session);
}
if (requestData.cookies) {
debug_default("defining session with api client request %O", requestData.session);
request.cookies(requestData.cookies);
}
});
};
return pluginFn;
};
//#endregion
export { authApiClient };