@asgardeo/express
Version:
Express.js implementation of Asgardeo JavaScript SDK.
271 lines (262 loc) • 8.9 kB
JavaScript
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
// src/__legacy__/client.ts
import {
LegacyAsgardeoNodeClient,
AsgardeoAuthException as AsgardeoAuthException2,
Logger as Logger3
} from "@asgardeo/node";
// src/__legacy__/constants/default-options.ts
var DEFAULT_LOGIN_PATH = "/login";
var DEFAULT_LOGOUT_PATH = "/logout";
// src/__legacy__/client.ts
import { v4 as uuidv4 } from "uuid";
// src/__legacy__/middleware/protect-route.ts
import { Logger } from "@asgardeo/node";
var protectRoute = (asgardeoExpressClient, callback) => {
return async (req, res, next) => {
if (req.cookies.ASGARDEO_SESSION_ID === void 0) {
Logger.error("No session ID found in the request cookies");
if (callback(res, "Unauthenticated")) {
return;
}
return next();
} else {
const isCookieValid = await asgardeoExpressClient.isSignedIn(req.cookies.ASGARDEO_SESSION_ID);
if (isCookieValid) {
return next();
} else {
Logger.error("Invalid session ID found in the request cookies");
if (callback(res, "Invalid session cookie")) {
return;
}
return next();
}
}
};
};
// src/__legacy__/middleware/authentication.ts
import { AsgardeoAuthException, Logger as Logger2 } from "@asgardeo/node";
import express from "express";
var asgardeoExpressAuth = (asgardeoExpressClient, config, onSignIn, onSignOut, onError) => {
const router = new express.Router();
router.use(async (req, res, next) => {
req.asgardeoAuth = asgardeoExpressClient;
res.asgardeoAuth = asgardeoExpressClient;
next();
});
router.get(
config.loginPath || DEFAULT_LOGIN_PATH,
async (req, res, next) => {
try {
const response = await asgardeoExpressClient.signIn(req, res, next, config.signInConfig);
if (response.accessToken || response.idToken) {
onSignIn(res, response);
}
} catch (e) {
Logger2.error(e.message);
onError(res, e);
}
}
);
router.get(
config.logoutPath || DEFAULT_LOGOUT_PATH,
async (req, res, next) => {
if (req.query.state === "sign_out_success") {
onSignOut(res);
return;
}
if (req.cookies.ASGARDEO_SESSION_ID === void 0) {
onError(
res,
new AsgardeoAuthException(
"EXPRESS-AUTH_MW-LOGOUT-NF01",
"No cookie found in the request",
"No cookie was sent with the request. The user may not have signed in yet."
)
);
return;
} else {
try {
const signOutURL = await req.asgardeoAuth.signOut(req.cookies.ASGARDEO_SESSION_ID);
if (signOutURL) {
res.cookie("ASGARDEO_SESSION_ID", null, { maxAge: 0 });
res.redirect(signOutURL);
return;
}
} catch (e) {
onError(res, e);
return;
}
}
}
);
return router;
};
// src/__legacy__/utils/express-utils.ts
var ExpressUtils = class {
/**
* Util function to check if the URL contains an error.
*
* @param url - URL to be checked.
*
* @returns {boolean} - True if the URL contains an error.
*/
static hasErrorInURL(url) {
return this.AUTH_CODE_REGEXP.test(url);
}
};
__publicField(ExpressUtils, "AUTH_CODE_REGEXP", /[?&]error=[^&]+/);
// src/__legacy__/client.ts
var _AsgardeoExpressClient = class _AsgardeoExpressClient {
constructor(config, storage) {
__publicField(this, "_authClient");
__publicField(this, "_storage");
_AsgardeoExpressClient._clientConfig = { ...config };
const nodeClientConfig = {
...config,
afterSignInUrl: config.appURL + (config.loginPath || DEFAULT_LOGIN_PATH),
afterSignOutUrl: config.appURL + (config.logoutPath || DEFAULT_LOGOUT_PATH)
};
if (storage) {
Logger3.debug("Initializing user provided storage");
this._storage = storage;
}
this._authClient = new LegacyAsgardeoNodeClient();
this._authClient.initialize(nodeClientConfig, this._storage);
}
static getInstance(config, storage) {
if (!_AsgardeoExpressClient._instance && config) {
_AsgardeoExpressClient._instance = new _AsgardeoExpressClient(config, storage);
Logger3.debug("Initialized AsgardeoExpressClient successfully");
}
if (!_AsgardeoExpressClient._instance && !config) {
throw Error(
new AsgardeoAuthException2(
"EXPRESS-CLIENT-GI1-NF01",
"User configuration is not found",
"User config has not been passed to initialize AsgardeoExpressClient"
).toString()
);
}
return _AsgardeoExpressClient._instance;
}
async signIn(req, res, next, signInConfig) {
if (ExpressUtils.hasErrorInURL(req.originalUrl)) {
return Promise.reject(
new AsgardeoAuthException2(
"EXPRESS-CLIENT-SI-IV01",
"Invalid login request URL",
"Login request contains an error query parameter in the URL"
)
);
}
let userId = req.cookies.ASGARDEO_SESSION_ID;
if (!userId) {
userId = uuidv4();
}
const authRedirectCallback = (url) => {
if (url) {
Logger3.debug("Redirecting to: " + url);
res.cookie("ASGARDEO_SESSION_ID", userId, {
maxAge: _AsgardeoExpressClient._clientConfig.cookieConfig?.maxAge ? _AsgardeoExpressClient._clientConfig.cookieConfig.maxAge : 9e4 /* defaultMaxAge */,
httpOnly: _AsgardeoExpressClient._clientConfig.cookieConfig?.httpOnly ?? "true" /* defaultHttpOnly */,
sameSite: _AsgardeoExpressClient._clientConfig.cookieConfig?.sameSite ?? "lax" /* defaultSameSite */,
secure: _AsgardeoExpressClient._clientConfig.cookieConfig?.secure ?? "false" /* defaultSecure */
});
res.redirect(url);
next && typeof next === "function" && next();
}
};
const authResponse = await this._authClient.signIn(
authRedirectCallback,
userId,
req.query.code,
req.query.session_state,
req.query.state,
signInConfig
);
if (authResponse.accessToken || authResponse.idToken) {
return authResponse;
} else {
return {
accessToken: "",
createdAt: 0,
expiresIn: "",
idToken: "",
refreshToken: "",
scope: "",
tokenType: ""
};
}
}
async signOut(userId) {
return this._authClient.signOut(userId);
}
async isSignedIn(userId) {
return this._authClient.isSignedIn(userId);
}
async getIdToken(userId) {
return this._authClient.getIdToken(userId);
}
async getUser(userId) {
return this._authClient.getUser(userId);
}
async getOpenIDProviderEndpoints() {
return this._authClient.getOpenIDProviderEndpoints();
}
async getDecodedIdToken(userId) {
return this._authClient.getDecodedIdToken(userId);
}
async getAccessToken(userId) {
return this._authClient.getAccessToken(userId);
}
async exchangeToken(config, userId) {
return this._authClient.exchangeToken(config, userId);
}
async reInitialize(config) {
return this._authClient.reInitialize(config);
}
async revokeAccessToken(userId) {
return this._authClient.revokeAccessToken(userId);
}
static didSignOutFail(afterSignOutUrl) {
return LegacyAsgardeoNodeClient.didSignOutFail(afterSignOutUrl);
}
static isSignOutSuccessful(afterSignOutUrl) {
return LegacyAsgardeoNodeClient.isSignOutSuccessful(afterSignOutUrl);
}
static protectRoute(callback) {
if (!this._instance) {
throw new AsgardeoAuthException2(
"EXPRESS-CLIENT-PR-NF01",
"AsgardeoExpressClient is not instantiated",
"Create an instance of AsgardeoExpressClient before using calling this method."
);
}
return protectRoute(this._instance, callback);
}
static asgardeoExpressAuth(onSignIn, onSignOut, onError) {
if (!this._instance) {
throw new AsgardeoAuthException2(
"EXPRESS-CLIENT-AEA-NF01",
"AsgardeoExpressClient is not instantiated",
"Create an instance of AsgardeoExpressClient before using calling this method."
);
}
return asgardeoExpressAuth(this._instance, _AsgardeoExpressClient._clientConfig, onSignIn, onSignOut, onError);
}
async getStorageManager() {
return this._authClient.getStorageManager();
}
};
__publicField(_AsgardeoExpressClient, "_clientConfig");
__publicField(_AsgardeoExpressClient, "_instance");
var AsgardeoExpressClient = _AsgardeoExpressClient;
// src/index.ts
export * from "@asgardeo/node";
export {
AsgardeoExpressClient
};
//# sourceMappingURL=index.js.map