add otp flow to resource auth portal

This commit is contained in:
Milo Schwartz
2024-12-15 17:47:07 -05:00
parent d3d2fe398b
commit 998fab6d0a
14 changed files with 1159 additions and 376 deletions

View File

@@ -9,7 +9,7 @@ import { VerifyEmail } from "@server/emails/templates/VerifyEmailCode";
export async function sendEmailVerificationCode(
email: string,
userId: string,
userId: string
): Promise<void> {
const code = await generateEmailVerificationCode(userId, email);
@@ -17,19 +17,19 @@ export async function sendEmailVerificationCode(
VerifyEmail({
username: email,
verificationCode: code,
verifyLink: `${config.app.base_url}/auth/verify-email`,
verifyLink: `${config.app.base_url}/auth/verify-email`
}),
{
to: email,
from: config.email?.no_reply,
subject: "Verify your email address",
},
subject: "Verify your email address"
}
);
}
async function generateEmailVerificationCode(
userId: string,
email: string,
email: string
): Promise<string> {
await db
.delete(emailVerificationCodes)
@@ -41,7 +41,7 @@ async function generateEmailVerificationCode(
userId,
email,
code,
expiresAt: createDate(new TimeSpan(15, "m")).getTime(),
expiresAt: createDate(new TimeSpan(15, "m")).getTime()
});
return code;

View File

@@ -11,7 +11,7 @@ import {
resourcePincode,
resources,
User,
userOrgs,
userOrgs
} from "@server/db/schema";
import { and, eq } from "drizzle-orm";
import config from "@server/config";
@@ -26,7 +26,7 @@ const verifyResourceSessionSchema = z.object({
host: z.string(),
path: z.string(),
method: z.string(),
tls: z.boolean(),
tls: z.boolean()
});
export type VerifyResourceSessionSchema = z.infer<
@@ -41,7 +41,7 @@ export type VerifyUserResponse = {
export async function verifyResourceSession(
req: Request,
res: Response,
next: NextFunction,
next: NextFunction
): Promise<any> {
logger.debug("Badger sent", req.body); // remove when done testing
@@ -51,8 +51,8 @@ export async function verifyResourceSession(
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString(),
),
fromError(parsedBody.error).toString()
)
);
}
@@ -64,11 +64,11 @@ export async function verifyResourceSession(
.from(resources)
.leftJoin(
resourcePincode,
eq(resourcePincode.resourceId, resources.resourceId),
eq(resourcePincode.resourceId, resources.resourceId)
)
.leftJoin(
resourcePassword,
eq(resourcePassword.resourceId, resources.resourceId),
eq(resourcePassword.resourceId, resources.resourceId)
)
.where(eq(resources.fullDomain, host))
.limit(1);
@@ -103,17 +103,17 @@ export async function verifyResourceSession(
const sessionToken = sessions[config.server.session_cookie_name];
// check for unified login
if (sso && sessionToken) {
if (sso && sessionToken && !resource.otpEnabled) {
const { session, user } = await validateSessionToken(sessionToken);
if (session && user) {
const isAllowed = await isUserAllowedToAccessResource(
user,
resource,
resource
);
if (isAllowed) {
logger.debug(
"Resource allowed because user session is valid",
"Resource allowed because user session is valid"
);
return allowed(res);
}
@@ -125,19 +125,56 @@ export async function verifyResourceSession(
`${config.server.resource_session_cookie_name}_${resource.resourceId}`
];
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,
resource.resourceId,
resource.resourceId
);
if (resourceSession) {
if (resource.otpEnabled && !resourceSession.usedOtp) {
logger.debug("Resource not allowed because OTP not used");
return notAllowed(res, redirectUrl);
}
if (
pincode &&
resourceSession.pincodeId === pincode.pincodeId
) {
logger.debug(
"Resource allowed because pincode session is valid",
"Resource allowed because pincode session is valid"
);
return allowed(res);
}
@@ -147,7 +184,7 @@ export async function verifyResourceSession(
resourceSession.passwordId === password.passwordId
) {
logger.debug(
"Resource allowed because password session is valid",
"Resource allowed because password session is valid"
);
return allowed(res);
}
@@ -161,8 +198,8 @@ export async function verifyResourceSession(
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to verify session",
),
"Failed to verify session"
)
);
}
}
@@ -173,7 +210,7 @@ function notAllowed(res: Response, redirectUrl?: string) {
success: true,
error: false,
message: "Access denied",
status: HttpCode.OK,
status: HttpCode.OK
};
logger.debug(JSON.stringify(data));
return response<VerifyUserResponse>(res, data);
@@ -185,7 +222,7 @@ function allowed(res: Response) {
success: true,
error: false,
message: "Access allowed",
status: HttpCode.OK,
status: HttpCode.OK
};
logger.debug(JSON.stringify(data));
return response<VerifyUserResponse>(res, data);
@@ -193,7 +230,7 @@ function allowed(res: Response) {
async function isUserAllowedToAccessResource(
user: User,
resource: Resource,
resource: Resource
): Promise<boolean> {
if (config.flags?.require_email_verification && !user.emailVerified) {
return false;
@@ -205,8 +242,8 @@ async function isUserAllowedToAccessResource(
.where(
and(
eq(userOrgs.userId, user.userId),
eq(userOrgs.orgId, resource.orgId),
),
eq(userOrgs.orgId, resource.orgId)
)
)
.limit(1);
@@ -220,8 +257,8 @@ async function isUserAllowedToAccessResource(
.where(
and(
eq(roleResources.resourceId, resource.resourceId),
eq(roleResources.roleId, userOrgRole[0].roleId),
),
eq(roleResources.roleId, userOrgRole[0].roleId)
)
)
.limit(1);
@@ -235,8 +272,8 @@ async function isUserAllowedToAccessResource(
.where(
and(
eq(userResources.userId, user.userId),
eq(userResources.resourceId, resource.resourceId),
),
eq(userResources.resourceId, resource.resourceId)
)
)
.limit(1);

View File

@@ -1,40 +1,42 @@
import { verify } from "@node-rs/argon2";
import { generateSessionToken } from "@server/auth";
import db from "@server/db";
import { resourcePassword, resources } from "@server/db/schema";
import { orgs, resourceOtp, resourcePassword, resources } from "@server/db/schema";
import HttpCode from "@server/types/HttpCode";
import response from "@server/utils/response";
import { eq } from "drizzle-orm";
import { and, 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,
serializeResourceSessionCookie
} from "@server/auth/resource";
import logger from "@server/logger";
import config from "@server/config";
import { isValidOtp, sendResourceOtpEmail } from "@server/auth/resourceOtp";
export const authWithPasswordBodySchema = z.object({
password: z.string(),
email: z.string().email().optional(),
code: z.string().optional(),
otp: z.string().optional()
});
export const authWithPasswordParamsSchema = z.object({
resourceId: z.string().transform(Number).pipe(z.number().int().positive()),
resourceId: z.string().transform(Number).pipe(z.number().int().positive())
});
export type AuthWithPasswordResponse = {
codeRequested?: boolean;
otpRequested?: boolean;
otpSent?: boolean;
session?: string;
};
export async function authWithPassword(
req: Request,
res: Response,
next: NextFunction,
next: NextFunction
): Promise<any> {
const parsedBody = authWithPasswordBodySchema.safeParse(req.body);
@@ -42,8 +44,8 @@ export async function authWithPassword(
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString(),
),
fromError(parsedBody.error).toString()
)
);
}
@@ -53,13 +55,13 @@ export async function authWithPassword(
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString(),
),
fromError(parsedParams.error).toString()
)
);
}
const { resourceId } = parsedParams.data;
const { email, password, code } = parsedBody.data;
const { email, password, otp } = parsedBody.data;
try {
const [result] = await db
@@ -67,20 +69,25 @@ export async function authWithPassword(
.from(resources)
.leftJoin(
resourcePassword,
eq(resourcePassword.resourceId, resources.resourceId),
eq(resourcePassword.resourceId, resources.resourceId)
)
.leftJoin(orgs, eq(orgs.orgId, resources.orgId))
.where(eq(resources.resourceId, resourceId))
.limit(1);
const resource = result?.resources;
const org = result?.orgs;
const definedPassword = result?.resourcePassword;
if (!org) {
return next(
createHttpError(HttpCode.BAD_REQUEST, "Resource does not exist")
);
}
if (!resource) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Resource does not exist",
),
createHttpError(HttpCode.BAD_REQUEST, "Resource does not exist")
);
}
@@ -90,9 +97,9 @@ export async function authWithPassword(
HttpCode.UNAUTHORIZED,
createHttpError(
HttpCode.BAD_REQUEST,
"Resource has no password protection",
),
),
"Resource has no password protection"
)
)
);
}
@@ -103,27 +110,69 @@ export async function authWithPassword(
memoryCost: 19456,
timeCost: 2,
outputLen: 32,
parallelism: 1,
},
parallelism: 1
}
);
if (!validPassword) {
return next(
createHttpError(HttpCode.UNAUTHORIZED, "Incorrect password"),
createHttpError(HttpCode.UNAUTHORIZED, "Incorrect password")
);
}
if (resource.twoFactorEnabled) {
if (!code) {
if (resource.otpEnabled) {
if (otp && email) {
const isValidCode = await isValidOtp(
email,
resource.resourceId,
otp
);
if (!isValidCode) {
return next(
createHttpError(HttpCode.UNAUTHORIZED, "Incorrect OTP")
);
}
await db
.delete(resourceOtp)
.where(
and(
eq(resourceOtp.email, email),
eq(resourceOtp.resourceId, resource.resourceId)
)
);
} else if (email) {
try {
await sendResourceOtpEmail(
email,
resource.resourceId,
resource.name,
org.name
);
return response<AuthWithPasswordResponse>(res, {
data: { otpSent: true },
success: true,
error: false,
message: "Sent one-time otp to email address",
status: HttpCode.ACCEPTED
});
} catch (e) {
logger.error(e);
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to send one-time otp. Make sure the email address is correct and try again."
)
);
}
} else {
return response<AuthWithPasswordResponse>(res, {
data: { codeRequested: true },
data: { otpRequested: true },
success: true,
error: false,
message: "Two-factor authentication required",
status: HttpCode.ACCEPTED,
message: "One-time otp required to complete authentication",
status: HttpCode.ACCEPTED
});
}
// TODO: Implement email OTP for resource 2fa
}
const token = generateSessionToken();
@@ -131,32 +180,32 @@ export async function authWithPassword(
resourceId,
token,
passwordId: definedPassword.passwordId,
usedOtp: otp !== undefined,
email
});
const cookieName = `${config.server.resource_session_cookie_name}_${resource.resourceId}`;
const cookie = serializeResourceSessionCookie(
cookieName,
token,
resource.fullDomain,
resource.fullDomain
);
res.appendHeader("Set-Cookie", cookie);
logger.debug(cookie); // remove after testing
return response<AuthWithPasswordResponse>(res, {
data: {
session: token,
session: token
},
success: true,
error: false,
message: "Authenticated with resource successfully",
status: HttpCode.OK,
status: HttpCode.OK
});
} catch (e) {
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to authenticate with resource",
),
"Failed to authenticate with resource"
)
);
}
}

View File

@@ -1,40 +1,48 @@
import { verify } from "@node-rs/argon2";
import { generateSessionToken } from "@server/auth";
import db from "@server/db";
import { resourcePincode, resources } from "@server/db/schema";
import {
orgs,
resourceOtp,
resourcePincode,
resources
} from "@server/db/schema";
import HttpCode from "@server/types/HttpCode";
import response from "@server/utils/response";
import { eq } from "drizzle-orm";
import { and, 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,
serializeResourceSessionCookie
} from "@server/auth/resource";
import logger from "@server/logger";
import config from "@server/config";
import { AuthWithPasswordResponse } from "./authWithPassword";
import { isValidOtp, sendResourceOtpEmail } from "@server/auth/resourceOtp";
export const authWithPincodeBodySchema = z.object({
pincode: z.string(),
email: z.string().email().optional(),
code: z.string().optional(),
otp: z.string().optional()
});
export const authWithPincodeParamsSchema = z.object({
resourceId: z.string().transform(Number).pipe(z.number().int().positive()),
resourceId: z.string().transform(Number).pipe(z.number().int().positive())
});
export type AuthWithPincodeResponse = {
codeRequested?: boolean;
otpRequested?: boolean;
otpSent?: boolean;
session?: string;
};
export async function authWithPincode(
req: Request,
res: Response,
next: NextFunction,
next: NextFunction
): Promise<any> {
const parsedBody = authWithPincodeBodySchema.safeParse(req.body);
@@ -42,8 +50,8 @@ export async function authWithPincode(
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString(),
),
fromError(parsedBody.error).toString()
)
);
}
@@ -53,13 +61,13 @@ export async function authWithPincode(
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString(),
),
fromError(parsedParams.error).toString()
)
);
}
const { resourceId } = parsedParams.data;
const { email, pincode, code } = parsedBody.data;
const { email, pincode, otp } = parsedBody.data;
try {
const [result] = await db
@@ -67,20 +75,28 @@ export async function authWithPincode(
.from(resources)
.leftJoin(
resourcePincode,
eq(resourcePincode.resourceId, resources.resourceId),
eq(resourcePincode.resourceId, resources.resourceId)
)
.leftJoin(orgs, eq(orgs.orgId, resources.orgId))
.where(eq(resources.resourceId, resourceId))
.limit(1);
const resource = result?.resources;
const org = result?.orgs;
const definedPincode = result?.resourcePincode;
if (!org) {
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Org does not exist"
)
);
}
if (!resource) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Resource does not exist",
),
createHttpError(HttpCode.BAD_REQUEST, "Resource does not exist")
);
}
@@ -90,9 +106,9 @@ export async function authWithPincode(
HttpCode.UNAUTHORIZED,
createHttpError(
HttpCode.BAD_REQUEST,
"Resource has no pincode protection",
),
),
"Resource has no pincode protection"
)
)
);
}
@@ -100,26 +116,68 @@ export async function authWithPincode(
memoryCost: 19456,
timeCost: 2,
outputLen: 32,
parallelism: 1,
parallelism: 1
});
if (!validPincode) {
return next(
createHttpError(HttpCode.UNAUTHORIZED, "Incorrect PIN code"),
createHttpError(HttpCode.UNAUTHORIZED, "Incorrect PIN")
);
}
if (resource.twoFactorEnabled) {
if (!code) {
return response<AuthWithPincodeResponse>(res, {
data: { codeRequested: true },
if (resource.otpEnabled) {
if (otp && email) {
const isValidCode = await isValidOtp(
email,
resource.resourceId,
otp
);
if (!isValidCode) {
return next(
createHttpError(HttpCode.UNAUTHORIZED, "Incorrect OTP")
);
}
await db
.delete(resourceOtp)
.where(
and(
eq(resourceOtp.email, email),
eq(resourceOtp.resourceId, resource.resourceId)
)
);
} else if (email) {
try {
await sendResourceOtpEmail(
email,
resource.resourceId,
resource.name,
org.name
);
return response<AuthWithPasswordResponse>(res, {
data: { otpSent: true },
success: true,
error: false,
message: "Sent one-time otp to email address",
status: HttpCode.ACCEPTED
});
} catch (e) {
logger.error(e);
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to send one-time otp. Make sure the email address is correct and try again."
)
);
}
} else {
return response<AuthWithPasswordResponse>(res, {
data: { otpRequested: true },
success: true,
error: false,
message: "Two-factor authentication required",
status: HttpCode.ACCEPTED,
message: "One-time otp required to complete authentication",
status: HttpCode.ACCEPTED
});
}
// TODO: Implement email OTP for resource 2fa
}
const token = generateSessionToken();
@@ -127,32 +185,33 @@ export async function authWithPincode(
resourceId,
token,
pincodeId: definedPincode.pincodeId,
usedOtp: otp !== undefined,
email
});
const cookieName = `${config.server.resource_session_cookie_name}_${resource.resourceId}`;
const cookie = serializeResourceSessionCookie(
cookieName,
token,
resource.fullDomain,
resource.fullDomain
);
res.appendHeader("Set-Cookie", cookie);
logger.debug(cookie); // remove after testing
return response<AuthWithPincodeResponse>(res, {
data: {
session: token,
session: token
},
success: true,
error: false,
message: "Authenticated with resource successfully",
status: HttpCode.OK,
status: HttpCode.OK
});
} catch (e) {
logger.error(e);
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to authenticate with resource",
),
"Failed to authenticate with resource"
)
);
}
}