mirror of
https://github.com/fosrl/pangolin.git
synced 2025-08-04 01:55:10 +02:00
add otp flow to resource auth portal
This commit is contained in:
parent
d3d2fe398b
commit
998fab6d0a
14 changed files with 1159 additions and 376 deletions
|
@ -16,15 +16,17 @@ export async function createResourceSession(opts: {
|
|||
resourceId: number;
|
||||
passwordId?: number;
|
||||
pincodeId?: number;
|
||||
whitelistId: number;
|
||||
usedOtp?: boolean;
|
||||
}): Promise<ResourceSession> {
|
||||
if (!opts.passwordId && !opts.pincodeId) {
|
||||
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(
|
||||
sha256(new TextEncoder().encode(opts.token)),
|
||||
sha256(new TextEncoder().encode(opts.token))
|
||||
);
|
||||
|
||||
const session: ResourceSession = {
|
||||
|
@ -33,6 +35,8 @@ export async function createResourceSession(opts: {
|
|||
resourceId: opts.resourceId,
|
||||
passwordId: opts.passwordId || null,
|
||||
pincodeId: opts.pincodeId || null,
|
||||
whitelistId: opts.whitelistId,
|
||||
usedOtp: opts.usedOtp || false
|
||||
};
|
||||
|
||||
await db.insert(resourceSessions).values(session);
|
||||
|
@ -42,10 +46,10 @@ export async function createResourceSession(opts: {
|
|||
|
||||
export async function validateResourceSessionToken(
|
||||
token: string,
|
||||
resourceId: number,
|
||||
resourceId: number
|
||||
): Promise<ResourceSessionValidationResult> {
|
||||
const sessionId = encodeHexLowerCase(
|
||||
sha256(new TextEncoder().encode(token)),
|
||||
sha256(new TextEncoder().encode(token))
|
||||
);
|
||||
const result = await db
|
||||
.select()
|
||||
|
@ -53,8 +57,8 @@ export async function validateResourceSessionToken(
|
|||
.where(
|
||||
and(
|
||||
eq(resourceSessions.sessionId, sessionId),
|
||||
eq(resourceSessions.resourceId, resourceId),
|
||||
),
|
||||
eq(resourceSessions.resourceId, resourceId)
|
||||
)
|
||||
);
|
||||
|
||||
if (result.length < 1) {
|
||||
|
@ -65,12 +69,12 @@ export async function validateResourceSessionToken(
|
|||
|
||||
if (Date.now() >= resourceSession.expiresAt - SESSION_COOKIE_EXPIRES / 2) {
|
||||
resourceSession.expiresAt = new Date(
|
||||
Date.now() + SESSION_COOKIE_EXPIRES,
|
||||
Date.now() + SESSION_COOKIE_EXPIRES
|
||||
).getTime();
|
||||
await db
|
||||
.update(resourceSessions)
|
||||
.set({
|
||||
expiresAt: resourceSession.expiresAt,
|
||||
expiresAt: resourceSession.expiresAt
|
||||
})
|
||||
.where(eq(resourceSessions.sessionId, resourceSession.sessionId));
|
||||
}
|
||||
|
@ -79,7 +83,7 @@ export async function validateResourceSessionToken(
|
|||
}
|
||||
|
||||
export async function invalidateResourceSession(
|
||||
sessionId: string,
|
||||
sessionId: string
|
||||
): Promise<void> {
|
||||
await db
|
||||
.delete(resourceSessions)
|
||||
|
@ -91,7 +95,8 @@ export async function invalidateAllSessions(
|
|||
method?: {
|
||||
passwordId?: number;
|
||||
pincodeId?: number;
|
||||
},
|
||||
whitelistId?: number;
|
||||
}
|
||||
): Promise<void> {
|
||||
if (method?.passwordId) {
|
||||
await db
|
||||
|
@ -99,19 +104,34 @@ export async function invalidateAllSessions(
|
|||
.where(
|
||||
and(
|
||||
eq(resourceSessions.resourceId, resourceId),
|
||||
eq(resourceSessions.passwordId, method.passwordId),
|
||||
),
|
||||
eq(resourceSessions.passwordId, method.passwordId)
|
||||
)
|
||||
);
|
||||
} else if (method?.pincodeId) {
|
||||
}
|
||||
|
||||
if (method?.pincodeId) {
|
||||
await db
|
||||
.delete(resourceSessions)
|
||||
.where(
|
||||
and(
|
||||
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
|
||||
.delete(resourceSessions)
|
||||
.where(eq(resourceSessions.resourceId, resourceId));
|
||||
|
@ -121,7 +141,7 @@ export async function invalidateAllSessions(
|
|||
export function serializeResourceSessionCookie(
|
||||
cookieName: string,
|
||||
token: string,
|
||||
fqdn: string,
|
||||
fqdn: string
|
||||
): string {
|
||||
if (SECURE_COOKIES) {
|
||||
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(
|
||||
cookieName: string,
|
||||
fqdn: string,
|
||||
fqdn: string
|
||||
): string {
|
||||
if (SECURE_COOKIES) {
|
||||
return `${cookieName}=; HttpOnly; SameSite=Lax; Max-Age=0; Path=/; Secure; Domain=${COOKIE_DOMAIN}`;
|
||||
|
|
102
server/auth/resourceOtp.ts
Normal file
102
server/auth/resourceOtp.ts
Normal 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;
|
||||
}
|
|
@ -1,41 +1,41 @@
|
|||
import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
|
||||
import { InferSelectModel } from "drizzle-orm";
|
||||
import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core";
|
||||
|
||||
export const orgs = sqliteTable("orgs", {
|
||||
orgId: text("orgId").primaryKey(),
|
||||
name: text("name").notNull(),
|
||||
domain: text("domain").notNull(),
|
||||
domain: text("domain").notNull()
|
||||
});
|
||||
|
||||
export const sites = sqliteTable("sites", {
|
||||
siteId: integer("siteId").primaryKey({ autoIncrement: true }),
|
||||
orgId: text("orgId")
|
||||
.references(() => orgs.orgId, {
|
||||
onDelete: "cascade",
|
||||
onDelete: "cascade"
|
||||
})
|
||||
.notNull(),
|
||||
niceId: text("niceId").notNull(),
|
||||
exitNodeId: integer("exitNode").references(() => exitNodes.exitNodeId, {
|
||||
onDelete: "set null",
|
||||
onDelete: "set null"
|
||||
}),
|
||||
name: text("name").notNull(),
|
||||
pubKey: text("pubKey"),
|
||||
subnet: text("subnet").notNull(),
|
||||
megabytesIn: integer("bytesIn"),
|
||||
megabytesOut: integer("bytesOut"),
|
||||
type: text("type").notNull(), // "newt" or "wireguard"
|
||||
type: text("type").notNull() // "newt" or "wireguard"
|
||||
});
|
||||
|
||||
export const resources = sqliteTable("resources", {
|
||||
resourceId: integer("resourceId").primaryKey({ autoIncrement: true }),
|
||||
siteId: integer("siteId")
|
||||
.references(() => sites.siteId, {
|
||||
onDelete: "cascade",
|
||||
onDelete: "cascade"
|
||||
})
|
||||
.notNull(),
|
||||
orgId: text("orgId")
|
||||
.references(() => orgs.orgId, {
|
||||
onDelete: "cascade",
|
||||
onDelete: "cascade"
|
||||
})
|
||||
.notNull(),
|
||||
name: text("name").notNull(),
|
||||
|
@ -46,16 +46,16 @@ export const resources = sqliteTable("resources", {
|
|||
.notNull()
|
||||
.default(false),
|
||||
sso: integer("sso", { mode: "boolean" }).notNull().default(true),
|
||||
twoFactorEnabled: integer("twoFactorEnabled", { mode: "boolean" })
|
||||
otpEnabled: integer("otpEnabled", { mode: "boolean" })
|
||||
.notNull()
|
||||
.default(false),
|
||||
.default(false)
|
||||
});
|
||||
|
||||
export const targets = sqliteTable("targets", {
|
||||
targetId: integer("targetId").primaryKey({ autoIncrement: true }),
|
||||
resourceId: integer("resourceId")
|
||||
.references(() => resources.resourceId, {
|
||||
onDelete: "cascade",
|
||||
onDelete: "cascade"
|
||||
})
|
||||
.notNull(),
|
||||
ip: text("ip").notNull(),
|
||||
|
@ -63,7 +63,7 @@ export const targets = sqliteTable("targets", {
|
|||
port: integer("port").notNull(),
|
||||
internalPort: integer("internalPort"),
|
||||
protocol: text("protocol"),
|
||||
enabled: integer("enabled", { mode: "boolean" }).notNull().default(true),
|
||||
enabled: integer("enabled", { mode: "boolean" }).notNull().default(true)
|
||||
});
|
||||
|
||||
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
|
||||
publicKey: text("pubicKey").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", {
|
||||
|
@ -87,14 +87,14 @@ export const users = sqliteTable("user", {
|
|||
emailVerified: integer("emailVerified", { mode: "boolean" })
|
||||
.notNull()
|
||||
.default(false),
|
||||
dateCreated: text("dateCreated").notNull(),
|
||||
dateCreated: text("dateCreated").notNull()
|
||||
});
|
||||
|
||||
export const newts = sqliteTable("newt", {
|
||||
newtId: text("id").primaryKey(),
|
||||
secretHash: text("secretHash").notNull(),
|
||||
dateCreated: text("dateCreated").notNull(),
|
||||
siteId: integer("siteId").references(() => sites.siteId),
|
||||
siteId: integer("siteId").references(() => sites.siteId)
|
||||
});
|
||||
|
||||
export const twoFactorBackupCodes = sqliteTable("twoFactorBackupCodes", {
|
||||
|
@ -102,7 +102,7 @@ export const twoFactorBackupCodes = sqliteTable("twoFactorBackupCodes", {
|
|||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => users.userId, { onDelete: "cascade" }),
|
||||
codeHash: text("codeHash").notNull(),
|
||||
codeHash: text("codeHash").notNull()
|
||||
});
|
||||
|
||||
export const sessions = sqliteTable("session", {
|
||||
|
@ -110,7 +110,7 @@ export const sessions = sqliteTable("session", {
|
|||
userId: text("userId")
|
||||
.notNull()
|
||||
.references(() => users.userId, { onDelete: "cascade" }),
|
||||
expiresAt: integer("expiresAt").notNull(),
|
||||
expiresAt: integer("expiresAt").notNull()
|
||||
});
|
||||
|
||||
export const newtSessions = sqliteTable("newtSession", {
|
||||
|
@ -118,7 +118,7 @@ export const newtSessions = sqliteTable("newtSession", {
|
|||
newtId: text("newtId")
|
||||
.notNull()
|
||||
.references(() => newts.newtId, { onDelete: "cascade" }),
|
||||
expiresAt: integer("expiresAt").notNull(),
|
||||
expiresAt: integer("expiresAt").notNull()
|
||||
});
|
||||
|
||||
export const userOrgs = sqliteTable("userOrgs", {
|
||||
|
@ -131,7 +131,7 @@ export const userOrgs = sqliteTable("userOrgs", {
|
|||
roleId: integer("roleId")
|
||||
.notNull()
|
||||
.references(() => roles.roleId),
|
||||
isOwner: integer("isOwner", { mode: "boolean" }).notNull().default(false),
|
||||
isOwner: integer("isOwner", { mode: "boolean" }).notNull().default(false)
|
||||
});
|
||||
|
||||
export const emailVerificationCodes = sqliteTable("emailVerificationCodes", {
|
||||
|
@ -141,7 +141,7 @@ export const emailVerificationCodes = sqliteTable("emailVerificationCodes", {
|
|||
.references(() => users.userId, { onDelete: "cascade" }),
|
||||
email: text("email").notNull(),
|
||||
code: text("code").notNull(),
|
||||
expiresAt: integer("expiresAt").notNull(),
|
||||
expiresAt: integer("expiresAt").notNull()
|
||||
});
|
||||
|
||||
export const passwordResetTokens = sqliteTable("passwordResetTokens", {
|
||||
|
@ -150,25 +150,25 @@ export const passwordResetTokens = sqliteTable("passwordResetTokens", {
|
|||
.notNull()
|
||||
.references(() => users.userId, { onDelete: "cascade" }),
|
||||
tokenHash: text("tokenHash").notNull(),
|
||||
expiresAt: integer("expiresAt").notNull(),
|
||||
expiresAt: integer("expiresAt").notNull()
|
||||
});
|
||||
|
||||
export const actions = sqliteTable("actions", {
|
||||
actionId: text("actionId").primaryKey(),
|
||||
name: text("name"),
|
||||
description: text("description"),
|
||||
description: text("description")
|
||||
});
|
||||
|
||||
export const roles = sqliteTable("roles", {
|
||||
roleId: integer("roleId").primaryKey({ autoIncrement: true }),
|
||||
orgId: text("orgId")
|
||||
.references(() => orgs.orgId, {
|
||||
onDelete: "cascade",
|
||||
onDelete: "cascade"
|
||||
})
|
||||
.notNull(),
|
||||
isAdmin: integer("isAdmin", { mode: "boolean" }),
|
||||
name: text("name").notNull(),
|
||||
description: text("description"),
|
||||
description: text("description")
|
||||
});
|
||||
|
||||
export const roleActions = sqliteTable("roleActions", {
|
||||
|
@ -180,7 +180,7 @@ export const roleActions = sqliteTable("roleActions", {
|
|||
.references(() => actions.actionId, { onDelete: "cascade" }),
|
||||
orgId: text("orgId")
|
||||
.notNull()
|
||||
.references(() => orgs.orgId, { onDelete: "cascade" }),
|
||||
.references(() => orgs.orgId, { onDelete: "cascade" })
|
||||
});
|
||||
|
||||
export const userActions = sqliteTable("userActions", {
|
||||
|
@ -192,7 +192,7 @@ export const userActions = sqliteTable("userActions", {
|
|||
.references(() => actions.actionId, { onDelete: "cascade" }),
|
||||
orgId: text("orgId")
|
||||
.notNull()
|
||||
.references(() => orgs.orgId, { onDelete: "cascade" }),
|
||||
.references(() => orgs.orgId, { onDelete: "cascade" })
|
||||
});
|
||||
|
||||
export const roleSites = sqliteTable("roleSites", {
|
||||
|
@ -201,7 +201,7 @@ export const roleSites = sqliteTable("roleSites", {
|
|||
.references(() => roles.roleId, { onDelete: "cascade" }),
|
||||
siteId: integer("siteId")
|
||||
.notNull()
|
||||
.references(() => sites.siteId, { onDelete: "cascade" }),
|
||||
.references(() => sites.siteId, { onDelete: "cascade" })
|
||||
});
|
||||
|
||||
export const userSites = sqliteTable("userSites", {
|
||||
|
@ -210,7 +210,7 @@ export const userSites = sqliteTable("userSites", {
|
|||
.references(() => users.userId, { onDelete: "cascade" }),
|
||||
siteId: integer("siteId")
|
||||
.notNull()
|
||||
.references(() => sites.siteId, { onDelete: "cascade" }),
|
||||
.references(() => sites.siteId, { onDelete: "cascade" })
|
||||
});
|
||||
|
||||
export const roleResources = sqliteTable("roleResources", {
|
||||
|
@ -219,7 +219,7 @@ export const roleResources = sqliteTable("roleResources", {
|
|||
.references(() => roles.roleId, { onDelete: "cascade" }),
|
||||
resourceId: integer("resourceId")
|
||||
.notNull()
|
||||
.references(() => resources.resourceId, { onDelete: "cascade" }),
|
||||
.references(() => resources.resourceId, { onDelete: "cascade" })
|
||||
});
|
||||
|
||||
export const userResources = sqliteTable("userResources", {
|
||||
|
@ -228,19 +228,19 @@ export const userResources = sqliteTable("userResources", {
|
|||
.references(() => users.userId, { onDelete: "cascade" }),
|
||||
resourceId: integer("resourceId")
|
||||
.notNull()
|
||||
.references(() => resources.resourceId, { onDelete: "cascade" }),
|
||||
.references(() => resources.resourceId, { onDelete: "cascade" })
|
||||
});
|
||||
|
||||
export const limitsTable = sqliteTable("limits", {
|
||||
limitId: integer("limitId").primaryKey({ autoIncrement: true }),
|
||||
orgId: text("orgId")
|
||||
.references(() => orgs.orgId, {
|
||||
onDelete: "cascade",
|
||||
onDelete: "cascade"
|
||||
})
|
||||
.notNull(),
|
||||
name: text("name").notNull(),
|
||||
value: integer("value").notNull(),
|
||||
description: text("description"),
|
||||
description: text("description")
|
||||
});
|
||||
|
||||
export const userInvites = sqliteTable("userInvites", {
|
||||
|
@ -253,28 +253,28 @@ export const userInvites = sqliteTable("userInvites", {
|
|||
tokenHash: text("token").notNull(),
|
||||
roleId: integer("roleId")
|
||||
.notNull()
|
||||
.references(() => roles.roleId, { onDelete: "cascade" }),
|
||||
.references(() => roles.roleId, { onDelete: "cascade" })
|
||||
});
|
||||
|
||||
export const resourcePincode = sqliteTable("resourcePincode", {
|
||||
pincodeId: integer("pincodeId").primaryKey({
|
||||
autoIncrement: true,
|
||||
autoIncrement: true
|
||||
}),
|
||||
resourceId: integer("resourceId")
|
||||
.notNull()
|
||||
.references(() => resources.resourceId, { onDelete: "cascade" }),
|
||||
pincodeHash: text("pincodeHash").notNull(),
|
||||
digitLength: integer("digitLength").notNull(),
|
||||
digitLength: integer("digitLength").notNull()
|
||||
});
|
||||
|
||||
export const resourcePassword = sqliteTable("resourcePassword", {
|
||||
passwordId: integer("passwordId").primaryKey({
|
||||
autoIncrement: true,
|
||||
autoIncrement: true
|
||||
}),
|
||||
resourceId: integer("resourceId")
|
||||
.notNull()
|
||||
.references(() => resources.resourceId, { onDelete: "cascade" }),
|
||||
passwordHash: text("passwordHash").notNull(),
|
||||
passwordHash: text("passwordHash").notNull()
|
||||
});
|
||||
|
||||
export const resourceSessions = sqliteTable("resourceSessions", {
|
||||
|
@ -282,31 +282,49 @@ export const resourceSessions = sqliteTable("resourceSessions", {
|
|||
resourceId: integer("resourceId")
|
||||
.notNull()
|
||||
.references(() => resources.resourceId, { onDelete: "cascade" }),
|
||||
usedOtp: integer("usedOtp", { mode: "boolean" }).notNull().default(false),
|
||||
expiresAt: integer("expiresAt").notNull(),
|
||||
passwordId: integer("passwordId").references(
|
||||
() => resourcePassword.passwordId,
|
||||
{
|
||||
onDelete: "cascade",
|
||||
},
|
||||
onDelete: "cascade"
|
||||
}
|
||||
),
|
||||
pincodeId: integer("pincodeId").references(
|
||||
() => 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", {
|
||||
otpId: integer("otpId").primaryKey({
|
||||
autoIncrement: true,
|
||||
autoIncrement: true
|
||||
}),
|
||||
resourceId: integer("resourceId")
|
||||
.notNull()
|
||||
.references(() => resources.resourceId, { onDelete: "cascade" }),
|
||||
email: text("email").notNull(),
|
||||
otpHash: text("otpHash").notNull(),
|
||||
expiresAt: integer("expiresAt").notNull(),
|
||||
expiresAt: integer("expiresAt").notNull()
|
||||
});
|
||||
|
||||
export type Org = InferSelectModel<typeof orgs>;
|
||||
|
|
71
server/emails/templates/ResourceOTPCode.tsx
Normal file
71
server/emails/templates/ResourceOTPCode.tsx
Normal 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">
|
||||
You’ve 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;
|
|
@ -71,11 +71,6 @@ export const SendInviteLink = ({
|
|||
Accept invitation to {orgName}
|
||||
</Button>
|
||||
</Section>
|
||||
<Text className="text-sm text-gray-500 mt-6">
|
||||
Best regards,
|
||||
<br />
|
||||
Fossorial
|
||||
</Text>
|
||||
</Container>
|
||||
</Body>
|
||||
</Tailwind>
|
||||
|
|
|
@ -63,11 +63,6 @@ export const VerifyEmail = ({
|
|||
If you didn’t request this, you can safely ignore
|
||||
this email.
|
||||
</Text>
|
||||
<Text className="text-sm text-gray-500 mt-6">
|
||||
Best regards,
|
||||
<br />
|
||||
Fossorial
|
||||
</Text>
|
||||
</Container>
|
||||
</Body>
|
||||
</Tailwind>
|
||||
|
|
|
@ -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;
|
||||
|
|
|
@ -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);
|
||||
|
||||
|
|
|
@ -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"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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"
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue