fosrl.pangolin/server/routers/badger/verifySession.ts

286 lines
8.1 KiB
TypeScript
Raw Normal View History

import HttpCode from "@server/types/HttpCode";
import { NextFunction, Request, Response } from "express";
import createHttpError from "http-errors";
import { z } from "zod";
import { fromError } from "zod-validation-error";
import { response } from "@server/utils/response";
import { validateSessionToken } from "@server/auth";
import db from "@server/db";
import {
resourcePassword,
resourcePincode,
resources,
User,
2024-12-15 17:47:07 -05:00
userOrgs
} from "@server/db/schema";
import { and, eq } from "drizzle-orm";
import config from "@server/config";
import { validateResourceSessionToken } from "@server/auth/resource";
import { Resource, roleResources, userResources } from "@server/db/schema";
import logger from "@server/logger";
const verifyResourceSessionSchema = z.object({
sessions: z.record(z.string()).optional(),
originalRequestURL: z.string().url(),
scheme: z.string(),
host: z.string(),
path: z.string(),
method: z.string(),
2024-12-15 17:47:07 -05:00
tls: z.boolean()
});
export type VerifyResourceSessionSchema = z.infer<
typeof verifyResourceSessionSchema
>;
export type VerifyUserResponse = {
valid: boolean;
redirectUrl?: string;
};
export async function verifyResourceSession(
req: Request,
res: Response,
2024-12-15 17:47:07 -05:00
next: NextFunction
): Promise<any> {
logger.debug("Badger sent", req.body); // remove when done testing
const parsedBody = verifyResourceSessionSchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
2024-12-15 17:47:07 -05:00
fromError(parsedBody.error).toString()
)
);
}
try {
const { sessions, host, originalRequestURL } = parsedBody.data;
const [result] = await db
.select()
.from(resources)
.leftJoin(
resourcePincode,
2024-12-15 17:47:07 -05:00
eq(resourcePincode.resourceId, resources.resourceId)
)
.leftJoin(
resourcePassword,
2024-12-15 17:47:07 -05:00
eq(resourcePassword.resourceId, resources.resourceId)
)
.where(eq(resources.fullDomain, host))
.limit(1);
const resource = result?.resources;
const pincode = result?.resourcePincode;
const password = result?.resourcePassword;
if (!resource) {
2024-11-24 14:28:23 -05:00
logger.debug("Resource not found", host);
return notAllowed(res);
}
const { sso, blockAccess } = resource;
if (blockAccess) {
2024-11-24 14:28:23 -05:00
logger.debug("Resource blocked", host);
return notAllowed(res);
}
if (!resource.sso && !pincode && !password) {
2024-11-24 14:28:23 -05:00
logger.debug("Resource allowed because no auth");
return allowed(res);
}
2024-11-24 14:28:23 -05:00
const redirectUrl = `${config.app.base_url}/auth/resource/${encodeURIComponent(resource.resourceId)}?redirect=${encodeURIComponent(originalRequestURL)}`;
if (!sessions) {
return notAllowed(res);
}
const sessionToken = sessions[config.server.session_cookie_name];
// check for unified login
2024-12-15 17:47:07 -05:00
if (sso && sessionToken && !resource.otpEnabled) {
const { session, user } = await validateSessionToken(sessionToken);
if (session && user) {
const isAllowed = await isUserAllowedToAccessResource(
user,
2024-12-15 17:47:07 -05:00
resource
);
if (isAllowed) {
2024-11-24 14:28:23 -05:00
logger.debug(
2024-12-15 17:47:07 -05:00
"Resource allowed because user session is valid"
2024-11-24 14:28:23 -05:00
);
return allowed(res);
}
}
}
const resourceSessionToken =
sessions[
`${config.server.resource_session_cookie_name}_${resource.resourceId}`
];
2024-12-15 17:47:07 -05:00
if (
sso &&
sessionToken &&
resourceSessionToken &&
resource.otpEnabled
) {
const { session, user } = await validateSessionToken(sessionToken);
const { resourceSession } = await validateResourceSessionToken(
resourceSessionToken,
resource.resourceId
);
if (session && user && resourceSession) {
if (!resourceSession.usedOtp) {
logger.debug("Resource not allowed because OTP not used");
return notAllowed(res, redirectUrl);
}
const isAllowed = await isUserAllowedToAccessResource(
user,
resource
);
if (isAllowed) {
logger.debug(
"Resource allowed because user and resource session is valid"
);
return allowed(res);
}
}
}
if ((pincode || password) && resourceSessionToken) {
const { resourceSession } = await validateResourceSessionToken(
resourceSessionToken,
2024-12-15 17:47:07 -05:00
resource.resourceId
);
if (resourceSession) {
2024-12-15 17:47:07 -05:00
if (resource.otpEnabled && !resourceSession.usedOtp) {
logger.debug("Resource not allowed because OTP not used");
return notAllowed(res, redirectUrl);
}
if (
pincode &&
resourceSession.pincodeId === pincode.pincodeId
) {
2024-11-24 14:28:23 -05:00
logger.debug(
2024-12-15 17:47:07 -05:00
"Resource allowed because pincode session is valid"
2024-11-24 14:28:23 -05:00
);
return allowed(res);
}
if (
password &&
resourceSession.passwordId === password.passwordId
) {
2024-11-24 14:28:23 -05:00
logger.debug(
2024-12-15 17:47:07 -05:00
"Resource allowed because password session is valid"
2024-11-24 14:28:23 -05:00
);
return allowed(res);
}
}
}
2024-11-24 14:28:23 -05:00
logger.debug("No more auth to check, resource not allowed");
return notAllowed(res, redirectUrl);
} catch (e) {
2024-11-24 14:28:23 -05:00
console.error(e);
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
2024-12-15 17:47:07 -05:00
"Failed to verify session"
)
);
}
}
function notAllowed(res: Response, redirectUrl?: string) {
2024-11-24 14:28:23 -05:00
const data = {
data: { valid: false, redirectUrl },
success: true,
error: false,
message: "Access denied",
2024-12-15 17:47:07 -05:00
status: HttpCode.OK
};
2024-11-24 14:28:23 -05:00
logger.debug(JSON.stringify(data));
return response<VerifyUserResponse>(res, data);
}
function allowed(res: Response) {
2024-11-24 14:28:23 -05:00
const data = {
data: { valid: true },
success: true,
error: false,
message: "Access allowed",
2024-12-15 17:47:07 -05:00
status: HttpCode.OK
};
2024-11-24 14:28:23 -05:00
logger.debug(JSON.stringify(data));
return response<VerifyUserResponse>(res, data);
}
async function isUserAllowedToAccessResource(
user: User,
2024-12-15 17:47:07 -05:00
resource: Resource
): Promise<boolean> {
if (config.flags?.require_email_verification && !user.emailVerified) {
return false;
}
const userOrgRole = await db
.select()
.from(userOrgs)
.where(
2024-11-24 14:28:23 -05:00
and(
eq(userOrgs.userId, user.userId),
2024-12-15 17:47:07 -05:00
eq(userOrgs.orgId, resource.orgId)
)
)
.limit(1);
if (userOrgRole.length === 0) {
return false;
}
const roleResourceAccess = await db
.select()
.from(roleResources)
.where(
and(
eq(roleResources.resourceId, resource.resourceId),
2024-12-15 17:47:07 -05:00
eq(roleResources.roleId, userOrgRole[0].roleId)
)
)
.limit(1);
if (roleResourceAccess.length > 0) {
return true;
}
const userResourceAccess = await db
.select()
.from(userResources)
.where(
and(
eq(userResources.userId, user.userId),
2024-12-15 17:47:07 -05:00
eq(userResources.resourceId, resource.resourceId)
)
)
.limit(1);
if (userResourceAccess.length > 0) {
return true;
}
return false;
}