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
No known key found for this signature in database
14 changed files with 1159 additions and 376 deletions

View file

@ -11,7 +11,7 @@
"db:studio": "drizzle-kit studio", "db:studio": "drizzle-kit studio",
"build": "mkdir -p dist && next build && node scripts/esbuild.mjs -e server/index.ts -o dist/server.mjs", "build": "mkdir -p dist && next build && node scripts/esbuild.mjs -e server/index.ts -o dist/server.mjs",
"start": "NODE_ENV=development ENVIRONMENT=prod node dist/server.mjs", "start": "NODE_ENV=development ENVIRONMENT=prod node dist/server.mjs",
"email": "email dev --dir server/emails/templates --port 3002" "email": "email dev --dir server/emails/templates --port 3005"
}, },
"dependencies": { "dependencies": {
"@hookform/resolvers": "3.9.0", "@hookform/resolvers": "3.9.0",

View file

@ -16,15 +16,17 @@ export async function createResourceSession(opts: {
resourceId: number; resourceId: number;
passwordId?: number; passwordId?: number;
pincodeId?: number; pincodeId?: number;
whitelistId: number;
usedOtp?: boolean;
}): Promise<ResourceSession> { }): Promise<ResourceSession> {
if (!opts.passwordId && !opts.pincodeId) { if (!opts.passwordId && !opts.pincodeId) {
throw new Error( throw new Error(
"At least one of passwordId or pincodeId must be provided", "At least one of passwordId or pincodeId must be provided"
); );
} }
const sessionId = encodeHexLowerCase( const sessionId = encodeHexLowerCase(
sha256(new TextEncoder().encode(opts.token)), sha256(new TextEncoder().encode(opts.token))
); );
const session: ResourceSession = { const session: ResourceSession = {
@ -33,6 +35,8 @@ export async function createResourceSession(opts: {
resourceId: opts.resourceId, resourceId: opts.resourceId,
passwordId: opts.passwordId || null, passwordId: opts.passwordId || null,
pincodeId: opts.pincodeId || null, pincodeId: opts.pincodeId || null,
whitelistId: opts.whitelistId,
usedOtp: opts.usedOtp || false
}; };
await db.insert(resourceSessions).values(session); await db.insert(resourceSessions).values(session);
@ -42,10 +46,10 @@ export async function createResourceSession(opts: {
export async function validateResourceSessionToken( export async function validateResourceSessionToken(
token: string, token: string,
resourceId: number, resourceId: number
): Promise<ResourceSessionValidationResult> { ): Promise<ResourceSessionValidationResult> {
const sessionId = encodeHexLowerCase( const sessionId = encodeHexLowerCase(
sha256(new TextEncoder().encode(token)), sha256(new TextEncoder().encode(token))
); );
const result = await db const result = await db
.select() .select()
@ -53,8 +57,8 @@ export async function validateResourceSessionToken(
.where( .where(
and( and(
eq(resourceSessions.sessionId, sessionId), eq(resourceSessions.sessionId, sessionId),
eq(resourceSessions.resourceId, resourceId), eq(resourceSessions.resourceId, resourceId)
), )
); );
if (result.length < 1) { if (result.length < 1) {
@ -65,12 +69,12 @@ export async function validateResourceSessionToken(
if (Date.now() >= resourceSession.expiresAt - SESSION_COOKIE_EXPIRES / 2) { if (Date.now() >= resourceSession.expiresAt - SESSION_COOKIE_EXPIRES / 2) {
resourceSession.expiresAt = new Date( resourceSession.expiresAt = new Date(
Date.now() + SESSION_COOKIE_EXPIRES, Date.now() + SESSION_COOKIE_EXPIRES
).getTime(); ).getTime();
await db await db
.update(resourceSessions) .update(resourceSessions)
.set({ .set({
expiresAt: resourceSession.expiresAt, expiresAt: resourceSession.expiresAt
}) })
.where(eq(resourceSessions.sessionId, resourceSession.sessionId)); .where(eq(resourceSessions.sessionId, resourceSession.sessionId));
} }
@ -79,7 +83,7 @@ export async function validateResourceSessionToken(
} }
export async function invalidateResourceSession( export async function invalidateResourceSession(
sessionId: string, sessionId: string
): Promise<void> { ): Promise<void> {
await db await db
.delete(resourceSessions) .delete(resourceSessions)
@ -91,7 +95,8 @@ export async function invalidateAllSessions(
method?: { method?: {
passwordId?: number; passwordId?: number;
pincodeId?: number; pincodeId?: number;
}, whitelistId?: number;
}
): Promise<void> { ): Promise<void> {
if (method?.passwordId) { if (method?.passwordId) {
await db await db
@ -99,19 +104,34 @@ export async function invalidateAllSessions(
.where( .where(
and( and(
eq(resourceSessions.resourceId, resourceId), eq(resourceSessions.resourceId, resourceId),
eq(resourceSessions.passwordId, method.passwordId), eq(resourceSessions.passwordId, method.passwordId)
), )
); );
} else if (method?.pincodeId) { }
if (method?.pincodeId) {
await db await db
.delete(resourceSessions) .delete(resourceSessions)
.where( .where(
and( and(
eq(resourceSessions.resourceId, resourceId), eq(resourceSessions.resourceId, resourceId),
eq(resourceSessions.pincodeId, method.pincodeId), eq(resourceSessions.pincodeId, method.pincodeId)
), )
); );
} else { }
if (method?.whitelistId) {
await db
.delete(resourceSessions)
.where(
and(
eq(resourceSessions.resourceId, resourceId),
eq(resourceSessions.whitelistId, method.whitelistId)
)
);
}
if (!method?.passwordId && !method?.pincodeId && !method?.whitelistId) {
await db await db
.delete(resourceSessions) .delete(resourceSessions)
.where(eq(resourceSessions.resourceId, resourceId)); .where(eq(resourceSessions.resourceId, resourceId));
@ -121,7 +141,7 @@ export async function invalidateAllSessions(
export function serializeResourceSessionCookie( export function serializeResourceSessionCookie(
cookieName: string, cookieName: string,
token: string, token: string,
fqdn: string, fqdn: string
): string { ): string {
if (SECURE_COOKIES) { if (SECURE_COOKIES) {
return `${cookieName}=${token}; HttpOnly; SameSite=Lax; Max-Age=${SESSION_COOKIE_EXPIRES}; Path=/; Secure; Domain=${COOKIE_DOMAIN}`; return `${cookieName}=${token}; HttpOnly; SameSite=Lax; Max-Age=${SESSION_COOKIE_EXPIRES}; Path=/; Secure; Domain=${COOKIE_DOMAIN}`;
@ -132,7 +152,7 @@ export function serializeResourceSessionCookie(
export function createBlankResourceSessionTokenCookie( export function createBlankResourceSessionTokenCookie(
cookieName: string, cookieName: string,
fqdn: string, fqdn: string
): string { ): string {
if (SECURE_COOKIES) { if (SECURE_COOKIES) {
return `${cookieName}=; HttpOnly; SameSite=Lax; Max-Age=0; Path=/; Secure; Domain=${COOKIE_DOMAIN}`; return `${cookieName}=; HttpOnly; SameSite=Lax; Max-Age=0; Path=/; Secure; Domain=${COOKIE_DOMAIN}`;

102
server/auth/resourceOtp.ts Normal file
View file

@ -0,0 +1,102 @@
import db from "@server/db";
import { resourceOtp } from "@server/db/schema";
import { and, eq } from "drizzle-orm";
import { createDate, isWithinExpirationDate, TimeSpan } from "oslo";
import { alphabet, generateRandomString, sha256 } from "oslo/crypto";
import { encodeHex } from "oslo/encoding";
import { sendEmail } from "@server/emails";
import ResourceOTPCode from "@server/emails/templates/ResourceOTPCode";
import config from "@server/config";
import { hash, verify } from "@node-rs/argon2";
export async function sendResourceOtpEmail(
email: string,
resourceId: number,
resourceName: string,
orgName: string
): Promise<void> {
const otp = await generateResourceOtpCode(resourceId, email);
await sendEmail(
ResourceOTPCode({
email,
resourceName,
orgName,
otp
}),
{
to: email,
from: config.email?.no_reply,
subject: `Your one-time code to access ${resourceName}`
}
);
}
export async function generateResourceOtpCode(
resourceId: number,
email: string
): Promise<string> {
await db
.delete(resourceOtp)
.where(
and(
eq(resourceOtp.email, email),
eq(resourceOtp.resourceId, resourceId)
)
);
const otp = generateRandomString(8, alphabet("0-9", "A-Z", "a-z"));
const otpHash = await hash(otp, {
memoryCost: 19456,
timeCost: 2,
outputLen: 32,
parallelism: 1,
});
await db.insert(resourceOtp).values({
resourceId,
email,
otpHash,
expiresAt: createDate(new TimeSpan(15, "m")).getTime()
});
return otp;
}
export async function isValidOtp(
email: string,
resourceId: number,
otp: string
): Promise<boolean> {
const record = await db
.select()
.from(resourceOtp)
.where(
and(
eq(resourceOtp.email, email),
eq(resourceOtp.resourceId, resourceId)
)
)
.limit(1);
if (record.length === 0) {
return false;
}
const validCode = await verify(record[0].otpHash, otp, {
memoryCost: 19456,
timeCost: 2,
outputLen: 32,
parallelism: 1
});
if (!validCode) {
return false;
}
if (!isWithinExpirationDate(new Date(record[0].expiresAt))) {
return false;
}
return true;
}

View file

@ -1,41 +1,41 @@
import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
import { InferSelectModel } from "drizzle-orm"; import { InferSelectModel } from "drizzle-orm";
import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
export const orgs = sqliteTable("orgs", { export const orgs = sqliteTable("orgs", {
orgId: text("orgId").primaryKey(), orgId: text("orgId").primaryKey(),
name: text("name").notNull(), name: text("name").notNull(),
domain: text("domain").notNull(), domain: text("domain").notNull()
}); });
export const sites = sqliteTable("sites", { export const sites = sqliteTable("sites", {
siteId: integer("siteId").primaryKey({ autoIncrement: true }), siteId: integer("siteId").primaryKey({ autoIncrement: true }),
orgId: text("orgId") orgId: text("orgId")
.references(() => orgs.orgId, { .references(() => orgs.orgId, {
onDelete: "cascade", onDelete: "cascade"
}) })
.notNull(), .notNull(),
niceId: text("niceId").notNull(), niceId: text("niceId").notNull(),
exitNodeId: integer("exitNode").references(() => exitNodes.exitNodeId, { exitNodeId: integer("exitNode").references(() => exitNodes.exitNodeId, {
onDelete: "set null", onDelete: "set null"
}), }),
name: text("name").notNull(), name: text("name").notNull(),
pubKey: text("pubKey"), pubKey: text("pubKey"),
subnet: text("subnet").notNull(), subnet: text("subnet").notNull(),
megabytesIn: integer("bytesIn"), megabytesIn: integer("bytesIn"),
megabytesOut: integer("bytesOut"), megabytesOut: integer("bytesOut"),
type: text("type").notNull(), // "newt" or "wireguard" type: text("type").notNull() // "newt" or "wireguard"
}); });
export const resources = sqliteTable("resources", { export const resources = sqliteTable("resources", {
resourceId: integer("resourceId").primaryKey({ autoIncrement: true }), resourceId: integer("resourceId").primaryKey({ autoIncrement: true }),
siteId: integer("siteId") siteId: integer("siteId")
.references(() => sites.siteId, { .references(() => sites.siteId, {
onDelete: "cascade", onDelete: "cascade"
}) })
.notNull(), .notNull(),
orgId: text("orgId") orgId: text("orgId")
.references(() => orgs.orgId, { .references(() => orgs.orgId, {
onDelete: "cascade", onDelete: "cascade"
}) })
.notNull(), .notNull(),
name: text("name").notNull(), name: text("name").notNull(),
@ -46,16 +46,16 @@ export const resources = sqliteTable("resources", {
.notNull() .notNull()
.default(false), .default(false),
sso: integer("sso", { mode: "boolean" }).notNull().default(true), sso: integer("sso", { mode: "boolean" }).notNull().default(true),
twoFactorEnabled: integer("twoFactorEnabled", { mode: "boolean" }) otpEnabled: integer("otpEnabled", { mode: "boolean" })
.notNull() .notNull()
.default(false), .default(false)
}); });
export const targets = sqliteTable("targets", { export const targets = sqliteTable("targets", {
targetId: integer("targetId").primaryKey({ autoIncrement: true }), targetId: integer("targetId").primaryKey({ autoIncrement: true }),
resourceId: integer("resourceId") resourceId: integer("resourceId")
.references(() => resources.resourceId, { .references(() => resources.resourceId, {
onDelete: "cascade", onDelete: "cascade"
}) })
.notNull(), .notNull(),
ip: text("ip").notNull(), ip: text("ip").notNull(),
@ -63,7 +63,7 @@ export const targets = sqliteTable("targets", {
port: integer("port").notNull(), port: integer("port").notNull(),
internalPort: integer("internalPort"), internalPort: integer("internalPort"),
protocol: text("protocol"), protocol: text("protocol"),
enabled: integer("enabled", { mode: "boolean" }).notNull().default(true), enabled: integer("enabled", { mode: "boolean" }).notNull().default(true)
}); });
export const exitNodes = sqliteTable("exitNodes", { export const exitNodes = sqliteTable("exitNodes", {
@ -73,7 +73,7 @@ export const exitNodes = sqliteTable("exitNodes", {
endpoint: text("endpoint").notNull(), // this is how to reach gerbil externally - gets put into the wireguard config endpoint: text("endpoint").notNull(), // this is how to reach gerbil externally - gets put into the wireguard config
publicKey: text("pubicKey").notNull(), publicKey: text("pubicKey").notNull(),
listenPort: integer("listenPort").notNull(), listenPort: integer("listenPort").notNull(),
reachableAt: text("reachableAt"), // this is the internal address of the gerbil http server for command control reachableAt: text("reachableAt") // this is the internal address of the gerbil http server for command control
}); });
export const users = sqliteTable("user", { export const users = sqliteTable("user", {
@ -87,14 +87,14 @@ export const users = sqliteTable("user", {
emailVerified: integer("emailVerified", { mode: "boolean" }) emailVerified: integer("emailVerified", { mode: "boolean" })
.notNull() .notNull()
.default(false), .default(false),
dateCreated: text("dateCreated").notNull(), dateCreated: text("dateCreated").notNull()
}); });
export const newts = sqliteTable("newt", { export const newts = sqliteTable("newt", {
newtId: text("id").primaryKey(), newtId: text("id").primaryKey(),
secretHash: text("secretHash").notNull(), secretHash: text("secretHash").notNull(),
dateCreated: text("dateCreated").notNull(), dateCreated: text("dateCreated").notNull(),
siteId: integer("siteId").references(() => sites.siteId), siteId: integer("siteId").references(() => sites.siteId)
}); });
export const twoFactorBackupCodes = sqliteTable("twoFactorBackupCodes", { export const twoFactorBackupCodes = sqliteTable("twoFactorBackupCodes", {
@ -102,7 +102,7 @@ export const twoFactorBackupCodes = sqliteTable("twoFactorBackupCodes", {
userId: text("userId") userId: text("userId")
.notNull() .notNull()
.references(() => users.userId, { onDelete: "cascade" }), .references(() => users.userId, { onDelete: "cascade" }),
codeHash: text("codeHash").notNull(), codeHash: text("codeHash").notNull()
}); });
export const sessions = sqliteTable("session", { export const sessions = sqliteTable("session", {
@ -110,7 +110,7 @@ export const sessions = sqliteTable("session", {
userId: text("userId") userId: text("userId")
.notNull() .notNull()
.references(() => users.userId, { onDelete: "cascade" }), .references(() => users.userId, { onDelete: "cascade" }),
expiresAt: integer("expiresAt").notNull(), expiresAt: integer("expiresAt").notNull()
}); });
export const newtSessions = sqliteTable("newtSession", { export const newtSessions = sqliteTable("newtSession", {
@ -118,7 +118,7 @@ export const newtSessions = sqliteTable("newtSession", {
newtId: text("newtId") newtId: text("newtId")
.notNull() .notNull()
.references(() => newts.newtId, { onDelete: "cascade" }), .references(() => newts.newtId, { onDelete: "cascade" }),
expiresAt: integer("expiresAt").notNull(), expiresAt: integer("expiresAt").notNull()
}); });
export const userOrgs = sqliteTable("userOrgs", { export const userOrgs = sqliteTable("userOrgs", {
@ -131,7 +131,7 @@ export const userOrgs = sqliteTable("userOrgs", {
roleId: integer("roleId") roleId: integer("roleId")
.notNull() .notNull()
.references(() => roles.roleId), .references(() => roles.roleId),
isOwner: integer("isOwner", { mode: "boolean" }).notNull().default(false), isOwner: integer("isOwner", { mode: "boolean" }).notNull().default(false)
}); });
export const emailVerificationCodes = sqliteTable("emailVerificationCodes", { export const emailVerificationCodes = sqliteTable("emailVerificationCodes", {
@ -141,7 +141,7 @@ export const emailVerificationCodes = sqliteTable("emailVerificationCodes", {
.references(() => users.userId, { onDelete: "cascade" }), .references(() => users.userId, { onDelete: "cascade" }),
email: text("email").notNull(), email: text("email").notNull(),
code: text("code").notNull(), code: text("code").notNull(),
expiresAt: integer("expiresAt").notNull(), expiresAt: integer("expiresAt").notNull()
}); });
export const passwordResetTokens = sqliteTable("passwordResetTokens", { export const passwordResetTokens = sqliteTable("passwordResetTokens", {
@ -150,25 +150,25 @@ export const passwordResetTokens = sqliteTable("passwordResetTokens", {
.notNull() .notNull()
.references(() => users.userId, { onDelete: "cascade" }), .references(() => users.userId, { onDelete: "cascade" }),
tokenHash: text("tokenHash").notNull(), tokenHash: text("tokenHash").notNull(),
expiresAt: integer("expiresAt").notNull(), expiresAt: integer("expiresAt").notNull()
}); });
export const actions = sqliteTable("actions", { export const actions = sqliteTable("actions", {
actionId: text("actionId").primaryKey(), actionId: text("actionId").primaryKey(),
name: text("name"), name: text("name"),
description: text("description"), description: text("description")
}); });
export const roles = sqliteTable("roles", { export const roles = sqliteTable("roles", {
roleId: integer("roleId").primaryKey({ autoIncrement: true }), roleId: integer("roleId").primaryKey({ autoIncrement: true }),
orgId: text("orgId") orgId: text("orgId")
.references(() => orgs.orgId, { .references(() => orgs.orgId, {
onDelete: "cascade", onDelete: "cascade"
}) })
.notNull(), .notNull(),
isAdmin: integer("isAdmin", { mode: "boolean" }), isAdmin: integer("isAdmin", { mode: "boolean" }),
name: text("name").notNull(), name: text("name").notNull(),
description: text("description"), description: text("description")
}); });
export const roleActions = sqliteTable("roleActions", { export const roleActions = sqliteTable("roleActions", {
@ -180,7 +180,7 @@ export const roleActions = sqliteTable("roleActions", {
.references(() => actions.actionId, { onDelete: "cascade" }), .references(() => actions.actionId, { onDelete: "cascade" }),
orgId: text("orgId") orgId: text("orgId")
.notNull() .notNull()
.references(() => orgs.orgId, { onDelete: "cascade" }), .references(() => orgs.orgId, { onDelete: "cascade" })
}); });
export const userActions = sqliteTable("userActions", { export const userActions = sqliteTable("userActions", {
@ -192,7 +192,7 @@ export const userActions = sqliteTable("userActions", {
.references(() => actions.actionId, { onDelete: "cascade" }), .references(() => actions.actionId, { onDelete: "cascade" }),
orgId: text("orgId") orgId: text("orgId")
.notNull() .notNull()
.references(() => orgs.orgId, { onDelete: "cascade" }), .references(() => orgs.orgId, { onDelete: "cascade" })
}); });
export const roleSites = sqliteTable("roleSites", { export const roleSites = sqliteTable("roleSites", {
@ -201,7 +201,7 @@ export const roleSites = sqliteTable("roleSites", {
.references(() => roles.roleId, { onDelete: "cascade" }), .references(() => roles.roleId, { onDelete: "cascade" }),
siteId: integer("siteId") siteId: integer("siteId")
.notNull() .notNull()
.references(() => sites.siteId, { onDelete: "cascade" }), .references(() => sites.siteId, { onDelete: "cascade" })
}); });
export const userSites = sqliteTable("userSites", { export const userSites = sqliteTable("userSites", {
@ -210,7 +210,7 @@ export const userSites = sqliteTable("userSites", {
.references(() => users.userId, { onDelete: "cascade" }), .references(() => users.userId, { onDelete: "cascade" }),
siteId: integer("siteId") siteId: integer("siteId")
.notNull() .notNull()
.references(() => sites.siteId, { onDelete: "cascade" }), .references(() => sites.siteId, { onDelete: "cascade" })
}); });
export const roleResources = sqliteTable("roleResources", { export const roleResources = sqliteTable("roleResources", {
@ -219,7 +219,7 @@ export const roleResources = sqliteTable("roleResources", {
.references(() => roles.roleId, { onDelete: "cascade" }), .references(() => roles.roleId, { onDelete: "cascade" }),
resourceId: integer("resourceId") resourceId: integer("resourceId")
.notNull() .notNull()
.references(() => resources.resourceId, { onDelete: "cascade" }), .references(() => resources.resourceId, { onDelete: "cascade" })
}); });
export const userResources = sqliteTable("userResources", { export const userResources = sqliteTable("userResources", {
@ -228,19 +228,19 @@ export const userResources = sqliteTable("userResources", {
.references(() => users.userId, { onDelete: "cascade" }), .references(() => users.userId, { onDelete: "cascade" }),
resourceId: integer("resourceId") resourceId: integer("resourceId")
.notNull() .notNull()
.references(() => resources.resourceId, { onDelete: "cascade" }), .references(() => resources.resourceId, { onDelete: "cascade" })
}); });
export const limitsTable = sqliteTable("limits", { export const limitsTable = sqliteTable("limits", {
limitId: integer("limitId").primaryKey({ autoIncrement: true }), limitId: integer("limitId").primaryKey({ autoIncrement: true }),
orgId: text("orgId") orgId: text("orgId")
.references(() => orgs.orgId, { .references(() => orgs.orgId, {
onDelete: "cascade", onDelete: "cascade"
}) })
.notNull(), .notNull(),
name: text("name").notNull(), name: text("name").notNull(),
value: integer("value").notNull(), value: integer("value").notNull(),
description: text("description"), description: text("description")
}); });
export const userInvites = sqliteTable("userInvites", { export const userInvites = sqliteTable("userInvites", {
@ -253,28 +253,28 @@ export const userInvites = sqliteTable("userInvites", {
tokenHash: text("token").notNull(), tokenHash: text("token").notNull(),
roleId: integer("roleId") roleId: integer("roleId")
.notNull() .notNull()
.references(() => roles.roleId, { onDelete: "cascade" }), .references(() => roles.roleId, { onDelete: "cascade" })
}); });
export const resourcePincode = sqliteTable("resourcePincode", { export const resourcePincode = sqliteTable("resourcePincode", {
pincodeId: integer("pincodeId").primaryKey({ pincodeId: integer("pincodeId").primaryKey({
autoIncrement: true, autoIncrement: true
}), }),
resourceId: integer("resourceId") resourceId: integer("resourceId")
.notNull() .notNull()
.references(() => resources.resourceId, { onDelete: "cascade" }), .references(() => resources.resourceId, { onDelete: "cascade" }),
pincodeHash: text("pincodeHash").notNull(), pincodeHash: text("pincodeHash").notNull(),
digitLength: integer("digitLength").notNull(), digitLength: integer("digitLength").notNull()
}); });
export const resourcePassword = sqliteTable("resourcePassword", { export const resourcePassword = sqliteTable("resourcePassword", {
passwordId: integer("passwordId").primaryKey({ passwordId: integer("passwordId").primaryKey({
autoIncrement: true, autoIncrement: true
}), }),
resourceId: integer("resourceId") resourceId: integer("resourceId")
.notNull() .notNull()
.references(() => resources.resourceId, { onDelete: "cascade" }), .references(() => resources.resourceId, { onDelete: "cascade" }),
passwordHash: text("passwordHash").notNull(), passwordHash: text("passwordHash").notNull()
}); });
export const resourceSessions = sqliteTable("resourceSessions", { export const resourceSessions = sqliteTable("resourceSessions", {
@ -282,31 +282,49 @@ export const resourceSessions = sqliteTable("resourceSessions", {
resourceId: integer("resourceId") resourceId: integer("resourceId")
.notNull() .notNull()
.references(() => resources.resourceId, { onDelete: "cascade" }), .references(() => resources.resourceId, { onDelete: "cascade" }),
usedOtp: integer("usedOtp", { mode: "boolean" }).notNull().default(false),
expiresAt: integer("expiresAt").notNull(), expiresAt: integer("expiresAt").notNull(),
passwordId: integer("passwordId").references( passwordId: integer("passwordId").references(
() => resourcePassword.passwordId, () => resourcePassword.passwordId,
{ {
onDelete: "cascade", onDelete: "cascade"
}, }
), ),
pincodeId: integer("pincodeId").references( pincodeId: integer("pincodeId").references(
() => resourcePincode.pincodeId, () => resourcePincode.pincodeId,
{ {
onDelete: "cascade", onDelete: "cascade"
}, }
), ),
whitelistId: integer("whitelistId").references(
() => resourceWhitelistedEmail.whitelistId,
{
onDelete: "cascade"
}
)
}); });
export const resourceWhitelistedEmail = sqliteTable(
"resourceWhitelistedEmail",
{
whitelistId: integer("id").primaryKey({ autoIncrement: true }),
email: text("email").primaryKey(),
resourceId: integer("resourceId")
.notNull()
.references(() => resources.resourceId, { onDelete: "cascade" })
}
);
export const resourceOtp = sqliteTable("resourceOtp", { export const resourceOtp = sqliteTable("resourceOtp", {
otpId: integer("otpId").primaryKey({ otpId: integer("otpId").primaryKey({
autoIncrement: true, autoIncrement: true
}), }),
resourceId: integer("resourceId") resourceId: integer("resourceId")
.notNull() .notNull()
.references(() => resources.resourceId, { onDelete: "cascade" }), .references(() => resources.resourceId, { onDelete: "cascade" }),
email: text("email").notNull(), email: text("email").notNull(),
otpHash: text("otpHash").notNull(), otpHash: text("otpHash").notNull(),
expiresAt: integer("expiresAt").notNull(), expiresAt: integer("expiresAt").notNull()
}); });
export type Org = InferSelectModel<typeof orgs>; export type Org = InferSelectModel<typeof orgs>;

View file

@ -0,0 +1,71 @@
import {
Body,
Container,
Head,
Heading,
Html,
Preview,
Section,
Text,
Tailwind
} from "@react-email/components";
import * as React from "react";
interface ResourceOTPCodeProps {
email?: string;
resourceName: string;
orgName: string;
otp: string;
}
export const ResourceOTPCode = ({
email,
resourceName,
orgName: organizationName,
otp
}: ResourceOTPCodeProps) => {
const previewText = `Your one-time password for ${resourceName} is ready!`;
return (
<Html>
<Head />
<Preview>{previewText}</Preview>
<Tailwind
config={{
theme: {
extend: {
colors: {
primary: "#F97317"
}
}
}
}}
>
<Body className="font-sans">
<Container className="bg-white border border-solid border-gray-200 p-6 max-w-lg mx-auto my-8 rounded-lg">
<Heading className="text-2xl font-semibold text-gray-800 text-center">
Your One-Time Password
</Heading>
<Text className="text-base text-gray-700 mt-4">
Hi {email || "there"},
</Text>
<Text className="text-base text-gray-700 mt-2">
Youve requested a one-time password (OTP) to
authenticate with the resource{" "}
<strong>{resourceName}</strong> in{" "}
<strong>{organizationName}</strong>. Use the OTP
below to complete your authentication:
</Text>
<Section className="text-center my-6">
<Text className="inline-block bg-primary text-xl font-bold text-white py-2 px-4 border border-gray-300 rounded-xl">
{otp}
</Text>
</Section>
</Container>
</Body>
</Tailwind>
</Html>
);
};
export default ResourceOTPCode;

View file

@ -71,11 +71,6 @@ export const SendInviteLink = ({
Accept invitation to {orgName} Accept invitation to {orgName}
</Button> </Button>
</Section> </Section>
<Text className="text-sm text-gray-500 mt-6">
Best regards,
<br />
Fossorial
</Text>
</Container> </Container>
</Body> </Body>
</Tailwind> </Tailwind>

View file

@ -63,11 +63,6 @@ export const VerifyEmail = ({
If you didnt request this, you can safely ignore If you didnt request this, you can safely ignore
this email. this email.
</Text> </Text>
<Text className="text-sm text-gray-500 mt-6">
Best regards,
<br />
Fossorial
</Text>
</Container> </Container>
</Body> </Body>
</Tailwind> </Tailwind>

View file

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

View file

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

View file

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

View file

@ -10,7 +10,7 @@ import { formatAxiosError } from "@app/lib/utils";
import { import {
GetResourceAuthInfoResponse, GetResourceAuthInfoResponse,
ListResourceRolesResponse, ListResourceRolesResponse,
ListResourceUsersResponse, ListResourceUsersResponse
} from "@server/routers/resource"; } from "@server/routers/resource";
import { Button } from "@app/components/ui/button"; import { Button } from "@app/components/ui/button";
import { set, z } from "zod"; import { set, z } from "zod";
@ -24,7 +24,7 @@ import {
FormField, FormField,
FormItem, FormItem,
FormLabel, FormLabel,
FormMessage, FormMessage
} from "@app/components/ui/form"; } from "@app/components/ui/form";
import { TagInput } from "emblor"; import { TagInput } from "emblor";
import SettingsSectionTitle from "@app/components/SettingsSectionTitle"; import SettingsSectionTitle from "@app/components/SettingsSectionTitle";
@ -42,15 +42,15 @@ const UsersRolesFormSchema = z.object({
roles: z.array( roles: z.array(
z.object({ z.object({
id: z.string(), id: z.string(),
text: z.string(), text: z.string()
}), })
), ),
users: z.array( users: z.array(
z.object({ z.object({
id: z.string(), id: z.string(),
text: z.string(), text: z.string()
}), })
), )
}); });
export default function ResourceAuthenticationPage() { export default function ResourceAuthenticationPage() {
@ -64,10 +64,10 @@ export default function ResourceAuthenticationPage() {
const [pageLoading, setPageLoading] = useState(true); const [pageLoading, setPageLoading] = useState(true);
const [allRoles, setAllRoles] = useState<{ id: string; text: string }[]>( const [allRoles, setAllRoles] = useState<{ id: string; text: string }[]>(
[], []
); );
const [allUsers, setAllUsers] = useState<{ id: string; text: string }[]>( const [allUsers, setAllUsers] = useState<{ id: string; text: string }[]>(
[], []
); );
const [activeRolesTagIndex, setActiveRolesTagIndex] = useState< const [activeRolesTagIndex, setActiveRolesTagIndex] = useState<
number | null number | null
@ -90,7 +90,7 @@ export default function ResourceAuthenticationPage() {
const usersRolesForm = useForm<z.infer<typeof UsersRolesFormSchema>>({ const usersRolesForm = useForm<z.infer<typeof UsersRolesFormSchema>>({
resolver: zodResolver(UsersRolesFormSchema), resolver: zodResolver(UsersRolesFormSchema),
defaultValues: { roles: [], users: [] }, defaultValues: { roles: [], users: [] }
}); });
useEffect(() => { useEffect(() => {
@ -100,29 +100,29 @@ export default function ResourceAuthenticationPage() {
rolesResponse, rolesResponse,
resourceRolesResponse, resourceRolesResponse,
usersResponse, usersResponse,
resourceUsersResponse, resourceUsersResponse
] = await Promise.all([ ] = await Promise.all([
api.get<AxiosResponse<ListRolesResponse>>( api.get<AxiosResponse<ListRolesResponse>>(
`/org/${org?.org.orgId}/roles`, `/org/${org?.org.orgId}/roles`
), ),
api.get<AxiosResponse<ListResourceRolesResponse>>( api.get<AxiosResponse<ListResourceRolesResponse>>(
`/resource/${resource.resourceId}/roles`, `/resource/${resource.resourceId}/roles`
), ),
api.get<AxiosResponse<ListUsersResponse>>( api.get<AxiosResponse<ListUsersResponse>>(
`/org/${org?.org.orgId}/users`, `/org/${org?.org.orgId}/users`
), ),
api.get<AxiosResponse<ListResourceUsersResponse>>( api.get<AxiosResponse<ListResourceUsersResponse>>(
`/resource/${resource.resourceId}/users`, `/resource/${resource.resourceId}/users`
), )
]); ]);
setAllRoles( setAllRoles(
rolesResponse.data.data.roles rolesResponse.data.data.roles
.map((role) => ({ .map((role) => ({
id: role.roleId.toString(), id: role.roleId.toString(),
text: role.name, text: role.name
})) }))
.filter((role) => role.text !== "Admin"), .filter((role) => role.text !== "Admin")
); );
usersRolesForm.setValue( usersRolesForm.setValue(
@ -130,24 +130,24 @@ export default function ResourceAuthenticationPage() {
resourceRolesResponse.data.data.roles resourceRolesResponse.data.data.roles
.map((i) => ({ .map((i) => ({
id: i.roleId.toString(), id: i.roleId.toString(),
text: i.name, text: i.name
})) }))
.filter((role) => role.text !== "Admin"), .filter((role) => role.text !== "Admin")
); );
setAllUsers( setAllUsers(
usersResponse.data.data.users.map((user) => ({ usersResponse.data.data.users.map((user) => ({
id: user.id.toString(), id: user.id.toString(),
text: user.email, text: user.email
})), }))
); );
usersRolesForm.setValue( usersRolesForm.setValue(
"users", "users",
resourceUsersResponse.data.data.users.map((i) => ({ resourceUsersResponse.data.data.users.map((i) => ({
id: i.userId.toString(), id: i.userId.toString(),
text: i.email, text: i.email
})), }))
); );
setPageLoading(false); setPageLoading(false);
@ -158,8 +158,8 @@ export default function ResourceAuthenticationPage() {
title: "Failed to fetch data", title: "Failed to fetch data",
description: formatAxiosError( description: formatAxiosError(
e, e,
"An error occurred while fetching the data", "An error occurred while fetching the data"
), )
}); });
} }
}; };
@ -168,36 +168,36 @@ export default function ResourceAuthenticationPage() {
}, []); }, []);
async function onSubmitUsersRoles( async function onSubmitUsersRoles(
data: z.infer<typeof UsersRolesFormSchema>, data: z.infer<typeof UsersRolesFormSchema>
) { ) {
try { try {
setLoadingSaveUsersRoles(true); setLoadingSaveUsersRoles(true);
const jobs = [ const jobs = [
api.post(`/resource/${resource.resourceId}/roles`, { api.post(`/resource/${resource.resourceId}/roles`, {
roleIds: data.roles.map((i) => parseInt(i.id)), roleIds: data.roles.map((i) => parseInt(i.id))
}), }),
api.post(`/resource/${resource.resourceId}/users`, { api.post(`/resource/${resource.resourceId}/users`, {
userIds: data.users.map((i) => i.id), userIds: data.users.map((i) => i.id)
}), }),
api.post(`/resource/${resource.resourceId}`, { api.post(`/resource/${resource.resourceId}`, {
sso: ssoEnabled, sso: ssoEnabled
}), })
]; ];
await Promise.all(jobs); await Promise.all(jobs);
updateResource({ updateResource({
sso: ssoEnabled, sso: ssoEnabled
}); });
updateAuthInfo({ updateAuthInfo({
sso: ssoEnabled, sso: ssoEnabled
}); });
toast({ toast({
title: "Saved successfully", title: "Saved successfully",
description: "Authentication settings have been saved", description: "Authentication settings have been saved"
}); });
} catch (e) { } catch (e) {
console.error(e); console.error(e);
@ -206,8 +206,8 @@ export default function ResourceAuthenticationPage() {
title: "Failed to set roles", title: "Failed to set roles",
description: formatAxiosError( description: formatAxiosError(
e, e,
"An error occurred while setting the roles", "An error occurred while setting the roles"
), )
}); });
} finally { } finally {
setLoadingSaveUsersRoles(false); setLoadingSaveUsersRoles(false);
@ -218,17 +218,17 @@ export default function ResourceAuthenticationPage() {
setLoadingRemoveResourcePassword(true); setLoadingRemoveResourcePassword(true);
api.post(`/resource/${resource.resourceId}/password`, { api.post(`/resource/${resource.resourceId}/password`, {
password: null, password: null
}) })
.then(() => { .then(() => {
toast({ toast({
title: "Resource password removed", title: "Resource password removed",
description: description:
"The resource password has been removed successfully", "The resource password has been removed successfully"
}); });
updateAuthInfo({ updateAuthInfo({
password: false, password: false
}); });
}) })
.catch((e) => { .catch((e) => {
@ -237,8 +237,8 @@ export default function ResourceAuthenticationPage() {
title: "Error removing resource password", title: "Error removing resource password",
description: formatAxiosError( description: formatAxiosError(
e, e,
"An error occurred while removing the resource password", "An error occurred while removing the resource password"
), )
}); });
}) })
.finally(() => setLoadingRemoveResourcePassword(false)); .finally(() => setLoadingRemoveResourcePassword(false));
@ -248,17 +248,17 @@ export default function ResourceAuthenticationPage() {
setLoadingRemoveResourcePincode(true); setLoadingRemoveResourcePincode(true);
api.post(`/resource/${resource.resourceId}/pincode`, { api.post(`/resource/${resource.resourceId}/pincode`, {
pincode: null, pincode: null
}) })
.then(() => { .then(() => {
toast({ toast({
title: "Resource pincode removed", title: "Resource pincode removed",
description: description:
"The resource password has been removed successfully", "The resource password has been removed successfully"
}); });
updateAuthInfo({ updateAuthInfo({
pincode: false, pincode: false
}); });
}) })
.catch((e) => { .catch((e) => {
@ -267,8 +267,8 @@ export default function ResourceAuthenticationPage() {
title: "Error removing resource pincode", title: "Error removing resource pincode",
description: formatAxiosError( description: formatAxiosError(
e, e,
"An error occurred while removing the resource pincode", "An error occurred while removing the resource pincode"
), )
}); });
}) })
.finally(() => setLoadingRemoveResourcePincode(false)); .finally(() => setLoadingRemoveResourcePincode(false));
@ -288,7 +288,7 @@ export default function ResourceAuthenticationPage() {
onSetPassword={() => { onSetPassword={() => {
setIsSetPasswordOpen(false); setIsSetPasswordOpen(false);
updateAuthInfo({ updateAuthInfo({
password: true, password: true
}); });
}} }}
/> />
@ -302,7 +302,7 @@ export default function ResourceAuthenticationPage() {
onSetPincode={() => { onSetPincode={() => {
setIsSetPincodeOpen(false); setIsSetPincodeOpen(false);
updateAuthInfo({ updateAuthInfo({
pincode: true, pincode: true
}); });
}} }}
/> />
@ -336,7 +336,7 @@ export default function ResourceAuthenticationPage() {
<Form {...usersRolesForm}> <Form {...usersRolesForm}>
<form <form
onSubmit={usersRolesForm.handleSubmit( onSubmit={usersRolesForm.handleSubmit(
onSubmitUsersRoles, onSubmitUsersRoles
)} )}
className="space-y-8" className="space-y-8"
> >
@ -365,8 +365,8 @@ export default function ResourceAuthenticationPage() {
"roles", "roles",
newRoles as [ newRoles as [
Tag, Tag,
...Tag[], ...Tag[]
], ]
); );
}} }}
enableAutocomplete={true} enableAutocomplete={true}
@ -378,11 +378,11 @@ export default function ResourceAuthenticationPage() {
sortTags={true} sortTags={true}
styleClasses={{ styleClasses={{
tag: { tag: {
body: "bg-muted hover:bg-accent text-foreground py-2 px-3 rounded-full", body: "bg-muted hover:bg-accent text-foreground py-2 px-3 rounded-full"
}, },
input: "border-none bg-transparent text-inherit placeholder:text-inherit shadow-none", input: "border-none bg-transparent text-inherit placeholder:text-inherit shadow-none",
inlineTagsContainer: inlineTagsContainer:
"bg-transparent", "bg-transparent"
}} }}
/> />
</FormControl> </FormControl>
@ -420,8 +420,8 @@ export default function ResourceAuthenticationPage() {
"users", "users",
newUsers as [ newUsers as [
Tag, Tag,
...Tag[], ...Tag[]
], ]
); );
}} }}
enableAutocomplete={true} enableAutocomplete={true}
@ -433,11 +433,11 @@ export default function ResourceAuthenticationPage() {
sortTags={true} sortTags={true}
styleClasses={{ styleClasses={{
tag: { tag: {
body: "bg-muted hover:bg-accent text-foreground py-2 px-3 rounded-full", body: "bg-muted hover:bg-accent text-foreground py-2 px-3 rounded-full"
}, },
input: "border-none bg-transparent text-inherit placeholder:text-inherit shadow-none", input: "border-none bg-transparent text-inherit placeholder:text-inherit shadow-none",
inlineTagsContainer: inlineTagsContainer:
"bg-transparent", "bg-transparent"
}} }}
/> />
</FormControl> </FormControl>
@ -468,7 +468,7 @@ export default function ResourceAuthenticationPage() {
<section className="space-y-8"> <section className="space-y-8">
<SettingsSectionTitle <SettingsSectionTitle
title="Authentication Methods" title="Authentication Methods"
description="Allow anyone to access the resource via the below methods" description="Allow access to the resource via additional auth methods"
size="1xl" size="1xl"
/> />

View file

@ -10,7 +10,7 @@ import {
CardDescription, CardDescription,
CardFooter, CardFooter,
CardHeader, CardHeader,
CardTitle, CardTitle
} from "@/components/ui/card"; } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
@ -18,16 +18,26 @@ import { Input } from "@/components/ui/input";
import { import {
Form, Form,
FormControl, FormControl,
FormDescription,
FormField, FormField,
FormItem, FormItem,
FormLabel, FormLabel,
FormMessage, FormMessage
} from "@/components/ui/form"; } from "@/components/ui/form";
import { LockIcon, Binary, Key, User } from "lucide-react"; import {
LockIcon,
Binary,
Key,
User,
Send,
ArrowLeft,
ArrowRight,
Lock
} from "lucide-react";
import { import {
InputOTP, InputOTP,
InputOTPGroup, InputOTPGroup,
InputOTPSlot, InputOTPSlot
} from "@app/components/ui/input-otp"; } from "@app/components/ui/input-otp";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { Alert, AlertDescription } from "@app/components/ui/alert"; import { Alert, AlertDescription } from "@app/components/ui/alert";
@ -39,18 +49,45 @@ import { redirect } from "next/dist/server/api-utils";
import ResourceAccessDenied from "./ResourceAccessDenied"; import ResourceAccessDenied from "./ResourceAccessDenied";
import { createApiClient } from "@app/api"; import { createApiClient } from "@app/api";
import { useEnvContext } from "@app/hooks/useEnvContext"; import { useEnvContext } from "@app/hooks/useEnvContext";
import { useToast } from "@app/hooks/useToast";
const pin = z
.string()
.length(6, { message: "PIN must be exactly 6 digits" })
.regex(/^\d+$/, { message: "PIN must only contain numbers" });
const pinSchema = z.object({ const pinSchema = z.object({
pin: z pin
.string() });
.length(6, { message: "PIN must be exactly 6 digits" })
.regex(/^\d+$/, { message: "PIN must only contain numbers" }), const pinRequestOtpSchema = z.object({
pin,
email: z.string().email()
});
const pinOtpSchema = z.object({
pin,
email: z.string().email(),
otp: z.string()
});
const password = z.string().min(1, {
message: "Password must be at least 1 character long"
}); });
const passwordSchema = z.object({ const passwordSchema = z.object({
password: z password
.string() });
.min(1, { message: "Password must be at least 1 character long" }),
const passwordRequestOtpSchema = z.object({
password,
email: z.string().email()
});
const passwordOtpSchema = z.object({
password,
email: z.string().email(),
otp: z.string()
}); });
type ResourceAuthPortalProps = { type ResourceAuthPortalProps = {
@ -68,6 +105,7 @@ type ResourceAuthPortalProps = {
export default function ResourceAuthPortal(props: ResourceAuthPortalProps) { export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
const router = useRouter(); const router = useRouter();
const { toast } = useToast();
const getNumMethods = () => { const getNumMethods = () => {
let colLength = 0; let colLength = 0;
@ -84,6 +122,10 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
const [accessDenied, setAccessDenied] = useState<boolean>(false); const [accessDenied, setAccessDenied] = useState<boolean>(false);
const [loadingLogin, setLoadingLogin] = useState(false); const [loadingLogin, setLoadingLogin] = useState(false);
const [otpState, setOtpState] = useState<
"idle" | "otp_requested" | "otp_sent"
>("idle");
const api = createApiClient(useEnvContext()); const api = createApiClient(useEnvContext());
function getDefaultSelectedMethod() { function getDefaultSelectedMethod() {
@ -104,25 +146,77 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
const pinForm = useForm<z.infer<typeof pinSchema>>({ const pinForm = useForm<z.infer<typeof pinSchema>>({
resolver: zodResolver(pinSchema), resolver: zodResolver(pinSchema),
defaultValues: {
pin: ""
}
});
const pinRequestOtpForm = useForm<z.infer<typeof pinRequestOtpSchema>>({
resolver: zodResolver(pinRequestOtpSchema),
defaultValues: { defaultValues: {
pin: "", pin: "",
}, email: ""
}
});
const pinOtpForm = useForm<z.infer<typeof pinOtpSchema>>({
resolver: zodResolver(pinOtpSchema),
defaultValues: {
pin: "",
email: "",
otp: ""
}
}); });
const passwordForm = useForm<z.infer<typeof passwordSchema>>({ const passwordForm = useForm<z.infer<typeof passwordSchema>>({
resolver: zodResolver(passwordSchema), resolver: zodResolver(passwordSchema),
defaultValues: { defaultValues: {
password: "", password: ""
}, }
}); });
const onPinSubmit = (values: z.infer<typeof pinSchema>) => { const passwordRequestOtpForm = useForm<
z.infer<typeof passwordRequestOtpSchema>
>({
resolver: zodResolver(passwordRequestOtpSchema),
defaultValues: {
password: "",
email: ""
}
});
const passwordOtpForm = useForm<z.infer<typeof passwordOtpSchema>>({
resolver: zodResolver(passwordOtpSchema),
defaultValues: {
password: "",
email: "",
otp: ""
}
});
const onPinSubmit = (values: any) => {
setLoadingLogin(true); setLoadingLogin(true);
api.post<AxiosResponse<AuthWithPasswordResponse>>( api.post<AxiosResponse<AuthWithPasswordResponse>>(
`/auth/resource/${props.resource.id}/pincode`, `/auth/resource/${props.resource.id}/pincode`,
{ pincode: values.pin }, { pincode: values.pin, email: values.email, otp: values.otp }
) )
.then((res) => { .then((res) => {
setPincodeError(null);
if (res.data.data.otpRequested) {
setOtpState("otp_requested");
pinRequestOtpForm.setValue("pin", values.pin);
return;
} else if (res.data.data.otpSent) {
pinOtpForm.setValue("email", values.email);
pinOtpForm.setValue("pin", values.pin);
toast({
title: "OTP Sent",
description: `OTP sent to ${values.email}`
});
setOtpState("otp_sent");
return;
}
const session = res.data.data.session; const session = res.data.data.session;
if (session) { if (session) {
window.location.href = props.redirect; window.location.href = props.redirect;
@ -131,21 +225,59 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
.catch((e) => { .catch((e) => {
console.error(e); console.error(e);
setPincodeError( setPincodeError(
formatAxiosError(e, "Failed to authenticate with pincode"), formatAxiosError(e, "Failed to authenticate with pincode")
); );
}) })
.then(() => setLoadingLogin(false)); .then(() => setLoadingLogin(false));
}; };
const onPasswordSubmit = (values: z.infer<typeof passwordSchema>) => { const resetPasswordForms = () => {
passwordForm.reset();
passwordRequestOtpForm.reset();
passwordOtpForm.reset();
setOtpState("idle");
setPasswordError(null);
};
const resetPinForms = () => {
pinForm.reset();
pinRequestOtpForm.reset();
pinOtpForm.reset();
setOtpState("idle");
setPincodeError(null);
}
const onPasswordSubmit = (values: any) => {
setLoadingLogin(true); setLoadingLogin(true);
api.post<AxiosResponse<AuthWithPasswordResponse>>( api.post<AxiosResponse<AuthWithPasswordResponse>>(
`/auth/resource/${props.resource.id}/password`, `/auth/resource/${props.resource.id}/password`,
{ {
password: values.password, password: values.password,
}, email: values.email,
otp: values.otp
}
) )
.then((res) => { .then((res) => {
setPasswordError(null);
if (res.data.data.otpRequested) {
setOtpState("otp_requested");
passwordRequestOtpForm.setValue(
"password",
values.password
);
return;
} else if (res.data.data.otpSent) {
passwordOtpForm.setValue("email", values.email);
passwordOtpForm.setValue("password", values.password);
toast({
title: "OTP Sent",
description: `OTP sent to ${values.email}`
});
setOtpState("otp_sent");
return;
}
const session = res.data.data.session; const session = res.data.data.session;
if (session) { if (session) {
window.location.href = props.redirect; window.location.href = props.redirect;
@ -154,7 +286,7 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
.catch((e) => { .catch((e) => {
console.error(e); console.error(e);
setPasswordError( setPasswordError(
formatAxiosError(e, "Failed to authenticate with password"), formatAxiosError(e, "Failed to authenticate with password")
); );
}) })
.finally(() => setLoadingLogin(false)); .finally(() => setLoadingLogin(false));
@ -233,86 +365,237 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
value="pin" value="pin"
className={`${numMethods <= 1 ? "mt-0" : ""}`} className={`${numMethods <= 1 ? "mt-0" : ""}`}
> >
<Form {...pinForm}> {otpState === "idle" && (
<form <Form {...pinForm}>
onSubmit={pinForm.handleSubmit( <form
onPinSubmit, onSubmit={pinForm.handleSubmit(
)} onPinSubmit
className="space-y-4"
>
<FormField
control={pinForm.control}
name="pin"
render={({ field }) => (
<FormItem>
<FormLabel>
6-digit PIN Code
</FormLabel>
<FormControl>
<div className="flex justify-center">
<InputOTP
maxLength={
6
}
{...field}
>
<InputOTPGroup className="flex">
<InputOTPSlot
index={
0
}
/>
<InputOTPSlot
index={
1
}
/>
<InputOTPSlot
index={
2
}
/>
<InputOTPSlot
index={
3
}
/>
<InputOTPSlot
index={
4
}
/>
<InputOTPSlot
index={
5
}
/>
</InputOTPGroup>
</InputOTP>
</div>
</FormControl>
<FormMessage />
</FormItem>
)} )}
/> className="space-y-4"
{pincodeError && (
<Alert variant="destructive">
<AlertDescription>
{pincodeError}
</AlertDescription>
</Alert>
)}
<Button
type="submit"
className="w-full"
loading={loadingLogin}
disabled={loadingLogin}
> >
<LockIcon className="w-4 h-4 mr-2" /> <FormField
Login with PIN control={
</Button> pinForm.control
</form> }
</Form> name="pin"
render={({ field }) => (
<FormItem>
<FormLabel>
6-digit PIN
Code
</FormLabel>
<FormControl>
<div className="flex justify-center">
<InputOTP
maxLength={
6
}
{...field}
>
<InputOTPGroup className="flex">
<InputOTPSlot
index={
0
}
/>
<InputOTPSlot
index={
1
}
/>
<InputOTPSlot
index={
2
}
/>
<InputOTPSlot
index={
3
}
/>
<InputOTPSlot
index={
4
}
/>
<InputOTPSlot
index={
5
}
/>
</InputOTPGroup>
</InputOTP>
</div>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{pincodeError && (
<Alert variant="destructive">
<AlertDescription>
{pincodeError}
</AlertDescription>
</Alert>
)}
<Button
type="submit"
className="w-full"
loading={loadingLogin}
disabled={loadingLogin}
>
<LockIcon className="w-4 h-4 mr-2" />
Login with PIN
</Button>
</form>
</Form>
)}
{otpState === "otp_requested" && (
<Form {...pinRequestOtpForm}>
<form
onSubmit={pinRequestOtpForm.handleSubmit(
onPinSubmit
)}
className="space-y-4"
>
<FormField
control={
pinRequestOtpForm.control
}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>
Email
</FormLabel>
<FormControl>
<Input
placeholder="Enter email"
type="email"
{...field}
/>
</FormControl>
<FormDescription>
A one-time
code will be
sent to this
email.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
{pincodeError && (
<Alert variant="destructive">
<AlertDescription>
{pincodeError}
</AlertDescription>
</Alert>
)}
<Button
type="submit"
className="w-full"
loading={loadingLogin}
disabled={loadingLogin}
>
<Send className="w-4 h-4 mr-2" />
Send OTP
</Button>
<Button
type="button"
className="w-full"
variant={"outline"}
onClick={() =>
resetPinForms()
}
>
Back to PIN
</Button>
</form>
</Form>
)}
{otpState === "otp_sent" && (
<Form {...pinOtpForm}>
<form
onSubmit={pinOtpForm.handleSubmit(
onPinSubmit
)}
className="space-y-4"
>
<FormField
control={
pinOtpForm.control
}
name="otp"
render={({ field }) => (
<FormItem>
<FormLabel>
One-Time
Password
(OTP)
</FormLabel>
<FormControl>
<Input
placeholder="Enter OTP"
type="otp"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{pincodeError && (
<Alert variant="destructive">
<AlertDescription>
{pincodeError}
</AlertDescription>
</Alert>
)}
<Button
type="submit"
className="w-full"
loading={loadingLogin}
disabled={loadingLogin}
>
<LockIcon className="w-4 h-4 mr-2" />
Submit OTP
</Button>
<Button
type="button"
className="w-full"
variant={"outline"}
onClick={() => {
setOtpState(
"otp_requested"
);
pinOtpForm.reset();
}}
>
Resend OTP
</Button>
<Button
type="button"
className="w-full"
variant={"outline"}
onClick={() =>
resetPinForms()
}
>
Back to PIN
</Button>
</form>
</Form>
)}
</TabsContent> </TabsContent>
)} )}
{props.methods.password && ( {props.methods.password && (
@ -320,52 +603,202 @@ export default function ResourceAuthPortal(props: ResourceAuthPortalProps) {
value="password" value="password"
className={`${numMethods <= 1 ? "mt-0" : ""}`} className={`${numMethods <= 1 ? "mt-0" : ""}`}
> >
<Form {...passwordForm}> {otpState === "idle" && (
<form <Form {...passwordForm}>
onSubmit={passwordForm.handleSubmit( <form
onPasswordSubmit, onSubmit={passwordForm.handleSubmit(
)} onPasswordSubmit
className="space-y-4"
>
<FormField
control={
passwordForm.control
}
name="password"
render={({ field }) => (
<FormItem>
<FormLabel>
Password
</FormLabel>
<FormControl>
<Input
placeholder="Enter password"
type="password"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)} )}
/> className="space-y-4"
{passwordError && (
<Alert variant="destructive">
<AlertDescription>
{passwordError}
</AlertDescription>
</Alert>
)}
<Button
type="submit"
className="w-full"
loading={loadingLogin}
disabled={loadingLogin}
> >
<LockIcon className="w-4 h-4 mr-2" /> <FormField
Login with Password control={
</Button> passwordForm.control
</form> }
</Form> name="password"
render={({ field }) => (
<FormItem>
<FormLabel>
Password
</FormLabel>
<FormControl>
<Input
placeholder="Enter password"
type="password"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{passwordError && (
<Alert variant="destructive">
<AlertDescription>
{passwordError}
</AlertDescription>
</Alert>
)}
<Button
type="submit"
className="w-full"
loading={loadingLogin}
disabled={loadingLogin}
>
<LockIcon className="w-4 h-4 mr-2" />
Login with Password
</Button>
</form>
</Form>
)}
{otpState === "otp_requested" && (
<Form {...passwordRequestOtpForm}>
<form
onSubmit={passwordRequestOtpForm.handleSubmit(
onPasswordSubmit
)}
className="space-y-4"
>
<FormField
control={
passwordRequestOtpForm.control
}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>
Email
</FormLabel>
<FormControl>
<Input
placeholder="Enter email"
type="email"
{...field}
/>
</FormControl>
<FormDescription>
A one-time
code will be
sent to this
email.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
{passwordError && (
<Alert variant="destructive">
<AlertDescription>
{passwordError}
</AlertDescription>
</Alert>
)}
<Button
type="submit"
className="w-full"
loading={loadingLogin}
disabled={loadingLogin}
>
<Send className="w-4 h-4 mr-2" />
Send OTP
</Button>
<Button
type="button"
className="w-full"
variant={"outline"}
onClick={() =>
resetPasswordForms()
}
>
Back to Password
</Button>
</form>
</Form>
)}
{otpState === "otp_sent" && (
<Form {...passwordOtpForm}>
<form
onSubmit={passwordOtpForm.handleSubmit(
onPasswordSubmit
)}
className="space-y-4"
>
<FormField
control={
passwordOtpForm.control
}
name="otp"
render={({ field }) => (
<FormItem>
<FormLabel>
One-Time
Password
(OTP)
</FormLabel>
<FormControl>
<Input
placeholder="Enter OTP"
type="otp"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
{passwordError && (
<Alert variant="destructive">
<AlertDescription>
{passwordError}
</AlertDescription>
</Alert>
)}
<Button
type="submit"
className="w-full"
loading={loadingLogin}
disabled={loadingLogin}
>
<LockIcon className="w-4 h-4 mr-2" />
Submit OTP
</Button>
<Button
type="button"
className="w-full"
variant={"outline"}
onClick={() => {
setOtpState(
"otp_requested"
);
passwordOtpForm.reset();
}}
>
Resend OTP
</Button>
<Button
type="button"
className="w-full"
variant={"outline"}
onClick={() =>
resetPasswordForms()
}
>
Back to Password
</Button>
</form>
</Form>
)}
</TabsContent> </TabsContent>
)} )}
{props.methods.sso && ( {props.methods.sso && (

View file

@ -23,11 +23,12 @@ import {
} from "@/components/ui/card"; } from "@/components/ui/card";
import { Alert, AlertDescription } from "@/components/ui/alert"; import { Alert, AlertDescription } from "@/components/ui/alert";
import { LoginResponse } from "@server/routers/auth"; import { LoginResponse } from "@server/routers/auth";
import { api } from "@app/api";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { AxiosResponse } from "axios"; import { AxiosResponse } from "axios";
import { formatAxiosError } from "@app/lib/utils"; import { formatAxiosError } from "@app/lib/utils";
import { LockIcon } from "lucide-react"; import { LockIcon } from "lucide-react";
import { createApiClient } from "@app/api";
import { useEnvContext } from "@app/hooks/useEnvContext";
type LoginFormProps = { type LoginFormProps = {
redirect?: string; redirect?: string;
@ -44,6 +45,8 @@ const formSchema = z.object({
export default function LoginForm({ redirect, onLogin }: LoginFormProps) { export default function LoginForm({ redirect, onLogin }: LoginFormProps) {
const router = useRouter(); const router = useRouter();
const api = createApiClient(useEnvContext());
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@ -58,6 +61,7 @@ export default function LoginForm({ redirect, onLogin }: LoginFormProps) {
async function onSubmit(values: z.infer<typeof formSchema>) { async function onSubmit(values: z.infer<typeof formSchema>) {
const { email, password } = values; const { email, password } = values;
setLoading(true); setLoading(true);
const res = await api const res = await api