api for set resource password and auth with resource password

This commit is contained in:
Milo Schwartz
2024-11-17 22:44:11 -05:00
parent c565c14aa0
commit e802d061ba
10 changed files with 432 additions and 88 deletions

View File

@@ -10,13 +10,15 @@ import {
resourcePassword,
resourcePincode,
resources,
userOrgs,
} from "@server/db/schema";
import { eq } from "drizzle-orm";
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";
const verifyResourceSessionSchema = z.object({
cookies: z.object({
sessions: z.object({
session: z.string().nullable(),
resource_session: z.string().nullable(),
}),
@@ -42,7 +44,7 @@ export async function verifyResourceSession(
res: Response,
next: NextFunction
): Promise<any> {
const parsedBody = verifyResourceSessionSchema.safeParse(req.query);
const parsedBody = verifyResourceSessionSchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
@@ -54,7 +56,7 @@ export async function verifyResourceSession(
}
try {
const { cookies, host, originalRequestURL } = parsedBody.data;
const { sessions, host, originalRequestURL } = parsedBody.data;
const [result] = await db
.select()
@@ -74,53 +76,60 @@ export async function verifyResourceSession(
const pincode = result?.resourcePincode;
const password = result?.resourcePassword;
// resource doesn't exist for some reason
if (!resource) {
return notAllowed(res); // no resource to redirect to
return notAllowed(res);
}
// no auth is configured; auth check is disabled
if (!resource.appSSOEnabled && !pincode && !password) {
const { sso, blockAccess } = resource;
if (blockAccess) {
return notAllowed(res);
}
if (!resource.sso && !pincode && !password) {
return allowed(res);
}
const redirectUrl = `${config.app.base_url}/auth/resource/${resource.resourceId}/login?redirect=${originalRequestURL}`;
// we need to check all session to find at least one valid session
// if we find one, we allow access
// if we don't find any, we deny access and redirect to the login page
// we found a session token, and app sso is enabled, so we need to check if it's a valid session
if (cookies.session && resource.appSSOEnabled) {
const { user, session } = await validateSessionToken(
cookies.session
if (sso && sessions.session) {
const { session, user } = await validateSessionToken(
sessions.session
);
if (user && session) {
return allowed(res);
}
}
// we found a resource session token, and either pincode or password is enabled for the resource
// so we need to check if it's a valid session
if (cookies.resource_session && (pincode || password)) {
const { session, user } = await validateResourceSessionToken(
cookies.resource_session
);
if (session && user) {
if (pincode && session.method === "pincode") {
return allowed(res);
}
const isAllowed = await isUserAllowedToAccessResource(
user.userId,
resource
);
if (password && session.method === "password") {
if (isAllowed) {
return allowed(res);
}
}
}
if (password && sessions.resource_session) {
const { resourceSession } = await validateResourceSessionToken(
sessions.resource_session,
resource.resourceId
);
if (resourceSession) {
if (
pincode &&
resourceSession.pincodeId === pincode.pincodeId
) {
return allowed(res);
}
if (
password &&
resourceSession.passwordId === password.passwordId
) {
return allowed(res);
}
}
}
// a valid session was not found for an enabled auth method so we deny access
// the user is redirected to the login page
// the login page with render which auth methods are enabled and show the user the correct login form
return notAllowed(res, redirectUrl);
} catch (e) {
return next(
@@ -151,3 +160,52 @@ function allowed(res: Response) {
status: HttpCode.OK,
});
}
async function isUserAllowedToAccessResource(
userId: string,
resource: Resource
) {
const userOrgRole = await db
.select()
.from(userOrgs)
.where(
and(eq(userOrgs.userId, userId), 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),
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, userId),
eq(userResources.resourceId, resource.resourceId)
)
)
.limit(1);
if (userResourceAccess.length > 0) {
return true;
}
return false;
}

View File

@@ -275,6 +275,18 @@ authenticated.post(
resource.setResourceUsers
);
authenticated.post(
`/resource/:resourceId/password`,
verifyResourceAccess,
verifyUserHasAction(ActionsEnum.setResourceAuthMethods),
resource.setResourcePassword
);
unauthenticated.post(
"/resource/:resourceId/auth/password",
resource.authWithPassword
);
// authenticated.get(
// "/role/:roleId/resources",
// verifyRoleAccess,

View File

@@ -24,6 +24,6 @@ gerbilRouter.post("/receive-bandwidth", gerbil.receiveBandwidth);
const badgerRouter = Router();
internalRouter.use("/badger", badgerRouter);
badgerRouter.get("/verify-session", badger.verifyResourceSession);
badgerRouter.post("/verify-session", badger.verifyResourceSession);
export default internalRouter;

View File

@@ -0,0 +1,153 @@
import { verify } from "@node-rs/argon2";
import { generateSessionToken } from "@server/auth";
import db from "@server/db";
import { resourcePassword, resources } from "@server/db/schema";
import HttpCode from "@server/types/HttpCode";
import response from "@server/utils/response";
import { eq } from "drizzle-orm";
import { NextFunction, Request, Response } from "express";
import createHttpError from "http-errors";
import { z } from "zod";
import { fromError } from "zod-validation-error";
import {
createResourceSession,
serializeResourceSessionCookie,
} from "@server/auth/resource";
export const authWithPasswordBodySchema = z.object({
password: z.string(),
email: z.string().email().optional(),
code: z.string().optional(),
});
export const authWithPasswordParamsSchema = z.object({
resourceId: z.string().transform(Number).pipe(z.number().int().positive()),
});
export type AuthWithPasswordResponse = {
codeRequested?: boolean;
};
export async function authWithPassword(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
const parsedBody = authWithPasswordBodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const parsedParams = authWithPasswordParamsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const { resourceId } = parsedParams.data;
const { email, password, code } = parsedBody.data;
try {
const [result] = await db
.select()
.from(resources)
.leftJoin(
resourcePassword,
eq(resourcePassword.resourceId, resources.resourceId)
)
.where(eq(resources.resourceId, resourceId))
.limit(1);
const resource = result?.resources;
const definedPassword = result?.resourcePassword;
if (!resource) {
return next(
createHttpError(HttpCode.BAD_REQUEST, "Resource does not exist")
);
}
if (!definedPassword) {
return next(
createHttpError(
HttpCode.UNAUTHORIZED,
createHttpError(
HttpCode.BAD_REQUEST,
"Resource has no password protection"
)
)
);
}
const validPassword = await verify(
definedPassword.passwordHash,
password,
{
memoryCost: 19456,
timeCost: 2,
outputLen: 32,
parallelism: 1,
}
);
if (!validPassword) {
return next(
createHttpError(HttpCode.UNAUTHORIZED, "Incorrect password")
);
}
if (resource.twoFactorEnabled) {
if (!code) {
return response<AuthWithPasswordResponse>(res, {
data: { codeRequested: true },
success: true,
error: false,
message: "Two-factor authentication required",
status: HttpCode.ACCEPTED,
});
}
// TODO: Implement email OTP for resource 2fa
}
const token = generateSessionToken();
await createResourceSession({
resourceId,
token,
passwordId: definedPassword.passwordId,
});
const secureCookie = resource.ssl;
const cookie = serializeResourceSessionCookie(
token,
resource.fullDomain,
secureCookie
);
res.appendHeader("Set-Cookie", cookie);
return response<null>(res, {
data: null,
success: true,
error: false,
message: "Authenticated with resource successfully",
status: HttpCode.OK,
});
} catch (e) {
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to authenticate with resource"
)
);
}
}

View File

@@ -6,4 +6,6 @@ export * from "./listResources";
export * from "./listResourceRoles";
export * from "./setResourceUsers";
export * from "./setResourceRoles";
export * from "./listResourceUsers"
export * from "./listResourceUsers";
export * from "./setResourcePassword";
export * from "./authWithPassword";

View File

@@ -0,0 +1,84 @@
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { resourcePassword, resources } from "@server/db/schema";
import { eq } from "drizzle-orm";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import { fromError } from "zod-validation-error";
import { hash } from "@node-rs/argon2";
import { response } from "@server/utils";
const setResourceAuthMethodsParamsSchema = z.object({
resourceId: z.string().transform(Number).pipe(z.number().int().positive()),
});
const setResourceAuthMethodsBodySchema = z
.object({
password: z.string().nullable(),
})
.strict();
export async function setResourcePassword(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = setResourceAuthMethodsParamsSchema.safeParse(
req.params
);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const parsedBody = setResourceAuthMethodsBodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const { resourceId } = parsedParams.data;
const { password } = parsedBody.data;
await db.transaction(async (trx) => {
await trx
.delete(resourcePassword)
.where(eq(resourcePassword.resourceId, resourceId));
if (password) {
const passwordHash = await hash(password, {
memoryCost: 19456,
timeCost: 2,
outputLen: 32,
parallelism: 1,
});
await trx
.insert(resourcePassword)
.values({ resourceId, passwordHash });
}
});
return response(res, {
data: {},
success: true,
error: false,
message: "Resource password set successfully",
status: HttpCode.CREATED,
});
} catch (error) {
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}

View File

@@ -19,6 +19,8 @@ const updateResourceBodySchema = z
name: z.string().min(1).max(255).optional(),
subdomain: subdomainSchema.optional(),
ssl: z.boolean().optional(),
sso: z.boolean().optional(),
blockAccess: z.boolean().optional(),
// siteId: z.number(),
})
.strict()