mirror of
https://github.com/fosrl/pangolin.git
synced 2026-03-01 16:26:39 +00:00
Compare commits
4 Commits
multi-role
...
1.15.4-s.7
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5ef808d4a2 | ||
|
|
a502780c9b | ||
|
|
418e099804 | ||
|
|
b622aca221 |
@@ -1,7 +1,7 @@
|
|||||||
import { Request } from "express";
|
import { Request } from "express";
|
||||||
import { db } from "@server/db";
|
import { db } from "@server/db";
|
||||||
import { userActions, roleActions } from "@server/db";
|
import { userActions, roleActions, userOrgs } from "@server/db";
|
||||||
import { and, eq, inArray } from "drizzle-orm";
|
import { and, eq } from "drizzle-orm";
|
||||||
import createHttpError from "http-errors";
|
import createHttpError from "http-errors";
|
||||||
import HttpCode from "@server/types/HttpCode";
|
import HttpCode from "@server/types/HttpCode";
|
||||||
|
|
||||||
@@ -52,7 +52,6 @@ export enum ActionsEnum {
|
|||||||
listRoleResources = "listRoleResources",
|
listRoleResources = "listRoleResources",
|
||||||
// listRoleActions = "listRoleActions",
|
// listRoleActions = "listRoleActions",
|
||||||
addUserRole = "addUserRole",
|
addUserRole = "addUserRole",
|
||||||
removeUserRole = "removeUserRole",
|
|
||||||
// addUserSite = "addUserSite",
|
// addUserSite = "addUserSite",
|
||||||
// addUserAction = "addUserAction",
|
// addUserAction = "addUserAction",
|
||||||
// removeUserAction = "removeUserAction",
|
// removeUserAction = "removeUserAction",
|
||||||
@@ -154,19 +153,29 @@ export async function checkUserActionPermission(
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
let userOrgRoleIds = req.userOrgRoleIds;
|
let userOrgRoleId = req.userOrgRoleId;
|
||||||
|
|
||||||
if (userOrgRoleIds === undefined) {
|
// If userOrgRoleId is not available on the request, fetch it
|
||||||
const { getUserOrgRoleIds } = await import(
|
if (userOrgRoleId === undefined) {
|
||||||
"@server/lib/userOrgRoles"
|
const userOrgRole = await db
|
||||||
);
|
.select()
|
||||||
userOrgRoleIds = await getUserOrgRoleIds(userId, req.userOrgId!);
|
.from(userOrgs)
|
||||||
if (userOrgRoleIds.length === 0) {
|
.where(
|
||||||
|
and(
|
||||||
|
eq(userOrgs.userId, userId),
|
||||||
|
eq(userOrgs.orgId, req.userOrgId!)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
if (userOrgRole.length === 0) {
|
||||||
throw createHttpError(
|
throw createHttpError(
|
||||||
HttpCode.FORBIDDEN,
|
HttpCode.FORBIDDEN,
|
||||||
"User does not have access to this organization"
|
"User does not have access to this organization"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
userOrgRoleId = userOrgRole[0].roleId;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if the user has direct permission for the action in the current org
|
// Check if the user has direct permission for the action in the current org
|
||||||
@@ -177,7 +186,7 @@ export async function checkUserActionPermission(
|
|||||||
and(
|
and(
|
||||||
eq(userActions.userId, userId),
|
eq(userActions.userId, userId),
|
||||||
eq(userActions.actionId, actionId),
|
eq(userActions.actionId, actionId),
|
||||||
eq(userActions.orgId, req.userOrgId!)
|
eq(userActions.orgId, req.userOrgId!) // TODO: we cant pass the org id if we are not checking the org
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
.limit(1);
|
.limit(1);
|
||||||
@@ -186,14 +195,14 @@ export async function checkUserActionPermission(
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// If no direct permission, check role-based permission (any of user's roles)
|
// If no direct permission, check role-based permission
|
||||||
const roleActionPermission = await db
|
const roleActionPermission = await db
|
||||||
.select()
|
.select()
|
||||||
.from(roleActions)
|
.from(roleActions)
|
||||||
.where(
|
.where(
|
||||||
and(
|
and(
|
||||||
eq(roleActions.actionId, actionId),
|
eq(roleActions.actionId, actionId),
|
||||||
inArray(roleActions.roleId, userOrgRoleIds),
|
eq(roleActions.roleId, userOrgRoleId!),
|
||||||
eq(roleActions.orgId, req.userOrgId!)
|
eq(roleActions.orgId, req.userOrgId!)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,29 +1,26 @@
|
|||||||
import { db } from "@server/db";
|
import { db } from "@server/db";
|
||||||
import { and, eq, inArray } from "drizzle-orm";
|
import { and, eq } from "drizzle-orm";
|
||||||
import { roleResources, userResources } from "@server/db";
|
import { roleResources, userResources } from "@server/db";
|
||||||
|
|
||||||
export async function canUserAccessResource({
|
export async function canUserAccessResource({
|
||||||
userId,
|
userId,
|
||||||
resourceId,
|
resourceId,
|
||||||
roleIds
|
roleId
|
||||||
}: {
|
}: {
|
||||||
userId: string;
|
userId: string;
|
||||||
resourceId: number;
|
resourceId: number;
|
||||||
roleIds: number[];
|
roleId: number;
|
||||||
}): Promise<boolean> {
|
}): Promise<boolean> {
|
||||||
const roleResourceAccess =
|
const roleResourceAccess = await db
|
||||||
roleIds.length > 0
|
.select()
|
||||||
? await db
|
.from(roleResources)
|
||||||
.select()
|
.where(
|
||||||
.from(roleResources)
|
and(
|
||||||
.where(
|
eq(roleResources.resourceId, resourceId),
|
||||||
and(
|
eq(roleResources.roleId, roleId)
|
||||||
eq(roleResources.resourceId, resourceId),
|
)
|
||||||
inArray(roleResources.roleId, roleIds)
|
)
|
||||||
)
|
.limit(1);
|
||||||
)
|
|
||||||
.limit(1)
|
|
||||||
: [];
|
|
||||||
|
|
||||||
if (roleResourceAccess.length > 0) {
|
if (roleResourceAccess.length > 0) {
|
||||||
return true;
|
return true;
|
||||||
|
|||||||
@@ -1,29 +1,26 @@
|
|||||||
import { db } from "@server/db";
|
import { db } from "@server/db";
|
||||||
import { and, eq, inArray } from "drizzle-orm";
|
import { and, eq } from "drizzle-orm";
|
||||||
import { roleSiteResources, userSiteResources } from "@server/db";
|
import { roleSiteResources, userSiteResources } from "@server/db";
|
||||||
|
|
||||||
export async function canUserAccessSiteResource({
|
export async function canUserAccessSiteResource({
|
||||||
userId,
|
userId,
|
||||||
resourceId,
|
resourceId,
|
||||||
roleIds
|
roleId
|
||||||
}: {
|
}: {
|
||||||
userId: string;
|
userId: string;
|
||||||
resourceId: number;
|
resourceId: number;
|
||||||
roleIds: number[];
|
roleId: number;
|
||||||
}): Promise<boolean> {
|
}): Promise<boolean> {
|
||||||
const roleResourceAccess =
|
const roleResourceAccess = await db
|
||||||
roleIds.length > 0
|
.select()
|
||||||
? await db
|
.from(roleSiteResources)
|
||||||
.select()
|
.where(
|
||||||
.from(roleSiteResources)
|
and(
|
||||||
.where(
|
eq(roleSiteResources.siteResourceId, resourceId),
|
||||||
and(
|
eq(roleSiteResources.roleId, roleId)
|
||||||
eq(roleSiteResources.siteResourceId, resourceId),
|
)
|
||||||
inArray(roleSiteResources.roleId, roleIds)
|
)
|
||||||
)
|
.limit(1);
|
||||||
)
|
|
||||||
.limit(1)
|
|
||||||
: [];
|
|
||||||
|
|
||||||
if (roleResourceAccess.length > 0) {
|
if (roleResourceAccess.length > 0) {
|
||||||
return true;
|
return true;
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
export * from "./driver";
|
export * from "./driver";
|
||||||
|
export * from "./logsDriver";
|
||||||
export * from "./safeRead";
|
export * from "./safeRead";
|
||||||
export * from "./schema/schema";
|
export * from "./schema/schema";
|
||||||
export * from "./schema/privateSchema";
|
export * from "./schema/privateSchema";
|
||||||
|
|||||||
89
server/db/pg/logsDriver.ts
Normal file
89
server/db/pg/logsDriver.ts
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
import { drizzle as DrizzlePostgres } from "drizzle-orm/node-postgres";
|
||||||
|
import { Pool } from "pg";
|
||||||
|
import { readConfigFile } from "@server/lib/readConfigFile";
|
||||||
|
import { readPrivateConfigFile } from "@server/private/lib/readConfigFile";
|
||||||
|
import { withReplicas } from "drizzle-orm/pg-core";
|
||||||
|
import { build } from "@server/build";
|
||||||
|
import { db as mainDb, primaryDb as mainPrimaryDb } from "./driver";
|
||||||
|
|
||||||
|
function createLogsDb() {
|
||||||
|
// Only use separate logs database in SaaS builds
|
||||||
|
if (build !== "saas") {
|
||||||
|
return mainDb;
|
||||||
|
}
|
||||||
|
|
||||||
|
const config = readConfigFile();
|
||||||
|
const privateConfig = readPrivateConfigFile();
|
||||||
|
|
||||||
|
// Merge configs, prioritizing private config
|
||||||
|
const logsConfig = privateConfig.postgres_logs || config.postgres_logs;
|
||||||
|
|
||||||
|
// Check environment variable first
|
||||||
|
let connectionString = process.env.POSTGRES_LOGS_CONNECTION_STRING;
|
||||||
|
let replicaConnections: Array<{ connection_string: string }> = [];
|
||||||
|
|
||||||
|
if (!connectionString && logsConfig) {
|
||||||
|
connectionString = logsConfig.connection_string;
|
||||||
|
replicaConnections = logsConfig.replicas || [];
|
||||||
|
}
|
||||||
|
|
||||||
|
// If POSTGRES_LOGS_REPLICA_CONNECTION_STRINGS is set, use it
|
||||||
|
if (process.env.POSTGRES_LOGS_REPLICA_CONNECTION_STRINGS) {
|
||||||
|
replicaConnections =
|
||||||
|
process.env.POSTGRES_LOGS_REPLICA_CONNECTION_STRINGS.split(",").map(
|
||||||
|
(conn) => ({
|
||||||
|
connection_string: conn.trim()
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// If no logs database is configured, fall back to main database
|
||||||
|
if (!connectionString) {
|
||||||
|
return mainDb;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create separate connection pool for logs database
|
||||||
|
const poolConfig = logsConfig?.pool || config.postgres?.pool;
|
||||||
|
const primaryPool = new Pool({
|
||||||
|
connectionString,
|
||||||
|
max: poolConfig?.max_connections || 20,
|
||||||
|
idleTimeoutMillis: poolConfig?.idle_timeout_ms || 30000,
|
||||||
|
connectionTimeoutMillis: poolConfig?.connection_timeout_ms || 5000
|
||||||
|
});
|
||||||
|
|
||||||
|
const replicas = [];
|
||||||
|
|
||||||
|
if (!replicaConnections.length) {
|
||||||
|
replicas.push(
|
||||||
|
DrizzlePostgres(primaryPool, {
|
||||||
|
logger: process.env.QUERY_LOGGING == "true"
|
||||||
|
})
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
for (const conn of replicaConnections) {
|
||||||
|
const replicaPool = new Pool({
|
||||||
|
connectionString: conn.connection_string,
|
||||||
|
max: poolConfig?.max_replica_connections || 20,
|
||||||
|
idleTimeoutMillis: poolConfig?.idle_timeout_ms || 30000,
|
||||||
|
connectionTimeoutMillis:
|
||||||
|
poolConfig?.connection_timeout_ms || 5000
|
||||||
|
});
|
||||||
|
replicas.push(
|
||||||
|
DrizzlePostgres(replicaPool, {
|
||||||
|
logger: process.env.QUERY_LOGGING == "true"
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return withReplicas(
|
||||||
|
DrizzlePostgres(primaryPool, {
|
||||||
|
logger: process.env.QUERY_LOGGING == "true"
|
||||||
|
}),
|
||||||
|
replicas as any
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const logsDb = createLogsDb();
|
||||||
|
export default logsDb;
|
||||||
|
export const primaryLogsDb = logsDb.$primary;
|
||||||
@@ -9,7 +9,6 @@ import {
|
|||||||
real,
|
real,
|
||||||
serial,
|
serial,
|
||||||
text,
|
text,
|
||||||
unique,
|
|
||||||
varchar
|
varchar
|
||||||
} from "drizzle-orm/pg-core";
|
} from "drizzle-orm/pg-core";
|
||||||
|
|
||||||
@@ -333,6 +332,9 @@ export const userOrgs = pgTable("userOrgs", {
|
|||||||
onDelete: "cascade"
|
onDelete: "cascade"
|
||||||
})
|
})
|
||||||
.notNull(),
|
.notNull(),
|
||||||
|
roleId: integer("roleId")
|
||||||
|
.notNull()
|
||||||
|
.references(() => roles.roleId),
|
||||||
isOwner: boolean("isOwner").notNull().default(false),
|
isOwner: boolean("isOwner").notNull().default(false),
|
||||||
autoProvisioned: boolean("autoProvisioned").default(false),
|
autoProvisioned: boolean("autoProvisioned").default(false),
|
||||||
pamUsername: varchar("pamUsername") // cleaned username for ssh and such
|
pamUsername: varchar("pamUsername") // cleaned username for ssh and such
|
||||||
@@ -381,22 +383,6 @@ export const roles = pgTable("roles", {
|
|||||||
sshUnixGroups: text("sshUnixGroups").default("[]")
|
sshUnixGroups: text("sshUnixGroups").default("[]")
|
||||||
});
|
});
|
||||||
|
|
||||||
export const userOrgRoles = pgTable(
|
|
||||||
"userOrgRoles",
|
|
||||||
{
|
|
||||||
userId: varchar("userId")
|
|
||||||
.notNull()
|
|
||||||
.references(() => users.userId, { onDelete: "cascade" }),
|
|
||||||
orgId: varchar("orgId")
|
|
||||||
.notNull()
|
|
||||||
.references(() => orgs.orgId, { onDelete: "cascade" }),
|
|
||||||
roleId: integer("roleId")
|
|
||||||
.notNull()
|
|
||||||
.references(() => roles.roleId, { onDelete: "cascade" })
|
|
||||||
},
|
|
||||||
(t) => [unique().on(t.userId, t.orgId, t.roleId)]
|
|
||||||
);
|
|
||||||
|
|
||||||
export const roleActions = pgTable("roleActions", {
|
export const roleActions = pgTable("roleActions", {
|
||||||
roleId: integer("roleId")
|
roleId: integer("roleId")
|
||||||
.notNull()
|
.notNull()
|
||||||
@@ -1045,7 +1031,6 @@ export type RoleResource = InferSelectModel<typeof roleResources>;
|
|||||||
export type UserResource = InferSelectModel<typeof userResources>;
|
export type UserResource = InferSelectModel<typeof userResources>;
|
||||||
export type UserInvite = InferSelectModel<typeof userInvites>;
|
export type UserInvite = InferSelectModel<typeof userInvites>;
|
||||||
export type UserOrg = InferSelectModel<typeof userOrgs>;
|
export type UserOrg = InferSelectModel<typeof userOrgs>;
|
||||||
export type UserOrgRole = InferSelectModel<typeof userOrgRoles>;
|
|
||||||
export type ResourceSession = InferSelectModel<typeof resourceSessions>;
|
export type ResourceSession = InferSelectModel<typeof resourceSessions>;
|
||||||
export type ResourcePincode = InferSelectModel<typeof resourcePincode>;
|
export type ResourcePincode = InferSelectModel<typeof resourcePincode>;
|
||||||
export type ResourcePassword = InferSelectModel<typeof resourcePassword>;
|
export type ResourcePassword = InferSelectModel<typeof resourcePassword>;
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ import {
|
|||||||
resources,
|
resources,
|
||||||
roleResources,
|
roleResources,
|
||||||
sessions,
|
sessions,
|
||||||
userOrgRoles,
|
|
||||||
userOrgs,
|
userOrgs,
|
||||||
userResources,
|
userResources,
|
||||||
users,
|
users,
|
||||||
@@ -105,57 +104,24 @@ export async function getUserSessionWithUser(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get user organization role (single role; prefer getUserOrgRoleIds + roles for multi-role).
|
* Get user organization role
|
||||||
* @deprecated Use userOrgRoles table and getUserOrgRoleIds for multi-role support.
|
|
||||||
*/
|
*/
|
||||||
export async function getUserOrgRole(userId: string, orgId: string) {
|
export async function getUserOrgRole(userId: string, orgId: string) {
|
||||||
const userOrg = await db
|
const userOrgRole = await db
|
||||||
.select({
|
.select({
|
||||||
userId: userOrgs.userId,
|
userId: userOrgs.userId,
|
||||||
orgId: userOrgs.orgId,
|
orgId: userOrgs.orgId,
|
||||||
|
roleId: userOrgs.roleId,
|
||||||
isOwner: userOrgs.isOwner,
|
isOwner: userOrgs.isOwner,
|
||||||
autoProvisioned: userOrgs.autoProvisioned
|
autoProvisioned: userOrgs.autoProvisioned,
|
||||||
|
roleName: roles.name
|
||||||
})
|
})
|
||||||
.from(userOrgs)
|
.from(userOrgs)
|
||||||
.where(and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, orgId)))
|
.where(and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, orgId)))
|
||||||
|
.leftJoin(roles, eq(userOrgs.roleId, roles.roleId))
|
||||||
.limit(1);
|
.limit(1);
|
||||||
|
|
||||||
if (userOrg.length === 0) return null;
|
return userOrgRole.length > 0 ? userOrgRole[0] : null;
|
||||||
|
|
||||||
const [firstRole] = await db
|
|
||||||
.select({
|
|
||||||
roleId: userOrgRoles.roleId,
|
|
||||||
roleName: roles.name
|
|
||||||
})
|
|
||||||
.from(userOrgRoles)
|
|
||||||
.leftJoin(roles, eq(userOrgRoles.roleId, roles.roleId))
|
|
||||||
.where(
|
|
||||||
and(
|
|
||||||
eq(userOrgRoles.userId, userId),
|
|
||||||
eq(userOrgRoles.orgId, orgId)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
return firstRole
|
|
||||||
? {
|
|
||||||
...userOrg[0],
|
|
||||||
roleId: firstRole.roleId,
|
|
||||||
roleName: firstRole.roleName
|
|
||||||
}
|
|
||||||
: { ...userOrg[0], roleId: null, roleName: null };
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get role name by role ID (for display).
|
|
||||||
*/
|
|
||||||
export async function getRoleName(roleId: number): Promise<string | null> {
|
|
||||||
const [row] = await db
|
|
||||||
.select({ name: roles.name })
|
|
||||||
.from(roles)
|
|
||||||
.where(eq(roles.roleId, roleId))
|
|
||||||
.limit(1);
|
|
||||||
return row?.name ?? null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
export * from "./driver";
|
export * from "./driver";
|
||||||
|
export * from "./logsDriver";
|
||||||
export * from "./safeRead";
|
export * from "./safeRead";
|
||||||
export * from "./schema/schema";
|
export * from "./schema/schema";
|
||||||
export * from "./schema/privateSchema";
|
export * from "./schema/privateSchema";
|
||||||
|
|||||||
7
server/db/sqlite/logsDriver.ts
Normal file
7
server/db/sqlite/logsDriver.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import { db as mainDb } from "./driver";
|
||||||
|
|
||||||
|
// SQLite doesn't support separate databases for logs in the same way as Postgres
|
||||||
|
// Always use the main database connection for SQLite
|
||||||
|
export const logsDb = mainDb;
|
||||||
|
export default logsDb;
|
||||||
|
export const primaryLogsDb = logsDb;
|
||||||
@@ -1,12 +1,6 @@
|
|||||||
import { randomUUID } from "crypto";
|
import { randomUUID } from "crypto";
|
||||||
import { InferSelectModel } from "drizzle-orm";
|
import { InferSelectModel } from "drizzle-orm";
|
||||||
import {
|
import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
|
||||||
index,
|
|
||||||
integer,
|
|
||||||
sqliteTable,
|
|
||||||
text,
|
|
||||||
unique
|
|
||||||
} from "drizzle-orm/sqlite-core";
|
|
||||||
|
|
||||||
export const domains = sqliteTable("domains", {
|
export const domains = sqliteTable("domains", {
|
||||||
domainId: text("domainId").primaryKey(),
|
domainId: text("domainId").primaryKey(),
|
||||||
@@ -641,6 +635,9 @@ export const userOrgs = sqliteTable("userOrgs", {
|
|||||||
onDelete: "cascade"
|
onDelete: "cascade"
|
||||||
})
|
})
|
||||||
.notNull(),
|
.notNull(),
|
||||||
|
roleId: integer("roleId")
|
||||||
|
.notNull()
|
||||||
|
.references(() => roles.roleId),
|
||||||
isOwner: integer("isOwner", { mode: "boolean" }).notNull().default(false),
|
isOwner: integer("isOwner", { mode: "boolean" }).notNull().default(false),
|
||||||
autoProvisioned: integer("autoProvisioned", {
|
autoProvisioned: integer("autoProvisioned", {
|
||||||
mode: "boolean"
|
mode: "boolean"
|
||||||
@@ -695,22 +692,6 @@ export const roles = sqliteTable("roles", {
|
|||||||
sshUnixGroups: text("sshUnixGroups").default("[]")
|
sshUnixGroups: text("sshUnixGroups").default("[]")
|
||||||
});
|
});
|
||||||
|
|
||||||
export const userOrgRoles = sqliteTable(
|
|
||||||
"userOrgRoles",
|
|
||||||
{
|
|
||||||
userId: text("userId")
|
|
||||||
.notNull()
|
|
||||||
.references(() => users.userId, { onDelete: "cascade" }),
|
|
||||||
orgId: text("orgId")
|
|
||||||
.notNull()
|
|
||||||
.references(() => orgs.orgId, { onDelete: "cascade" }),
|
|
||||||
roleId: integer("roleId")
|
|
||||||
.notNull()
|
|
||||||
.references(() => roles.roleId, { onDelete: "cascade" })
|
|
||||||
},
|
|
||||||
(t) => [unique().on(t.userId, t.orgId, t.roleId)]
|
|
||||||
);
|
|
||||||
|
|
||||||
export const roleActions = sqliteTable("roleActions", {
|
export const roleActions = sqliteTable("roleActions", {
|
||||||
roleId: integer("roleId")
|
roleId: integer("roleId")
|
||||||
.notNull()
|
.notNull()
|
||||||
@@ -1145,7 +1126,6 @@ export type RoleResource = InferSelectModel<typeof roleResources>;
|
|||||||
export type UserResource = InferSelectModel<typeof userResources>;
|
export type UserResource = InferSelectModel<typeof userResources>;
|
||||||
export type UserInvite = InferSelectModel<typeof userInvites>;
|
export type UserInvite = InferSelectModel<typeof userInvites>;
|
||||||
export type UserOrg = InferSelectModel<typeof userOrgs>;
|
export type UserOrg = InferSelectModel<typeof userOrgs>;
|
||||||
export type UserOrgRole = InferSelectModel<typeof userOrgRoles>;
|
|
||||||
export type ResourceSession = InferSelectModel<typeof resourceSessions>;
|
export type ResourceSession = InferSelectModel<typeof resourceSessions>;
|
||||||
export type ResourcePincode = InferSelectModel<typeof resourcePincode>;
|
export type ResourcePincode = InferSelectModel<typeof resourcePincode>;
|
||||||
export type ResourcePassword = InferSelectModel<typeof resourcePassword>;
|
export type ResourcePassword = InferSelectModel<typeof resourcePassword>;
|
||||||
|
|||||||
@@ -74,7 +74,7 @@ declare global {
|
|||||||
session: Session;
|
session: Session;
|
||||||
userOrg?: UserOrg;
|
userOrg?: UserOrg;
|
||||||
apiKeyOrg?: ApiKeyOrg;
|
apiKeyOrg?: ApiKeyOrg;
|
||||||
userOrgRoleIds?: number[];
|
userOrgRoleId?: number;
|
||||||
userOrgId?: string;
|
userOrgId?: string;
|
||||||
userOrgIds?: string[];
|
userOrgIds?: string[];
|
||||||
remoteExitNode?: RemoteExitNode;
|
remoteExitNode?: RemoteExitNode;
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import {
|
|||||||
userSiteResources
|
userSiteResources
|
||||||
} from "@server/db";
|
} from "@server/db";
|
||||||
import { sites } from "@server/db";
|
import { sites } from "@server/db";
|
||||||
import { eq, and, ne, inArray } from "drizzle-orm";
|
import { eq, and, ne, inArray, or } from "drizzle-orm";
|
||||||
import { Config } from "./types";
|
import { Config } from "./types";
|
||||||
import logger from "@server/logger";
|
import logger from "@server/logger";
|
||||||
import { getNextAvailableAliasAddress } from "../ip";
|
import { getNextAvailableAliasAddress } from "../ip";
|
||||||
@@ -142,7 +142,10 @@ export async function updateClientResources(
|
|||||||
.innerJoin(userOrgs, eq(users.userId, userOrgs.userId))
|
.innerJoin(userOrgs, eq(users.userId, userOrgs.userId))
|
||||||
.where(
|
.where(
|
||||||
and(
|
and(
|
||||||
inArray(users.username, resourceData.users),
|
or(
|
||||||
|
inArray(users.username, resourceData.users),
|
||||||
|
inArray(users.email, resourceData.users)
|
||||||
|
),
|
||||||
eq(userOrgs.orgId, orgId)
|
eq(userOrgs.orgId, orgId)
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
@@ -276,7 +279,10 @@ export async function updateClientResources(
|
|||||||
.innerJoin(userOrgs, eq(users.userId, userOrgs.userId))
|
.innerJoin(userOrgs, eq(users.userId, userOrgs.userId))
|
||||||
.where(
|
.where(
|
||||||
and(
|
and(
|
||||||
inArray(users.username, resourceData.users),
|
or(
|
||||||
|
inArray(users.username, resourceData.users),
|
||||||
|
inArray(users.email, resourceData.users)
|
||||||
|
),
|
||||||
eq(userOrgs.orgId, orgId)
|
eq(userOrgs.orgId, orgId)
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -212,7 +212,10 @@ export async function updateProxyResources(
|
|||||||
} else {
|
} else {
|
||||||
// Update existing resource
|
// Update existing resource
|
||||||
|
|
||||||
const isLicensed = await isLicensedOrSubscribed(orgId, tierMatrix.maintencePage);
|
const isLicensed = await isLicensedOrSubscribed(
|
||||||
|
orgId,
|
||||||
|
tierMatrix.maintencePage
|
||||||
|
);
|
||||||
if (!isLicensed) {
|
if (!isLicensed) {
|
||||||
resourceData.maintenance = undefined;
|
resourceData.maintenance = undefined;
|
||||||
}
|
}
|
||||||
@@ -590,7 +593,10 @@ export async function updateProxyResources(
|
|||||||
existingRule.action !== getRuleAction(rule.action) ||
|
existingRule.action !== getRuleAction(rule.action) ||
|
||||||
existingRule.match !== rule.match.toUpperCase() ||
|
existingRule.match !== rule.match.toUpperCase() ||
|
||||||
existingRule.value !==
|
existingRule.value !==
|
||||||
getRuleValue(rule.match.toUpperCase(), rule.value) ||
|
getRuleValue(
|
||||||
|
rule.match.toUpperCase(),
|
||||||
|
rule.value
|
||||||
|
) ||
|
||||||
existingRule.priority !== intendedPriority
|
existingRule.priority !== intendedPriority
|
||||||
) {
|
) {
|
||||||
validateRule(rule);
|
validateRule(rule);
|
||||||
@@ -648,7 +654,10 @@ export async function updateProxyResources(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const isLicensed = await isLicensedOrSubscribed(orgId, tierMatrix.maintencePage);
|
const isLicensed = await isLicensedOrSubscribed(
|
||||||
|
orgId,
|
||||||
|
tierMatrix.maintencePage
|
||||||
|
);
|
||||||
if (!isLicensed) {
|
if (!isLicensed) {
|
||||||
resourceData.maintenance = undefined;
|
resourceData.maintenance = undefined;
|
||||||
}
|
}
|
||||||
@@ -935,7 +944,12 @@ async function syncUserResources(
|
|||||||
.select()
|
.select()
|
||||||
.from(users)
|
.from(users)
|
||||||
.innerJoin(userOrgs, eq(users.userId, userOrgs.userId))
|
.innerJoin(userOrgs, eq(users.userId, userOrgs.userId))
|
||||||
.where(and(eq(users.username, username), eq(userOrgs.orgId, orgId)))
|
.where(
|
||||||
|
and(
|
||||||
|
or(eq(users.username, username), eq(users.email, username)),
|
||||||
|
eq(userOrgs.orgId, orgId)
|
||||||
|
)
|
||||||
|
)
|
||||||
.limit(1);
|
.limit(1);
|
||||||
|
|
||||||
if (!user) {
|
if (!user) {
|
||||||
|
|||||||
@@ -69,7 +69,7 @@ export const AuthSchema = z.object({
|
|||||||
.refine((roles) => !roles.includes("Admin"), {
|
.refine((roles) => !roles.includes("Admin"), {
|
||||||
error: "Admin role cannot be included in sso-roles"
|
error: "Admin role cannot be included in sso-roles"
|
||||||
}),
|
}),
|
||||||
"sso-users": z.array(z.email()).optional().default([]),
|
"sso-users": z.array(z.string()).optional().default([]),
|
||||||
"whitelist-users": z.array(z.email()).optional().default([]),
|
"whitelist-users": z.array(z.email()).optional().default([]),
|
||||||
"auto-login-idp": z.int().positive().optional()
|
"auto-login-idp": z.int().positive().optional()
|
||||||
});
|
});
|
||||||
@@ -335,7 +335,7 @@ export const ClientResourceSchema = z
|
|||||||
.refine((roles) => !roles.includes("Admin"), {
|
.refine((roles) => !roles.includes("Admin"), {
|
||||||
error: "Admin role cannot be included in roles"
|
error: "Admin role cannot be included in roles"
|
||||||
}),
|
}),
|
||||||
users: z.array(z.email()).optional().default([]),
|
users: z.array(z.string()).optional().default([]),
|
||||||
machines: z.array(z.string()).optional().default([])
|
machines: z.array(z.string()).optional().default([])
|
||||||
})
|
})
|
||||||
.refine(
|
.refine(
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ import {
|
|||||||
roles,
|
roles,
|
||||||
Transaction,
|
Transaction,
|
||||||
userClients,
|
userClients,
|
||||||
userOrgRoles,
|
|
||||||
userOrgs
|
userOrgs
|
||||||
} from "@server/db";
|
} from "@server/db";
|
||||||
import { getUniqueClientName } from "@server/db/names";
|
import { getUniqueClientName } from "@server/db/names";
|
||||||
@@ -40,36 +39,20 @@ export async function calculateUserClientsForOrgs(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get all user orgs with all roles (for org list and role-based logic)
|
// Get all user orgs
|
||||||
const userOrgRoleRows = await transaction
|
const allUserOrgs = await transaction
|
||||||
.select()
|
.select()
|
||||||
.from(userOrgs)
|
.from(userOrgs)
|
||||||
.innerJoin(
|
.innerJoin(roles, eq(roles.roleId, userOrgs.roleId))
|
||||||
userOrgRoles,
|
|
||||||
and(
|
|
||||||
eq(userOrgs.userId, userOrgRoles.userId),
|
|
||||||
eq(userOrgs.orgId, userOrgRoles.orgId)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.innerJoin(roles, eq(userOrgRoles.roleId, roles.roleId))
|
|
||||||
.where(eq(userOrgs.userId, userId));
|
.where(eq(userOrgs.userId, userId));
|
||||||
|
|
||||||
const userOrgIds = [...new Set(userOrgRoleRows.map((r) => r.userOrgs.orgId))];
|
const userOrgIds = allUserOrgs.map(({ userOrgs: uo }) => uo.orgId);
|
||||||
const orgIdToRoleRows = new Map<
|
|
||||||
string,
|
|
||||||
(typeof userOrgRoleRows)[0][]
|
|
||||||
>();
|
|
||||||
for (const r of userOrgRoleRows) {
|
|
||||||
const list = orgIdToRoleRows.get(r.userOrgs.orgId) ?? [];
|
|
||||||
list.push(r);
|
|
||||||
orgIdToRoleRows.set(r.userOrgs.orgId, list);
|
|
||||||
}
|
|
||||||
|
|
||||||
// For each OLM, ensure there's a client in each org the user is in
|
// For each OLM, ensure there's a client in each org the user is in
|
||||||
for (const olm of userOlms) {
|
for (const olm of userOlms) {
|
||||||
for (const orgId of orgIdToRoleRows.keys()) {
|
for (const userRoleOrg of allUserOrgs) {
|
||||||
const roleRowsForOrg = orgIdToRoleRows.get(orgId)!;
|
const { userOrgs: userOrg, roles: role } = userRoleOrg;
|
||||||
const userOrg = roleRowsForOrg[0].userOrgs;
|
const orgId = userOrg.orgId;
|
||||||
|
|
||||||
const [org] = await transaction
|
const [org] = await transaction
|
||||||
.select()
|
.select()
|
||||||
@@ -213,7 +196,7 @@ export async function calculateUserClientsForOrgs(
|
|||||||
const requireApproval =
|
const requireApproval =
|
||||||
build !== "oss" &&
|
build !== "oss" &&
|
||||||
isOrgLicensed &&
|
isOrgLicensed &&
|
||||||
roleRowsForOrg.some((r) => r.roles.requireDeviceApproval);
|
role.requireDeviceApproval;
|
||||||
|
|
||||||
const newClientData: InferInsertModel<typeof clients> = {
|
const newClientData: InferInsertModel<typeof clients> = {
|
||||||
userId,
|
userId,
|
||||||
|
|||||||
@@ -189,6 +189,46 @@ export const configSchema = z
|
|||||||
.prefault({})
|
.prefault({})
|
||||||
})
|
})
|
||||||
.optional(),
|
.optional(),
|
||||||
|
postgres_logs: z
|
||||||
|
.object({
|
||||||
|
connection_string: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.transform(getEnvOrYaml("POSTGRES_LOGS_CONNECTION_STRING")),
|
||||||
|
replicas: z
|
||||||
|
.array(
|
||||||
|
z.object({
|
||||||
|
connection_string: z.string()
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.optional(),
|
||||||
|
pool: z
|
||||||
|
.object({
|
||||||
|
max_connections: z
|
||||||
|
.number()
|
||||||
|
.positive()
|
||||||
|
.optional()
|
||||||
|
.default(20),
|
||||||
|
max_replica_connections: z
|
||||||
|
.number()
|
||||||
|
.positive()
|
||||||
|
.optional()
|
||||||
|
.default(10),
|
||||||
|
idle_timeout_ms: z
|
||||||
|
.number()
|
||||||
|
.positive()
|
||||||
|
.optional()
|
||||||
|
.default(30000),
|
||||||
|
connection_timeout_ms: z
|
||||||
|
.number()
|
||||||
|
.positive()
|
||||||
|
.optional()
|
||||||
|
.default(5000)
|
||||||
|
})
|
||||||
|
.optional()
|
||||||
|
.prefault({})
|
||||||
|
})
|
||||||
|
.optional(),
|
||||||
traefik: z
|
traefik: z
|
||||||
.object({
|
.object({
|
||||||
http_entrypoint: z.string().optional().default("web"),
|
http_entrypoint: z.string().optional().default("web"),
|
||||||
|
|||||||
@@ -14,7 +14,6 @@ import {
|
|||||||
siteResources,
|
siteResources,
|
||||||
sites,
|
sites,
|
||||||
Transaction,
|
Transaction,
|
||||||
userOrgRoles,
|
|
||||||
userOrgs,
|
userOrgs,
|
||||||
userSiteResources
|
userSiteResources
|
||||||
} from "@server/db";
|
} from "@server/db";
|
||||||
@@ -78,10 +77,10 @@ export async function getClientSiteResourceAccess(
|
|||||||
// get all of the users in these roles
|
// get all of the users in these roles
|
||||||
const userIdsFromRoles = await trx
|
const userIdsFromRoles = await trx
|
||||||
.select({
|
.select({
|
||||||
userId: userOrgRoles.userId
|
userId: userOrgs.userId
|
||||||
})
|
})
|
||||||
.from(userOrgRoles)
|
.from(userOrgs)
|
||||||
.where(inArray(userOrgRoles.roleId, roleIds))
|
.where(inArray(userOrgs.roleId, roleIds))
|
||||||
.then((rows) => rows.map((row) => row.userId));
|
.then((rows) => rows.map((row) => row.userId));
|
||||||
|
|
||||||
const newAllUserIds = Array.from(
|
const newAllUserIds = Array.from(
|
||||||
@@ -812,12 +811,12 @@ export async function rebuildClientAssociationsFromClient(
|
|||||||
|
|
||||||
// Role-based access
|
// Role-based access
|
||||||
const roleIds = await trx
|
const roleIds = await trx
|
||||||
.select({ roleId: userOrgRoles.roleId })
|
.select({ roleId: userOrgs.roleId })
|
||||||
.from(userOrgRoles)
|
.from(userOrgs)
|
||||||
.where(
|
.where(
|
||||||
and(
|
and(
|
||||||
eq(userOrgRoles.userId, client.userId),
|
eq(userOrgs.userId, client.userId),
|
||||||
eq(userOrgRoles.orgId, client.orgId)
|
eq(userOrgs.orgId, client.orgId)
|
||||||
)
|
)
|
||||||
) // this needs to be locked onto this org or else cross-org access could happen
|
) // this needs to be locked onto this org or else cross-org access could happen
|
||||||
.then((rows) => rows.map((row) => row.roleId));
|
.then((rows) => rows.map((row) => row.roleId));
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import {
|
|||||||
siteResources,
|
siteResources,
|
||||||
sites,
|
sites,
|
||||||
Transaction,
|
Transaction,
|
||||||
userOrgRoles,
|
UserOrg,
|
||||||
userOrgs,
|
userOrgs,
|
||||||
userResources,
|
userResources,
|
||||||
userSiteResources,
|
userSiteResources,
|
||||||
@@ -19,15 +19,9 @@ import { FeatureId } from "@server/lib/billing";
|
|||||||
export async function assignUserToOrg(
|
export async function assignUserToOrg(
|
||||||
org: Org,
|
org: Org,
|
||||||
values: typeof userOrgs.$inferInsert,
|
values: typeof userOrgs.$inferInsert,
|
||||||
roleId: number,
|
|
||||||
trx: Transaction | typeof db = db
|
trx: Transaction | typeof db = db
|
||||||
) {
|
) {
|
||||||
const [userOrg] = await trx.insert(userOrgs).values(values).returning();
|
const [userOrg] = await trx.insert(userOrgs).values(values).returning();
|
||||||
await trx.insert(userOrgRoles).values({
|
|
||||||
userId: userOrg.userId,
|
|
||||||
orgId: userOrg.orgId,
|
|
||||||
roleId
|
|
||||||
});
|
|
||||||
|
|
||||||
// calculate if the user is in any other of the orgs before we count it as an add to the billing org
|
// calculate if the user is in any other of the orgs before we count it as an add to the billing org
|
||||||
if (org.billingOrgId) {
|
if (org.billingOrgId) {
|
||||||
@@ -64,14 +58,6 @@ export async function removeUserFromOrg(
|
|||||||
userId: string,
|
userId: string,
|
||||||
trx: Transaction | typeof db = db
|
trx: Transaction | typeof db = db
|
||||||
) {
|
) {
|
||||||
await trx
|
|
||||||
.delete(userOrgRoles)
|
|
||||||
.where(
|
|
||||||
and(
|
|
||||||
eq(userOrgRoles.userId, userId),
|
|
||||||
eq(userOrgRoles.orgId, org.orgId)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
await trx
|
await trx
|
||||||
.delete(userOrgs)
|
.delete(userOrgs)
|
||||||
.where(and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, org.orgId)));
|
.where(and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, org.orgId)));
|
||||||
|
|||||||
@@ -1,22 +0,0 @@
|
|||||||
import { db, userOrgRoles } from "@server/db";
|
|
||||||
import { and, eq } from "drizzle-orm";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get all role IDs a user has in an organization.
|
|
||||||
* Returns empty array if the user has no roles in the org (callers must treat as no access).
|
|
||||||
*/
|
|
||||||
export async function getUserOrgRoleIds(
|
|
||||||
userId: string,
|
|
||||||
orgId: string
|
|
||||||
): Promise<number[]> {
|
|
||||||
const rows = await db
|
|
||||||
.select({ roleId: userOrgRoles.roleId })
|
|
||||||
.from(userOrgRoles)
|
|
||||||
.where(
|
|
||||||
and(
|
|
||||||
eq(userOrgRoles.userId, userId),
|
|
||||||
eq(userOrgRoles.orgId, orgId)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
return rows.map((r) => r.roleId);
|
|
||||||
}
|
|
||||||
@@ -21,7 +21,8 @@ export async function getUserOrgs(
|
|||||||
try {
|
try {
|
||||||
const userOrganizations = await db
|
const userOrganizations = await db
|
||||||
.select({
|
.select({
|
||||||
orgId: userOrgs.orgId
|
orgId: userOrgs.orgId,
|
||||||
|
roleId: userOrgs.roleId
|
||||||
})
|
})
|
||||||
.from(userOrgs)
|
.from(userOrgs)
|
||||||
.where(eq(userOrgs.userId, userId));
|
.where(eq(userOrgs.userId, userId));
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import createHttpError from "http-errors";
|
|||||||
import HttpCode from "@server/types/HttpCode";
|
import HttpCode from "@server/types/HttpCode";
|
||||||
import { canUserAccessResource } from "@server/auth/canUserAccessResource";
|
import { canUserAccessResource } from "@server/auth/canUserAccessResource";
|
||||||
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
|
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
|
||||||
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
|
|
||||||
|
|
||||||
export async function verifyAccessTokenAccess(
|
export async function verifyAccessTokenAccess(
|
||||||
req: Request,
|
req: Request,
|
||||||
@@ -94,10 +93,7 @@ export async function verifyAccessTokenAccess(
|
|||||||
)
|
)
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
req.userOrgRoleIds = await getUserOrgRoleIds(
|
req.userOrgRoleId = req.userOrg.roleId;
|
||||||
req.userOrg.userId,
|
|
||||||
resource[0].orgId!
|
|
||||||
);
|
|
||||||
req.userOrgId = resource[0].orgId!;
|
req.userOrgId = resource[0].orgId!;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -122,7 +118,7 @@ export async function verifyAccessTokenAccess(
|
|||||||
const resourceAllowed = await canUserAccessResource({
|
const resourceAllowed = await canUserAccessResource({
|
||||||
userId,
|
userId,
|
||||||
resourceId,
|
resourceId,
|
||||||
roleIds: req.userOrgRoleIds ?? []
|
roleId: req.userOrgRoleId!
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!resourceAllowed) {
|
if (!resourceAllowed) {
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
import { db } from "@server/db";
|
import { db } from "@server/db";
|
||||||
import { roles, userOrgs } from "@server/db";
|
import { roles, userOrgs } from "@server/db";
|
||||||
import { and, eq, inArray } from "drizzle-orm";
|
import { and, eq } from "drizzle-orm";
|
||||||
import createHttpError from "http-errors";
|
import createHttpError from "http-errors";
|
||||||
import HttpCode from "@server/types/HttpCode";
|
import HttpCode from "@server/types/HttpCode";
|
||||||
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
|
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
|
||||||
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
|
|
||||||
|
|
||||||
export async function verifyAdmin(
|
export async function verifyAdmin(
|
||||||
req: Request,
|
req: Request,
|
||||||
@@ -63,29 +62,13 @@ export async function verifyAdmin(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
req.userOrgRoleIds = await getUserOrgRoleIds(req.userOrg.userId, orgId!);
|
const userRole = await db
|
||||||
|
|
||||||
if (req.userOrgRoleIds.length === 0) {
|
|
||||||
return next(
|
|
||||||
createHttpError(
|
|
||||||
HttpCode.FORBIDDEN,
|
|
||||||
"User does not have Admin access"
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const userAdminRoles = await db
|
|
||||||
.select()
|
.select()
|
||||||
.from(roles)
|
.from(roles)
|
||||||
.where(
|
.where(eq(roles.roleId, req.userOrg.roleId))
|
||||||
and(
|
|
||||||
inArray(roles.roleId, req.userOrgRoleIds),
|
|
||||||
eq(roles.isAdmin, true)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.limit(1);
|
.limit(1);
|
||||||
|
|
||||||
if (userAdminRoles.length === 0) {
|
if (userRole.length === 0 || !userRole[0].isAdmin) {
|
||||||
return next(
|
return next(
|
||||||
createHttpError(
|
createHttpError(
|
||||||
HttpCode.FORBIDDEN,
|
HttpCode.FORBIDDEN,
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
import { db } from "@server/db";
|
import { db } from "@server/db";
|
||||||
import { userOrgs, apiKeys, apiKeyOrg } from "@server/db";
|
import { userOrgs, apiKeys, apiKeyOrg } from "@server/db";
|
||||||
import { and, eq } from "drizzle-orm";
|
import { and, eq, or } from "drizzle-orm";
|
||||||
import createHttpError from "http-errors";
|
import createHttpError from "http-errors";
|
||||||
import HttpCode from "@server/types/HttpCode";
|
import HttpCode from "@server/types/HttpCode";
|
||||||
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
|
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
|
||||||
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
|
|
||||||
|
|
||||||
export async function verifyApiKeyAccess(
|
export async function verifyApiKeyAccess(
|
||||||
req: Request,
|
req: Request,
|
||||||
@@ -104,10 +103,8 @@ export async function verifyApiKeyAccess(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
req.userOrgRoleIds = await getUserOrgRoleIds(
|
const userOrgRoleId = req.userOrg.roleId;
|
||||||
req.userOrg.userId,
|
req.userOrgRoleId = userOrgRoleId;
|
||||||
orgId
|
|
||||||
);
|
|
||||||
|
|
||||||
return next();
|
return next();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
import { Client, db } from "@server/db";
|
import { Client, db } from "@server/db";
|
||||||
import { userOrgs, clients, roleClients, userClients } from "@server/db";
|
import { userOrgs, clients, roleClients, userClients } from "@server/db";
|
||||||
import { and, eq, inArray } from "drizzle-orm";
|
import { and, eq } from "drizzle-orm";
|
||||||
import createHttpError from "http-errors";
|
import createHttpError from "http-errors";
|
||||||
import HttpCode from "@server/types/HttpCode";
|
import HttpCode from "@server/types/HttpCode";
|
||||||
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
|
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
|
||||||
import logger from "@server/logger";
|
import logger from "@server/logger";
|
||||||
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
|
|
||||||
|
|
||||||
export async function verifyClientAccess(
|
export async function verifyClientAccess(
|
||||||
req: Request,
|
req: Request,
|
||||||
@@ -114,30 +113,21 @@ export async function verifyClientAccess(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
req.userOrgRoleIds = await getUserOrgRoleIds(
|
const userOrgRoleId = req.userOrg.roleId;
|
||||||
req.userOrg.userId,
|
req.userOrgRoleId = userOrgRoleId;
|
||||||
client.orgId
|
|
||||||
);
|
|
||||||
req.userOrgId = client.orgId;
|
req.userOrgId = client.orgId;
|
||||||
|
|
||||||
// Check role-based client access (any of user's roles)
|
// Check role-based site access first
|
||||||
const roleClientAccessList =
|
const [roleClientAccess] = await db
|
||||||
(req.userOrgRoleIds?.length ?? 0) > 0
|
.select()
|
||||||
? await db
|
.from(roleClients)
|
||||||
.select()
|
.where(
|
||||||
.from(roleClients)
|
and(
|
||||||
.where(
|
eq(roleClients.clientId, client.clientId),
|
||||||
and(
|
eq(roleClients.roleId, userOrgRoleId)
|
||||||
eq(roleClients.clientId, client.clientId),
|
)
|
||||||
inArray(
|
)
|
||||||
roleClients.roleId,
|
.limit(1);
|
||||||
req.userOrgRoleIds!
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.limit(1)
|
|
||||||
: [];
|
|
||||||
const [roleClientAccess] = roleClientAccessList;
|
|
||||||
|
|
||||||
if (roleClientAccess) {
|
if (roleClientAccess) {
|
||||||
// User has access to the site through their role
|
// User has access to the site through their role
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
import { db, domains, orgDomains } from "@server/db";
|
import { db, domains, orgDomains } from "@server/db";
|
||||||
import { userOrgs } from "@server/db";
|
import { userOrgs, apiKeyOrg } from "@server/db";
|
||||||
import { and, eq } from "drizzle-orm";
|
import { and, eq } from "drizzle-orm";
|
||||||
import createHttpError from "http-errors";
|
import createHttpError from "http-errors";
|
||||||
import HttpCode from "@server/types/HttpCode";
|
import HttpCode from "@server/types/HttpCode";
|
||||||
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
|
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
|
||||||
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
|
|
||||||
|
|
||||||
export async function verifyDomainAccess(
|
export async function verifyDomainAccess(
|
||||||
req: Request,
|
req: Request,
|
||||||
@@ -64,7 +63,7 @@ export async function verifyDomainAccess(
|
|||||||
.where(
|
.where(
|
||||||
and(
|
and(
|
||||||
eq(userOrgs.userId, userId),
|
eq(userOrgs.userId, userId),
|
||||||
eq(userOrgs.orgId, orgId)
|
eq(userOrgs.orgId, apiKeyOrg.orgId)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
.limit(1);
|
.limit(1);
|
||||||
@@ -98,7 +97,8 @@ export async function verifyDomainAccess(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
req.userOrgRoleIds = await getUserOrgRoleIds(req.userOrg.userId, orgId);
|
const userOrgRoleId = req.userOrg.roleId;
|
||||||
|
req.userOrgRoleId = userOrgRoleId;
|
||||||
|
|
||||||
return next();
|
return next();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
import { db } from "@server/db";
|
import { db, orgs } from "@server/db";
|
||||||
import { userOrgs } from "@server/db";
|
import { userOrgs } from "@server/db";
|
||||||
import { and, eq } from "drizzle-orm";
|
import { and, eq } from "drizzle-orm";
|
||||||
import createHttpError from "http-errors";
|
import createHttpError from "http-errors";
|
||||||
import HttpCode from "@server/types/HttpCode";
|
import HttpCode from "@server/types/HttpCode";
|
||||||
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
|
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
|
||||||
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
|
|
||||||
|
|
||||||
export async function verifyOrgAccess(
|
export async function verifyOrgAccess(
|
||||||
req: Request,
|
req: Request,
|
||||||
@@ -65,8 +64,8 @@ export async function verifyOrgAccess(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// User has access, attach the user's role(s) to the request for potential future use
|
// User has access, attach the user's role to the request for potential future use
|
||||||
req.userOrgRoleIds = await getUserOrgRoleIds(req.userOrg.userId, orgId);
|
req.userOrgRoleId = req.userOrg.roleId;
|
||||||
req.userOrgId = orgId;
|
req.userOrgId = orgId;
|
||||||
|
|
||||||
return next();
|
return next();
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
import { db, Resource } from "@server/db";
|
import { db, Resource } from "@server/db";
|
||||||
import { resources, userOrgs, userResources, roleResources } from "@server/db";
|
import { resources, userOrgs, userResources, roleResources } from "@server/db";
|
||||||
import { and, eq, inArray } from "drizzle-orm";
|
import { and, eq } from "drizzle-orm";
|
||||||
import createHttpError from "http-errors";
|
import createHttpError from "http-errors";
|
||||||
import HttpCode from "@server/types/HttpCode";
|
import HttpCode from "@server/types/HttpCode";
|
||||||
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
|
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
|
||||||
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
|
|
||||||
|
|
||||||
export async function verifyResourceAccess(
|
export async function verifyResourceAccess(
|
||||||
req: Request,
|
req: Request,
|
||||||
@@ -108,28 +107,20 @@ export async function verifyResourceAccess(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
req.userOrgRoleIds = await getUserOrgRoleIds(
|
const userOrgRoleId = req.userOrg.roleId;
|
||||||
req.userOrg.userId,
|
req.userOrgRoleId = userOrgRoleId;
|
||||||
resource.orgId
|
|
||||||
);
|
|
||||||
req.userOrgId = resource.orgId;
|
req.userOrgId = resource.orgId;
|
||||||
|
|
||||||
const roleResourceAccess =
|
const roleResourceAccess = await db
|
||||||
(req.userOrgRoleIds?.length ?? 0) > 0
|
.select()
|
||||||
? await db
|
.from(roleResources)
|
||||||
.select()
|
.where(
|
||||||
.from(roleResources)
|
and(
|
||||||
.where(
|
eq(roleResources.resourceId, resource.resourceId),
|
||||||
and(
|
eq(roleResources.roleId, userOrgRoleId)
|
||||||
eq(roleResources.resourceId, resource.resourceId),
|
)
|
||||||
inArray(
|
)
|
||||||
roleResources.roleId,
|
.limit(1);
|
||||||
req.userOrgRoleIds!
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.limit(1)
|
|
||||||
: [];
|
|
||||||
|
|
||||||
if (roleResourceAccess.length > 0) {
|
if (roleResourceAccess.length > 0) {
|
||||||
return next();
|
return next();
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import createHttpError from "http-errors";
|
|||||||
import HttpCode from "@server/types/HttpCode";
|
import HttpCode from "@server/types/HttpCode";
|
||||||
import logger from "@server/logger";
|
import logger from "@server/logger";
|
||||||
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
|
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
|
||||||
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
|
|
||||||
|
|
||||||
export async function verifyRoleAccess(
|
export async function verifyRoleAccess(
|
||||||
req: Request,
|
req: Request,
|
||||||
@@ -100,6 +99,7 @@ export async function verifyRoleAccess(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!req.userOrg) {
|
if (!req.userOrg) {
|
||||||
|
// get the userORg
|
||||||
const userOrg = await db
|
const userOrg = await db
|
||||||
.select()
|
.select()
|
||||||
.from(userOrgs)
|
.from(userOrgs)
|
||||||
@@ -109,7 +109,7 @@ export async function verifyRoleAccess(
|
|||||||
.limit(1);
|
.limit(1);
|
||||||
|
|
||||||
req.userOrg = userOrg[0];
|
req.userOrg = userOrg[0];
|
||||||
req.userOrgRoleIds = await getUserOrgRoleIds(userId, orgId!);
|
req.userOrgRoleId = userOrg[0].roleId;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!req.userOrg) {
|
if (!req.userOrg) {
|
||||||
|
|||||||
@@ -1,11 +1,10 @@
|
|||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
import { db } from "@server/db";
|
import { db } from "@server/db";
|
||||||
import { sites, Site, userOrgs, userSites, roleSites, roles } from "@server/db";
|
import { sites, Site, userOrgs, userSites, roleSites, roles } from "@server/db";
|
||||||
import { and, eq, inArray, or } from "drizzle-orm";
|
import { and, eq, or } from "drizzle-orm";
|
||||||
import createHttpError from "http-errors";
|
import createHttpError from "http-errors";
|
||||||
import HttpCode from "@server/types/HttpCode";
|
import HttpCode from "@server/types/HttpCode";
|
||||||
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
|
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
|
||||||
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
|
|
||||||
|
|
||||||
export async function verifySiteAccess(
|
export async function verifySiteAccess(
|
||||||
req: Request,
|
req: Request,
|
||||||
@@ -113,29 +112,21 @@ export async function verifySiteAccess(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
req.userOrgRoleIds = await getUserOrgRoleIds(
|
const userOrgRoleId = req.userOrg.roleId;
|
||||||
req.userOrg.userId,
|
req.userOrgRoleId = userOrgRoleId;
|
||||||
site.orgId
|
|
||||||
);
|
|
||||||
req.userOrgId = site.orgId;
|
req.userOrgId = site.orgId;
|
||||||
|
|
||||||
// Check role-based site access first (any of user's roles)
|
// Check role-based site access first
|
||||||
const roleSiteAccess =
|
const roleSiteAccess = await db
|
||||||
(req.userOrgRoleIds?.length ?? 0) > 0
|
.select()
|
||||||
? await db
|
.from(roleSites)
|
||||||
.select()
|
.where(
|
||||||
.from(roleSites)
|
and(
|
||||||
.where(
|
eq(roleSites.siteId, site.siteId),
|
||||||
and(
|
eq(roleSites.roleId, userOrgRoleId)
|
||||||
eq(roleSites.siteId, site.siteId),
|
)
|
||||||
inArray(
|
)
|
||||||
roleSites.roleId,
|
.limit(1);
|
||||||
req.userOrgRoleIds!
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.limit(1)
|
|
||||||
: [];
|
|
||||||
|
|
||||||
if (roleSiteAccess.length > 0) {
|
if (roleSiteAccess.length > 0) {
|
||||||
// User's role has access to the site
|
// User's role has access to the site
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
import { db, roleSiteResources, userOrgs, userSiteResources } from "@server/db";
|
import { db, roleSiteResources, userOrgs, userSiteResources } from "@server/db";
|
||||||
import { siteResources } from "@server/db";
|
import { siteResources } from "@server/db";
|
||||||
import { eq, and, inArray } from "drizzle-orm";
|
import { eq, and } from "drizzle-orm";
|
||||||
import createHttpError from "http-errors";
|
import createHttpError from "http-errors";
|
||||||
import HttpCode from "@server/types/HttpCode";
|
import HttpCode from "@server/types/HttpCode";
|
||||||
import logger from "@server/logger";
|
import logger from "@server/logger";
|
||||||
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
|
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
|
||||||
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
|
|
||||||
|
|
||||||
export async function verifySiteResourceAccess(
|
export async function verifySiteResourceAccess(
|
||||||
req: Request,
|
req: Request,
|
||||||
@@ -110,34 +109,23 @@ export async function verifySiteResourceAccess(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
req.userOrgRoleIds = await getUserOrgRoleIds(
|
const userOrgRoleId = req.userOrg.roleId;
|
||||||
req.userOrg.userId,
|
req.userOrgRoleId = userOrgRoleId;
|
||||||
siteResource.orgId
|
|
||||||
);
|
|
||||||
req.userOrgId = siteResource.orgId;
|
req.userOrgId = siteResource.orgId;
|
||||||
|
|
||||||
// Attach the siteResource to the request for use in the next middleware/route
|
// Attach the siteResource to the request for use in the next middleware/route
|
||||||
req.siteResource = siteResource;
|
req.siteResource = siteResource;
|
||||||
|
|
||||||
const roleResourceAccess =
|
const roleResourceAccess = await db
|
||||||
(req.userOrgRoleIds?.length ?? 0) > 0
|
.select()
|
||||||
? await db
|
.from(roleSiteResources)
|
||||||
.select()
|
.where(
|
||||||
.from(roleSiteResources)
|
and(
|
||||||
.where(
|
eq(roleSiteResources.siteResourceId, siteResourceIdNum),
|
||||||
and(
|
eq(roleSiteResources.roleId, userOrgRoleId)
|
||||||
eq(
|
)
|
||||||
roleSiteResources.siteResourceId,
|
)
|
||||||
siteResourceIdNum
|
.limit(1);
|
||||||
),
|
|
||||||
inArray(
|
|
||||||
roleSiteResources.roleId,
|
|
||||||
req.userOrgRoleIds!
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.limit(1)
|
|
||||||
: [];
|
|
||||||
|
|
||||||
if (roleResourceAccess.length > 0) {
|
if (roleResourceAccess.length > 0) {
|
||||||
return next();
|
return next();
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ import createHttpError from "http-errors";
|
|||||||
import HttpCode from "@server/types/HttpCode";
|
import HttpCode from "@server/types/HttpCode";
|
||||||
import { canUserAccessResource } from "../auth/canUserAccessResource";
|
import { canUserAccessResource } from "../auth/canUserAccessResource";
|
||||||
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
|
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
|
||||||
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
|
|
||||||
|
|
||||||
export async function verifyTargetAccess(
|
export async function verifyTargetAccess(
|
||||||
req: Request,
|
req: Request,
|
||||||
@@ -100,10 +99,7 @@ export async function verifyTargetAccess(
|
|||||||
)
|
)
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
req.userOrgRoleIds = await getUserOrgRoleIds(
|
req.userOrgRoleId = req.userOrg.roleId;
|
||||||
req.userOrg.userId,
|
|
||||||
resource[0].orgId!
|
|
||||||
);
|
|
||||||
req.userOrgId = resource[0].orgId!;
|
req.userOrgId = resource[0].orgId!;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -130,7 +126,7 @@ export async function verifyTargetAccess(
|
|||||||
const resourceAllowed = await canUserAccessResource({
|
const resourceAllowed = await canUserAccessResource({
|
||||||
userId,
|
userId,
|
||||||
resourceId,
|
resourceId,
|
||||||
roleIds: req.userOrgRoleIds ?? []
|
roleId: req.userOrgRoleId!
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!resourceAllowed) {
|
if (!resourceAllowed) {
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ export async function verifyUserInRole(
|
|||||||
const roleId = parseInt(
|
const roleId = parseInt(
|
||||||
req.params.roleId || req.body.roleId || req.query.roleId
|
req.params.roleId || req.body.roleId || req.query.roleId
|
||||||
);
|
);
|
||||||
const userOrgRoleIds = req.userOrgRoleIds ?? [];
|
const userRoleId = req.userOrgRoleId;
|
||||||
|
|
||||||
if (isNaN(roleId)) {
|
if (isNaN(roleId)) {
|
||||||
return next(
|
return next(
|
||||||
@@ -20,7 +20,7 @@ export async function verifyUserInRole(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (userOrgRoleIds.length === 0) {
|
if (!userRoleId) {
|
||||||
return next(
|
return next(
|
||||||
createHttpError(
|
createHttpError(
|
||||||
HttpCode.FORBIDDEN,
|
HttpCode.FORBIDDEN,
|
||||||
@@ -29,7 +29,7 @@ export async function verifyUserInRole(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!userOrgRoleIds.includes(roleId)) {
|
if (userRoleId !== roleId) {
|
||||||
return next(
|
return next(
|
||||||
createHttpError(
|
createHttpError(
|
||||||
HttpCode.FORBIDDEN,
|
HttpCode.FORBIDDEN,
|
||||||
|
|||||||
@@ -11,7 +11,7 @@
|
|||||||
* This file is not licensed under the AGPLv3.
|
* This file is not licensed under the AGPLv3.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { accessAuditLog, db, orgs } from "@server/db";
|
import { accessAuditLog, logsDb, db, orgs } from "@server/db";
|
||||||
import { getCountryCodeForIp } from "@server/lib/geoip";
|
import { getCountryCodeForIp } from "@server/lib/geoip";
|
||||||
import logger from "@server/logger";
|
import logger from "@server/logger";
|
||||||
import { and, eq, lt } from "drizzle-orm";
|
import { and, eq, lt } from "drizzle-orm";
|
||||||
@@ -52,7 +52,7 @@ export async function cleanUpOldLogs(orgId: string, retentionDays: number) {
|
|||||||
const cutoffTimestamp = calculateCutoffTimestamp(retentionDays);
|
const cutoffTimestamp = calculateCutoffTimestamp(retentionDays);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await db
|
await logsDb
|
||||||
.delete(accessAuditLog)
|
.delete(accessAuditLog)
|
||||||
.where(
|
.where(
|
||||||
and(
|
and(
|
||||||
@@ -124,7 +124,7 @@ export async function logAccessAudit(data: {
|
|||||||
? await getCountryCodeFromIp(data.requestIp)
|
? await getCountryCodeFromIp(data.requestIp)
|
||||||
: undefined;
|
: undefined;
|
||||||
|
|
||||||
await db.insert(accessAuditLog).values({
|
await logsDb.insert(accessAuditLog).values({
|
||||||
timestamp: timestamp,
|
timestamp: timestamp,
|
||||||
orgId: data.orgId,
|
orgId: data.orgId,
|
||||||
actorType,
|
actorType,
|
||||||
|
|||||||
@@ -83,6 +83,46 @@ export const privateConfigSchema = z.object({
|
|||||||
.optional()
|
.optional()
|
||||||
})
|
})
|
||||||
.optional(),
|
.optional(),
|
||||||
|
postgres_logs: z
|
||||||
|
.object({
|
||||||
|
connection_string: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.transform(getEnvOrYaml("POSTGRES_LOGS_CONNECTION_STRING")),
|
||||||
|
replicas: z
|
||||||
|
.array(
|
||||||
|
z.object({
|
||||||
|
connection_string: z.string()
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.optional(),
|
||||||
|
pool: z
|
||||||
|
.object({
|
||||||
|
max_connections: z
|
||||||
|
.number()
|
||||||
|
.positive()
|
||||||
|
.optional()
|
||||||
|
.default(20),
|
||||||
|
max_replica_connections: z
|
||||||
|
.number()
|
||||||
|
.positive()
|
||||||
|
.optional()
|
||||||
|
.default(10),
|
||||||
|
idle_timeout_ms: z
|
||||||
|
.number()
|
||||||
|
.positive()
|
||||||
|
.optional()
|
||||||
|
.default(30000),
|
||||||
|
connection_timeout_ms: z
|
||||||
|
.number()
|
||||||
|
.positive()
|
||||||
|
.optional()
|
||||||
|
.default(5000)
|
||||||
|
})
|
||||||
|
.optional()
|
||||||
|
.prefault({})
|
||||||
|
})
|
||||||
|
.optional(),
|
||||||
gerbil: z
|
gerbil: z
|
||||||
.object({
|
.object({
|
||||||
local_exit_node_reachable_at: z
|
local_exit_node_reachable_at: z
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { ActionsEnum } from "@server/auth/actions";
|
import { ActionsEnum } from "@server/auth/actions";
|
||||||
import { actionAuditLog, db, orgs } from "@server/db";
|
import { actionAuditLog, logsDb, db, orgs } from "@server/db";
|
||||||
import logger from "@server/logger";
|
import logger from "@server/logger";
|
||||||
import HttpCode from "@server/types/HttpCode";
|
import HttpCode from "@server/types/HttpCode";
|
||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
@@ -54,7 +54,7 @@ export async function cleanUpOldLogs(orgId: string, retentionDays: number) {
|
|||||||
const cutoffTimestamp = calculateCutoffTimestamp(retentionDays);
|
const cutoffTimestamp = calculateCutoffTimestamp(retentionDays);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await db
|
await logsDb
|
||||||
.delete(actionAuditLog)
|
.delete(actionAuditLog)
|
||||||
.where(
|
.where(
|
||||||
and(
|
and(
|
||||||
@@ -123,7 +123,7 @@ export function logActionAudit(action: ActionsEnum) {
|
|||||||
metadata = JSON.stringify(req.params);
|
metadata = JSON.stringify(req.params);
|
||||||
}
|
}
|
||||||
|
|
||||||
await db.insert(actionAuditLog).values({
|
await logsDb.insert(actionAuditLog).values({
|
||||||
timestamp,
|
timestamp,
|
||||||
orgId,
|
orgId,
|
||||||
actorType,
|
actorType,
|
||||||
|
|||||||
@@ -13,10 +13,9 @@
|
|||||||
|
|
||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
import { userOrgs, db, idp, idpOrg } from "@server/db";
|
import { userOrgs, db, idp, idpOrg } from "@server/db";
|
||||||
import { and, eq } from "drizzle-orm";
|
import { and, eq, or } from "drizzle-orm";
|
||||||
import createHttpError from "http-errors";
|
import createHttpError from "http-errors";
|
||||||
import HttpCode from "@server/types/HttpCode";
|
import HttpCode from "@server/types/HttpCode";
|
||||||
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
|
|
||||||
|
|
||||||
export async function verifyIdpAccess(
|
export async function verifyIdpAccess(
|
||||||
req: Request,
|
req: Request,
|
||||||
@@ -85,10 +84,8 @@ export async function verifyIdpAccess(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
req.userOrgRoleIds = await getUserOrgRoleIds(
|
const userOrgRoleId = req.userOrg.roleId;
|
||||||
req.userOrg.userId,
|
req.userOrgRoleId = userOrgRoleId;
|
||||||
idpRes.idpOrg.orgId
|
|
||||||
);
|
|
||||||
|
|
||||||
return next();
|
return next();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -12,12 +12,11 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
import { db, exitNodeOrgs, remoteExitNodes } from "@server/db";
|
import { db, exitNodeOrgs, exitNodes, remoteExitNodes } from "@server/db";
|
||||||
import { userOrgs } from "@server/db";
|
import { sites, userOrgs, userSites, roleSites, roles } from "@server/db";
|
||||||
import { and, eq } from "drizzle-orm";
|
import { and, eq, or } from "drizzle-orm";
|
||||||
import createHttpError from "http-errors";
|
import createHttpError from "http-errors";
|
||||||
import HttpCode from "@server/types/HttpCode";
|
import HttpCode from "@server/types/HttpCode";
|
||||||
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
|
|
||||||
|
|
||||||
export async function verifyRemoteExitNodeAccess(
|
export async function verifyRemoteExitNodeAccess(
|
||||||
req: Request,
|
req: Request,
|
||||||
@@ -104,10 +103,8 @@ export async function verifyRemoteExitNodeAccess(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
req.userOrgRoleIds = await getUserOrgRoleIds(
|
const userOrgRoleId = req.userOrg.roleId;
|
||||||
req.userOrg.userId,
|
req.userOrgRoleId = userOrgRoleId;
|
||||||
exitNodeOrg.orgId
|
|
||||||
);
|
|
||||||
|
|
||||||
return next();
|
return next();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -11,11 +11,11 @@
|
|||||||
* This file is not licensed under the AGPLv3.
|
* This file is not licensed under the AGPLv3.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { accessAuditLog, db, resources } from "@server/db";
|
import { accessAuditLog, logsDb, resources, db, primaryDb } from "@server/db";
|
||||||
import { registry } from "@server/openApi";
|
import { registry } from "@server/openApi";
|
||||||
import { NextFunction } from "express";
|
import { NextFunction } from "express";
|
||||||
import { Request, Response } from "express";
|
import { Request, Response } from "express";
|
||||||
import { eq, gt, lt, and, count, desc } from "drizzle-orm";
|
import { eq, gt, lt, and, count, desc, inArray } from "drizzle-orm";
|
||||||
import { OpenAPITags } from "@server/openApi";
|
import { OpenAPITags } from "@server/openApi";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import createHttpError from "http-errors";
|
import createHttpError from "http-errors";
|
||||||
@@ -115,7 +115,7 @@ function getWhere(data: Q) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function queryAccess(data: Q) {
|
export function queryAccess(data: Q) {
|
||||||
return db
|
return logsDb
|
||||||
.select({
|
.select({
|
||||||
orgId: accessAuditLog.orgId,
|
orgId: accessAuditLog.orgId,
|
||||||
action: accessAuditLog.action,
|
action: accessAuditLog.action,
|
||||||
@@ -133,16 +133,46 @@ export function queryAccess(data: Q) {
|
|||||||
actor: accessAuditLog.actor
|
actor: accessAuditLog.actor
|
||||||
})
|
})
|
||||||
.from(accessAuditLog)
|
.from(accessAuditLog)
|
||||||
.leftJoin(
|
|
||||||
resources,
|
|
||||||
eq(accessAuditLog.resourceId, resources.resourceId)
|
|
||||||
)
|
|
||||||
.where(getWhere(data))
|
.where(getWhere(data))
|
||||||
.orderBy(desc(accessAuditLog.timestamp), desc(accessAuditLog.id));
|
.orderBy(desc(accessAuditLog.timestamp), desc(accessAuditLog.id));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function enrichWithResourceDetails(logs: Awaited<ReturnType<typeof queryAccess>>) {
|
||||||
|
// If logs database is the same as main database, we can do a join
|
||||||
|
// Otherwise, we need to fetch resource details separately
|
||||||
|
const resourceIds = logs
|
||||||
|
.map(log => log.resourceId)
|
||||||
|
.filter((id): id is number => id !== null && id !== undefined);
|
||||||
|
|
||||||
|
if (resourceIds.length === 0) {
|
||||||
|
return logs.map(log => ({ ...log, resourceName: null, resourceNiceId: null }));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch resource details from main database
|
||||||
|
const resourceDetails = await primaryDb
|
||||||
|
.select({
|
||||||
|
resourceId: resources.resourceId,
|
||||||
|
name: resources.name,
|
||||||
|
niceId: resources.niceId
|
||||||
|
})
|
||||||
|
.from(resources)
|
||||||
|
.where(inArray(resources.resourceId, resourceIds));
|
||||||
|
|
||||||
|
// Create a map for quick lookup
|
||||||
|
const resourceMap = new Map(
|
||||||
|
resourceDetails.map(r => [r.resourceId, { name: r.name, niceId: r.niceId }])
|
||||||
|
);
|
||||||
|
|
||||||
|
// Enrich logs with resource details
|
||||||
|
return logs.map(log => ({
|
||||||
|
...log,
|
||||||
|
resourceName: log.resourceId ? resourceMap.get(log.resourceId)?.name ?? null : null,
|
||||||
|
resourceNiceId: log.resourceId ? resourceMap.get(log.resourceId)?.niceId ?? null : null
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
export function countAccessQuery(data: Q) {
|
export function countAccessQuery(data: Q) {
|
||||||
const countQuery = db
|
const countQuery = logsDb
|
||||||
.select({ count: count() })
|
.select({ count: count() })
|
||||||
.from(accessAuditLog)
|
.from(accessAuditLog)
|
||||||
.where(getWhere(data));
|
.where(getWhere(data));
|
||||||
@@ -161,7 +191,7 @@ async function queryUniqueFilterAttributes(
|
|||||||
);
|
);
|
||||||
|
|
||||||
// Get unique actors
|
// Get unique actors
|
||||||
const uniqueActors = await db
|
const uniqueActors = await logsDb
|
||||||
.selectDistinct({
|
.selectDistinct({
|
||||||
actor: accessAuditLog.actor
|
actor: accessAuditLog.actor
|
||||||
})
|
})
|
||||||
@@ -169,7 +199,7 @@ async function queryUniqueFilterAttributes(
|
|||||||
.where(baseConditions);
|
.where(baseConditions);
|
||||||
|
|
||||||
// Get unique locations
|
// Get unique locations
|
||||||
const uniqueLocations = await db
|
const uniqueLocations = await logsDb
|
||||||
.selectDistinct({
|
.selectDistinct({
|
||||||
locations: accessAuditLog.location
|
locations: accessAuditLog.location
|
||||||
})
|
})
|
||||||
@@ -177,25 +207,40 @@ async function queryUniqueFilterAttributes(
|
|||||||
.where(baseConditions);
|
.where(baseConditions);
|
||||||
|
|
||||||
// Get unique resources with names
|
// Get unique resources with names
|
||||||
const uniqueResources = await db
|
const uniqueResources = await logsDb
|
||||||
.selectDistinct({
|
.selectDistinct({
|
||||||
id: accessAuditLog.resourceId,
|
id: accessAuditLog.resourceId
|
||||||
name: resources.name
|
|
||||||
})
|
})
|
||||||
.from(accessAuditLog)
|
.from(accessAuditLog)
|
||||||
.leftJoin(
|
|
||||||
resources,
|
|
||||||
eq(accessAuditLog.resourceId, resources.resourceId)
|
|
||||||
)
|
|
||||||
.where(baseConditions);
|
.where(baseConditions);
|
||||||
|
|
||||||
|
// Fetch resource names from main database for the unique resource IDs
|
||||||
|
const resourceIds = uniqueResources
|
||||||
|
.map(row => row.id)
|
||||||
|
.filter((id): id is number => id !== null);
|
||||||
|
|
||||||
|
let resourcesWithNames: Array<{ id: number; name: string | null }> = [];
|
||||||
|
|
||||||
|
if (resourceIds.length > 0) {
|
||||||
|
const resourceDetails = await primaryDb
|
||||||
|
.select({
|
||||||
|
resourceId: resources.resourceId,
|
||||||
|
name: resources.name
|
||||||
|
})
|
||||||
|
.from(resources)
|
||||||
|
.where(inArray(resources.resourceId, resourceIds));
|
||||||
|
|
||||||
|
resourcesWithNames = resourceDetails.map(r => ({
|
||||||
|
id: r.resourceId,
|
||||||
|
name: r.name
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
actors: uniqueActors
|
actors: uniqueActors
|
||||||
.map((row) => row.actor)
|
.map((row) => row.actor)
|
||||||
.filter((actor): actor is string => actor !== null),
|
.filter((actor): actor is string => actor !== null),
|
||||||
resources: uniqueResources.filter(
|
resources: resourcesWithNames,
|
||||||
(row): row is { id: number; name: string | null } => row.id !== null
|
|
||||||
),
|
|
||||||
locations: uniqueLocations
|
locations: uniqueLocations
|
||||||
.map((row) => row.locations)
|
.map((row) => row.locations)
|
||||||
.filter((location): location is string => location !== null)
|
.filter((location): location is string => location !== null)
|
||||||
@@ -243,7 +288,10 @@ export async function queryAccessAuditLogs(
|
|||||||
|
|
||||||
const baseQuery = queryAccess(data);
|
const baseQuery = queryAccess(data);
|
||||||
|
|
||||||
const log = await baseQuery.limit(data.limit).offset(data.offset);
|
const logsRaw = await baseQuery.limit(data.limit).offset(data.offset);
|
||||||
|
|
||||||
|
// Enrich with resource details (handles cross-database scenario)
|
||||||
|
const log = await enrichWithResourceDetails(logsRaw);
|
||||||
|
|
||||||
const totalCountResult = await countAccessQuery(data);
|
const totalCountResult = await countAccessQuery(data);
|
||||||
const totalCount = totalCountResult[0].count;
|
const totalCount = totalCountResult[0].count;
|
||||||
|
|||||||
@@ -11,7 +11,7 @@
|
|||||||
* This file is not licensed under the AGPLv3.
|
* This file is not licensed under the AGPLv3.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { actionAuditLog, db } from "@server/db";
|
import { actionAuditLog, logsDb } from "@server/db";
|
||||||
import { registry } from "@server/openApi";
|
import { registry } from "@server/openApi";
|
||||||
import { NextFunction } from "express";
|
import { NextFunction } from "express";
|
||||||
import { Request, Response } from "express";
|
import { Request, Response } from "express";
|
||||||
@@ -97,7 +97,7 @@ function getWhere(data: Q) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function queryAction(data: Q) {
|
export function queryAction(data: Q) {
|
||||||
return db
|
return logsDb
|
||||||
.select({
|
.select({
|
||||||
orgId: actionAuditLog.orgId,
|
orgId: actionAuditLog.orgId,
|
||||||
action: actionAuditLog.action,
|
action: actionAuditLog.action,
|
||||||
@@ -113,7 +113,7 @@ export function queryAction(data: Q) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function countActionQuery(data: Q) {
|
export function countActionQuery(data: Q) {
|
||||||
const countQuery = db
|
const countQuery = logsDb
|
||||||
.select({ count: count() })
|
.select({ count: count() })
|
||||||
.from(actionAuditLog)
|
.from(actionAuditLog)
|
||||||
.where(getWhere(data));
|
.where(getWhere(data));
|
||||||
@@ -132,14 +132,14 @@ async function queryUniqueFilterAttributes(
|
|||||||
);
|
);
|
||||||
|
|
||||||
// Get unique actors
|
// Get unique actors
|
||||||
const uniqueActors = await db
|
const uniqueActors = await logsDb
|
||||||
.selectDistinct({
|
.selectDistinct({
|
||||||
actor: actionAuditLog.actor
|
actor: actionAuditLog.actor
|
||||||
})
|
})
|
||||||
.from(actionAuditLog)
|
.from(actionAuditLog)
|
||||||
.where(baseConditions);
|
.where(baseConditions);
|
||||||
|
|
||||||
const uniqueActions = await db
|
const uniqueActions = await logsDb
|
||||||
.selectDistinct({
|
.selectDistinct({
|
||||||
action: actionAuditLog.action
|
action: actionAuditLog.action
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -14,7 +14,7 @@
|
|||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { db } from "@server/db";
|
import { db } from "@server/db";
|
||||||
import { userOrgs, userOrgRoles, users, roles, orgs } from "@server/db";
|
import { userOrgs, users, roles, orgs } from "@server/db";
|
||||||
import { eq, and, or } from "drizzle-orm";
|
import { eq, and, or } from "drizzle-orm";
|
||||||
import response from "@server/lib/response";
|
import response from "@server/lib/response";
|
||||||
import HttpCode from "@server/types/HttpCode";
|
import HttpCode from "@server/types/HttpCode";
|
||||||
@@ -95,14 +95,7 @@ async function getOrgAdmins(orgId: string) {
|
|||||||
})
|
})
|
||||||
.from(userOrgs)
|
.from(userOrgs)
|
||||||
.innerJoin(users, eq(userOrgs.userId, users.userId))
|
.innerJoin(users, eq(userOrgs.userId, users.userId))
|
||||||
.leftJoin(
|
.leftJoin(roles, eq(userOrgs.roleId, roles.roleId))
|
||||||
userOrgRoles,
|
|
||||||
and(
|
|
||||||
eq(userOrgs.userId, userOrgRoles.userId),
|
|
||||||
eq(userOrgs.orgId, userOrgRoles.orgId)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.leftJoin(roles, eq(userOrgRoles.roleId, roles.roleId))
|
|
||||||
.where(
|
.where(
|
||||||
and(
|
and(
|
||||||
eq(userOrgs.orgId, orgId),
|
eq(userOrgs.orgId, orgId),
|
||||||
@@ -110,11 +103,8 @@ async function getOrgAdmins(orgId: string) {
|
|||||||
)
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
// Dedupe by userId (user may have multiple roles)
|
// Filter to only include users with verified emails
|
||||||
const byUserId = new Map(
|
const orgAdmins = admins.filter(
|
||||||
admins.map((a) => [a.userId, a])
|
|
||||||
);
|
|
||||||
const orgAdmins = Array.from(byUserId.values()).filter(
|
|
||||||
(admin) => admin.email && admin.email.length > 0
|
(admin) => admin.email && admin.email.length > 0
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ export async function createRemoteExitNode(
|
|||||||
|
|
||||||
const { remoteExitNodeId, secret } = parsedBody.data;
|
const { remoteExitNodeId, secret } = parsedBody.data;
|
||||||
|
|
||||||
if (req.user && (!req.userOrgRoleIds || req.userOrgRoleIds.length === 0)) {
|
if (req.user && !req.userOrgRoleId) {
|
||||||
return next(
|
return next(
|
||||||
createHttpError(HttpCode.FORBIDDEN, "User does not have a role")
|
createHttpError(HttpCode.FORBIDDEN, "User does not have a role")
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ import createHttpError from "http-errors";
|
|||||||
import logger from "@server/logger";
|
import logger from "@server/logger";
|
||||||
import { fromError } from "zod-validation-error";
|
import { fromError } from "zod-validation-error";
|
||||||
import { OpenAPITags, registry } from "@server/openApi";
|
import { OpenAPITags, registry } from "@server/openApi";
|
||||||
import { and, eq, inArray, or } from "drizzle-orm";
|
import { eq, or, and } from "drizzle-orm";
|
||||||
import { canUserAccessSiteResource } from "@server/auth/canUserAccessSiteResource";
|
import { canUserAccessSiteResource } from "@server/auth/canUserAccessSiteResource";
|
||||||
import { signPublicKey, getOrgCAKeys } from "#private/lib/sshCA";
|
import { signPublicKey, getOrgCAKeys } from "#private/lib/sshCA";
|
||||||
import config from "@server/lib/config";
|
import config from "@server/lib/config";
|
||||||
@@ -122,7 +122,7 @@ export async function signSshKey(
|
|||||||
resource: resourceQueryString
|
resource: resourceQueryString
|
||||||
} = parsedBody.data;
|
} = parsedBody.data;
|
||||||
const userId = req.user?.userId;
|
const userId = req.user?.userId;
|
||||||
const roleIds = req.userOrgRoleIds ?? [];
|
const roleId = req.userOrgRoleId!;
|
||||||
|
|
||||||
if (!userId) {
|
if (!userId) {
|
||||||
return next(
|
return next(
|
||||||
@@ -130,15 +130,6 @@ export async function signSshKey(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (roleIds.length === 0) {
|
|
||||||
return next(
|
|
||||||
createHttpError(
|
|
||||||
HttpCode.FORBIDDEN,
|
|
||||||
"User has no role in organization"
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const [userOrg] = await db
|
const [userOrg] = await db
|
||||||
.select()
|
.select()
|
||||||
.from(userOrgs)
|
.from(userOrgs)
|
||||||
@@ -319,11 +310,11 @@ export async function signSshKey(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if the user has access to the resource (any of their roles)
|
// Check if the user has access to the resource
|
||||||
const hasAccess = await canUserAccessSiteResource({
|
const hasAccess = await canUserAccessSiteResource({
|
||||||
userId: userId,
|
userId: userId,
|
||||||
resourceId: resource.siteResourceId,
|
resourceId: resource.siteResourceId,
|
||||||
roleIds
|
roleId: roleId
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!hasAccess) {
|
if (!hasAccess) {
|
||||||
@@ -335,39 +326,28 @@ export async function signSshKey(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const roleRows = await db
|
const [roleRow] = await db
|
||||||
.select()
|
.select()
|
||||||
.from(roles)
|
.from(roles)
|
||||||
.where(inArray(roles.roleId, roleIds));
|
.where(eq(roles.roleId, roleId))
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
const parsedSudoCommands: string[] = [];
|
let parsedSudoCommands: string[] = [];
|
||||||
const parsedGroupsSet = new Set<string>();
|
let parsedGroups: string[] = [];
|
||||||
let homedir: boolean | null = null;
|
try {
|
||||||
const sudoModeOrder = { none: 0, commands: 1, all: 2 };
|
parsedSudoCommands = JSON.parse(roleRow?.sshSudoCommands ?? "[]");
|
||||||
let sudoMode: "none" | "commands" | "all" = "none";
|
if (!Array.isArray(parsedSudoCommands)) parsedSudoCommands = [];
|
||||||
for (const roleRow of roleRows) {
|
} catch {
|
||||||
try {
|
parsedSudoCommands = [];
|
||||||
const cmds = JSON.parse(roleRow?.sshSudoCommands ?? "[]");
|
|
||||||
if (Array.isArray(cmds)) parsedSudoCommands.push(...cmds);
|
|
||||||
} catch {
|
|
||||||
// skip
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
const grps = JSON.parse(roleRow?.sshUnixGroups ?? "[]");
|
|
||||||
if (Array.isArray(grps)) grps.forEach((g: string) => parsedGroupsSet.add(g));
|
|
||||||
} catch {
|
|
||||||
// skip
|
|
||||||
}
|
|
||||||
if (roleRow?.sshCreateHomeDir === true) homedir = true;
|
|
||||||
const m = roleRow?.sshSudoMode ?? "none";
|
|
||||||
if (sudoModeOrder[m as keyof typeof sudoModeOrder] > sudoModeOrder[sudoMode]) {
|
|
||||||
sudoMode = m as "none" | "commands" | "all";
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
const parsedGroups = Array.from(parsedGroupsSet);
|
try {
|
||||||
if (homedir === null && roleRows.length > 0) {
|
parsedGroups = JSON.parse(roleRow?.sshUnixGroups ?? "[]");
|
||||||
homedir = roleRows[0].sshCreateHomeDir ?? null;
|
if (!Array.isArray(parsedGroups)) parsedGroups = [];
|
||||||
|
} catch {
|
||||||
|
parsedGroups = [];
|
||||||
}
|
}
|
||||||
|
const homedir = roleRow?.sshCreateHomeDir ?? null;
|
||||||
|
const sudoMode = roleRow?.sshSudoMode ?? "none";
|
||||||
|
|
||||||
// get the site
|
// get the site
|
||||||
const [newt] = await db
|
const [newt] = await db
|
||||||
|
|||||||
@@ -208,7 +208,7 @@ export async function listAccessTokens(
|
|||||||
.where(
|
.where(
|
||||||
or(
|
or(
|
||||||
eq(userResources.userId, req.user!.userId),
|
eq(userResources.userId, req.user!.userId),
|
||||||
inArray(roleResources.roleId, req.userOrgRoleIds!)
|
eq(roleResources.roleId, req.userOrgRoleId!)
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { db, requestAuditLog, driver, primaryDb } from "@server/db";
|
import { logsDb, requestAuditLog, driver, primaryLogsDb } from "@server/db";
|
||||||
import { registry } from "@server/openApi";
|
import { registry } from "@server/openApi";
|
||||||
import { NextFunction } from "express";
|
import { NextFunction } from "express";
|
||||||
import { Request, Response } from "express";
|
import { Request, Response } from "express";
|
||||||
@@ -74,12 +74,12 @@ async function query(query: Q) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const [all] = await primaryDb
|
const [all] = await primaryLogsDb
|
||||||
.select({ total: count() })
|
.select({ total: count() })
|
||||||
.from(requestAuditLog)
|
.from(requestAuditLog)
|
||||||
.where(baseConditions);
|
.where(baseConditions);
|
||||||
|
|
||||||
const [blocked] = await primaryDb
|
const [blocked] = await primaryLogsDb
|
||||||
.select({ total: count() })
|
.select({ total: count() })
|
||||||
.from(requestAuditLog)
|
.from(requestAuditLog)
|
||||||
.where(and(baseConditions, eq(requestAuditLog.action, false)));
|
.where(and(baseConditions, eq(requestAuditLog.action, false)));
|
||||||
@@ -90,7 +90,7 @@ async function query(query: Q) {
|
|||||||
|
|
||||||
const DISTINCT_LIMIT = 500;
|
const DISTINCT_LIMIT = 500;
|
||||||
|
|
||||||
const requestsPerCountry = await primaryDb
|
const requestsPerCountry = await primaryLogsDb
|
||||||
.selectDistinct({
|
.selectDistinct({
|
||||||
code: requestAuditLog.location,
|
code: requestAuditLog.location,
|
||||||
count: totalQ
|
count: totalQ
|
||||||
@@ -118,7 +118,7 @@ async function query(query: Q) {
|
|||||||
const booleanTrue = driver === "pg" ? sql`true` : sql`1`;
|
const booleanTrue = driver === "pg" ? sql`true` : sql`1`;
|
||||||
const booleanFalse = driver === "pg" ? sql`false` : sql`0`;
|
const booleanFalse = driver === "pg" ? sql`false` : sql`0`;
|
||||||
|
|
||||||
const requestsPerDay = await primaryDb
|
const requestsPerDay = await primaryLogsDb
|
||||||
.select({
|
.select({
|
||||||
day: groupByDayFunction.as("day"),
|
day: groupByDayFunction.as("day"),
|
||||||
allowedCount:
|
allowedCount:
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import { db, primaryDb, requestAuditLog, resources } from "@server/db";
|
import { logsDb, primaryLogsDb, requestAuditLog, resources, db, primaryDb } from "@server/db";
|
||||||
import { registry } from "@server/openApi";
|
import { registry } from "@server/openApi";
|
||||||
import { NextFunction } from "express";
|
import { NextFunction } from "express";
|
||||||
import { Request, Response } from "express";
|
import { Request, Response } from "express";
|
||||||
import { eq, gt, lt, and, count, desc } from "drizzle-orm";
|
import { eq, gt, lt, and, count, desc, inArray } from "drizzle-orm";
|
||||||
import { OpenAPITags } from "@server/openApi";
|
import { OpenAPITags } from "@server/openApi";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import createHttpError from "http-errors";
|
import createHttpError from "http-errors";
|
||||||
@@ -107,7 +107,7 @@ function getWhere(data: Q) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function queryRequest(data: Q) {
|
export function queryRequest(data: Q) {
|
||||||
return primaryDb
|
return primaryLogsDb
|
||||||
.select({
|
.select({
|
||||||
id: requestAuditLog.id,
|
id: requestAuditLog.id,
|
||||||
timestamp: requestAuditLog.timestamp,
|
timestamp: requestAuditLog.timestamp,
|
||||||
@@ -129,21 +129,49 @@ export function queryRequest(data: Q) {
|
|||||||
host: requestAuditLog.host,
|
host: requestAuditLog.host,
|
||||||
path: requestAuditLog.path,
|
path: requestAuditLog.path,
|
||||||
method: requestAuditLog.method,
|
method: requestAuditLog.method,
|
||||||
tls: requestAuditLog.tls,
|
tls: requestAuditLog.tls
|
||||||
resourceName: resources.name,
|
|
||||||
resourceNiceId: resources.niceId
|
|
||||||
})
|
})
|
||||||
.from(requestAuditLog)
|
.from(requestAuditLog)
|
||||||
.leftJoin(
|
|
||||||
resources,
|
|
||||||
eq(requestAuditLog.resourceId, resources.resourceId)
|
|
||||||
) // TODO: Is this efficient?
|
|
||||||
.where(getWhere(data))
|
.where(getWhere(data))
|
||||||
.orderBy(desc(requestAuditLog.timestamp));
|
.orderBy(desc(requestAuditLog.timestamp));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function enrichWithResourceDetails(logs: Awaited<ReturnType<typeof queryRequest>>) {
|
||||||
|
// If logs database is the same as main database, we can do a join
|
||||||
|
// Otherwise, we need to fetch resource details separately
|
||||||
|
const resourceIds = logs
|
||||||
|
.map(log => log.resourceId)
|
||||||
|
.filter((id): id is number => id !== null && id !== undefined);
|
||||||
|
|
||||||
|
if (resourceIds.length === 0) {
|
||||||
|
return logs.map(log => ({ ...log, resourceName: null, resourceNiceId: null }));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fetch resource details from main database
|
||||||
|
const resourceDetails = await primaryDb
|
||||||
|
.select({
|
||||||
|
resourceId: resources.resourceId,
|
||||||
|
name: resources.name,
|
||||||
|
niceId: resources.niceId
|
||||||
|
})
|
||||||
|
.from(resources)
|
||||||
|
.where(inArray(resources.resourceId, resourceIds));
|
||||||
|
|
||||||
|
// Create a map for quick lookup
|
||||||
|
const resourceMap = new Map(
|
||||||
|
resourceDetails.map(r => [r.resourceId, { name: r.name, niceId: r.niceId }])
|
||||||
|
);
|
||||||
|
|
||||||
|
// Enrich logs with resource details
|
||||||
|
return logs.map(log => ({
|
||||||
|
...log,
|
||||||
|
resourceName: log.resourceId ? resourceMap.get(log.resourceId)?.name ?? null : null,
|
||||||
|
resourceNiceId: log.resourceId ? resourceMap.get(log.resourceId)?.niceId ?? null : null
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
export function countRequestQuery(data: Q) {
|
export function countRequestQuery(data: Q) {
|
||||||
const countQuery = primaryDb
|
const countQuery = primaryLogsDb
|
||||||
.select({ count: count() })
|
.select({ count: count() })
|
||||||
.from(requestAuditLog)
|
.from(requestAuditLog)
|
||||||
.where(getWhere(data));
|
.where(getWhere(data));
|
||||||
@@ -185,36 +213,31 @@ async function queryUniqueFilterAttributes(
|
|||||||
uniquePaths,
|
uniquePaths,
|
||||||
uniqueResources
|
uniqueResources
|
||||||
] = await Promise.all([
|
] = await Promise.all([
|
||||||
primaryDb
|
primaryLogsDb
|
||||||
.selectDistinct({ actor: requestAuditLog.actor })
|
.selectDistinct({ actor: requestAuditLog.actor })
|
||||||
.from(requestAuditLog)
|
.from(requestAuditLog)
|
||||||
.where(baseConditions)
|
.where(baseConditions)
|
||||||
.limit(DISTINCT_LIMIT + 1),
|
.limit(DISTINCT_LIMIT + 1),
|
||||||
primaryDb
|
primaryLogsDb
|
||||||
.selectDistinct({ locations: requestAuditLog.location })
|
.selectDistinct({ locations: requestAuditLog.location })
|
||||||
.from(requestAuditLog)
|
.from(requestAuditLog)
|
||||||
.where(baseConditions)
|
.where(baseConditions)
|
||||||
.limit(DISTINCT_LIMIT + 1),
|
.limit(DISTINCT_LIMIT + 1),
|
||||||
primaryDb
|
primaryLogsDb
|
||||||
.selectDistinct({ hosts: requestAuditLog.host })
|
.selectDistinct({ hosts: requestAuditLog.host })
|
||||||
.from(requestAuditLog)
|
.from(requestAuditLog)
|
||||||
.where(baseConditions)
|
.where(baseConditions)
|
||||||
.limit(DISTINCT_LIMIT + 1),
|
.limit(DISTINCT_LIMIT + 1),
|
||||||
primaryDb
|
primaryLogsDb
|
||||||
.selectDistinct({ paths: requestAuditLog.path })
|
.selectDistinct({ paths: requestAuditLog.path })
|
||||||
.from(requestAuditLog)
|
.from(requestAuditLog)
|
||||||
.where(baseConditions)
|
.where(baseConditions)
|
||||||
.limit(DISTINCT_LIMIT + 1),
|
.limit(DISTINCT_LIMIT + 1),
|
||||||
primaryDb
|
primaryLogsDb
|
||||||
.selectDistinct({
|
.selectDistinct({
|
||||||
id: requestAuditLog.resourceId,
|
id: requestAuditLog.resourceId
|
||||||
name: resources.name
|
|
||||||
})
|
})
|
||||||
.from(requestAuditLog)
|
.from(requestAuditLog)
|
||||||
.leftJoin(
|
|
||||||
resources,
|
|
||||||
eq(requestAuditLog.resourceId, resources.resourceId)
|
|
||||||
)
|
|
||||||
.where(baseConditions)
|
.where(baseConditions)
|
||||||
.limit(DISTINCT_LIMIT + 1)
|
.limit(DISTINCT_LIMIT + 1)
|
||||||
]);
|
]);
|
||||||
@@ -231,13 +254,33 @@ async function queryUniqueFilterAttributes(
|
|||||||
// throw new Error("Too many distinct filter attributes to retrieve. Please refine your time range.");
|
// throw new Error("Too many distinct filter attributes to retrieve. Please refine your time range.");
|
||||||
// }
|
// }
|
||||||
|
|
||||||
|
// Fetch resource names from main database for the unique resource IDs
|
||||||
|
const resourceIds = uniqueResources
|
||||||
|
.map(row => row.id)
|
||||||
|
.filter((id): id is number => id !== null);
|
||||||
|
|
||||||
|
let resourcesWithNames: Array<{ id: number; name: string | null }> = [];
|
||||||
|
|
||||||
|
if (resourceIds.length > 0) {
|
||||||
|
const resourceDetails = await primaryDb
|
||||||
|
.select({
|
||||||
|
resourceId: resources.resourceId,
|
||||||
|
name: resources.name
|
||||||
|
})
|
||||||
|
.from(resources)
|
||||||
|
.where(inArray(resources.resourceId, resourceIds));
|
||||||
|
|
||||||
|
resourcesWithNames = resourceDetails.map(r => ({
|
||||||
|
id: r.resourceId,
|
||||||
|
name: r.name
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
actors: uniqueActors
|
actors: uniqueActors
|
||||||
.map((row) => row.actor)
|
.map((row) => row.actor)
|
||||||
.filter((actor): actor is string => actor !== null),
|
.filter((actor): actor is string => actor !== null),
|
||||||
resources: uniqueResources.filter(
|
resources: resourcesWithNames,
|
||||||
(row): row is { id: number; name: string | null } => row.id !== null
|
|
||||||
),
|
|
||||||
locations: uniqueLocations
|
locations: uniqueLocations
|
||||||
.map((row) => row.locations)
|
.map((row) => row.locations)
|
||||||
.filter((location): location is string => location !== null),
|
.filter((location): location is string => location !== null),
|
||||||
@@ -280,7 +323,10 @@ export async function queryRequestAuditLogs(
|
|||||||
|
|
||||||
const baseQuery = queryRequest(data);
|
const baseQuery = queryRequest(data);
|
||||||
|
|
||||||
const log = await baseQuery.limit(data.limit).offset(data.offset);
|
const logsRaw = await baseQuery.limit(data.limit).offset(data.offset);
|
||||||
|
|
||||||
|
// Enrich with resource details (handles cross-database scenario)
|
||||||
|
const log = await enrichWithResourceDetails(logsRaw);
|
||||||
|
|
||||||
const totalCountResult = await countRequestQuery(data);
|
const totalCountResult = await countRequestQuery(data);
|
||||||
const totalCount = totalCountResult[0].count;
|
const totalCount = totalCountResult[0].count;
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { db, orgs, requestAuditLog } from "@server/db";
|
import { logsDb, primaryLogsDb, db, orgs, requestAuditLog } from "@server/db";
|
||||||
import logger from "@server/logger";
|
import logger from "@server/logger";
|
||||||
import { and, eq, lt, sql } from "drizzle-orm";
|
import { and, eq, lt, sql } from "drizzle-orm";
|
||||||
import cache from "@server/lib/cache";
|
import cache from "@server/lib/cache";
|
||||||
@@ -69,7 +69,7 @@ async function flushAuditLogs() {
|
|||||||
try {
|
try {
|
||||||
// Use a transaction to ensure all inserts succeed or fail together
|
// Use a transaction to ensure all inserts succeed or fail together
|
||||||
// This prevents index corruption from partial writes
|
// This prevents index corruption from partial writes
|
||||||
await db.transaction(async (tx) => {
|
await logsDb.transaction(async (tx) => {
|
||||||
// Batch insert logs in groups of 25 to avoid overwhelming the database
|
// Batch insert logs in groups of 25 to avoid overwhelming the database
|
||||||
const BATCH_DB_SIZE = 25;
|
const BATCH_DB_SIZE = 25;
|
||||||
for (let i = 0; i < logsToWrite.length; i += BATCH_DB_SIZE) {
|
for (let i = 0; i < logsToWrite.length; i += BATCH_DB_SIZE) {
|
||||||
@@ -162,7 +162,7 @@ export async function cleanUpOldLogs(orgId: string, retentionDays: number) {
|
|||||||
const cutoffTimestamp = calculateCutoffTimestamp(retentionDays);
|
const cutoffTimestamp = calculateCutoffTimestamp(retentionDays);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await db
|
await logsDb
|
||||||
.delete(requestAuditLog)
|
.delete(requestAuditLog)
|
||||||
.where(
|
.where(
|
||||||
and(
|
and(
|
||||||
|
|||||||
@@ -3,13 +3,12 @@ import { verifyResourceAccessToken } from "@server/auth/verifyResourceAccessToke
|
|||||||
import {
|
import {
|
||||||
getResourceByDomain,
|
getResourceByDomain,
|
||||||
getResourceRules,
|
getResourceRules,
|
||||||
getRoleName,
|
|
||||||
getRoleResourceAccess,
|
getRoleResourceAccess,
|
||||||
|
getUserOrgRole,
|
||||||
getUserResourceAccess,
|
getUserResourceAccess,
|
||||||
getOrgLoginPage,
|
getOrgLoginPage,
|
||||||
getUserSessionWithUser
|
getUserSessionWithUser
|
||||||
} from "@server/db/queries/verifySessionQueries";
|
} from "@server/db/queries/verifySessionQueries";
|
||||||
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
|
|
||||||
import {
|
import {
|
||||||
LoginPage,
|
LoginPage,
|
||||||
Org,
|
Org,
|
||||||
@@ -917,9 +916,9 @@ async function isUserAllowedToAccessResource(
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const userOrgRoleIds = await getUserOrgRoleIds(user.userId, resource.orgId);
|
const userOrgRole = await getUserOrgRole(user.userId, resource.orgId);
|
||||||
|
|
||||||
if (!userOrgRoleIds.length) {
|
if (!userOrgRole) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -935,23 +934,17 @@ async function isUserAllowedToAccessResource(
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const roleNames: string[] = [];
|
const roleResourceAccess = await getRoleResourceAccess(
|
||||||
for (const roleId of userOrgRoleIds) {
|
resource.resourceId,
|
||||||
const roleResourceAccess = await getRoleResourceAccess(
|
userOrgRole.roleId
|
||||||
resource.resourceId,
|
);
|
||||||
roleId
|
|
||||||
);
|
if (roleResourceAccess) {
|
||||||
if (roleResourceAccess) {
|
|
||||||
const roleName = await getRoleName(roleId);
|
|
||||||
if (roleName) roleNames.push(roleName);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (roleNames.length > 0) {
|
|
||||||
return {
|
return {
|
||||||
username: user.username,
|
username: user.username,
|
||||||
email: user.email,
|
email: user.email,
|
||||||
name: user.name,
|
name: user.name,
|
||||||
role: roleNames.join(", ")
|
role: userOrgRole.roleName
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -961,15 +954,11 @@ async function isUserAllowedToAccessResource(
|
|||||||
);
|
);
|
||||||
|
|
||||||
if (userResourceAccess) {
|
if (userResourceAccess) {
|
||||||
const names = await Promise.all(
|
|
||||||
userOrgRoleIds.map((id) => getRoleName(id))
|
|
||||||
);
|
|
||||||
const role = names.filter(Boolean).join(", ") || "";
|
|
||||||
return {
|
return {
|
||||||
username: user.username,
|
username: user.username,
|
||||||
email: user.email,
|
email: user.email,
|
||||||
name: user.name,
|
name: user.name,
|
||||||
role
|
role: userOrgRole.roleName
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -92,7 +92,7 @@ export async function createClient(
|
|||||||
|
|
||||||
const { orgId } = parsedParams.data;
|
const { orgId } = parsedParams.data;
|
||||||
|
|
||||||
if (req.user && (!req.userOrgRoleIds || req.userOrgRoleIds.length === 0)) {
|
if (req.user && !req.userOrgRoleId) {
|
||||||
return next(
|
return next(
|
||||||
createHttpError(HttpCode.FORBIDDEN, "User does not have a role")
|
createHttpError(HttpCode.FORBIDDEN, "User does not have a role")
|
||||||
);
|
);
|
||||||
@@ -234,7 +234,7 @@ export async function createClient(
|
|||||||
clientId: newClient.clientId
|
clientId: newClient.clientId
|
||||||
});
|
});
|
||||||
|
|
||||||
if (req.user && !req.userOrgRoleIds?.includes(adminRole.roleId)) {
|
if (req.user && req.userOrgRoleId != adminRole.roleId) {
|
||||||
// make sure the user can access the client
|
// make sure the user can access the client
|
||||||
trx.insert(userClients).values({
|
trx.insert(userClients).values({
|
||||||
userId: req.user.userId,
|
userId: req.user.userId,
|
||||||
|
|||||||
@@ -297,7 +297,7 @@ export async function listClients(
|
|||||||
.where(
|
.where(
|
||||||
or(
|
or(
|
||||||
eq(userClients.userId, req.user!.userId),
|
eq(userClients.userId, req.user!.userId),
|
||||||
inArray(roleClients.roleId, req.userOrgRoleIds!)
|
eq(roleClients.roleId, req.userOrgRoleId!)
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -316,7 +316,7 @@ export async function listUserDevices(
|
|||||||
.where(
|
.where(
|
||||||
or(
|
or(
|
||||||
eq(userClients.userId, req.user!.userId),
|
eq(userClients.userId, req.user!.userId),
|
||||||
inArray(roleClients.roleId, req.userOrgRoleIds!)
|
eq(roleClients.roleId, req.userOrgRoleId!)
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -654,16 +654,6 @@ authenticated.post(
|
|||||||
user.addUserRole
|
user.addUserRole
|
||||||
);
|
);
|
||||||
|
|
||||||
authenticated.delete(
|
|
||||||
"/role/:roleId/remove/:userId",
|
|
||||||
verifyRoleAccess,
|
|
||||||
verifyUserAccess,
|
|
||||||
verifyLimits,
|
|
||||||
verifyUserHasAction(ActionsEnum.removeUserRole),
|
|
||||||
logActionAudit(ActionsEnum.removeUserRole),
|
|
||||||
user.removeUserRole
|
|
||||||
);
|
|
||||||
|
|
||||||
authenticated.post(
|
authenticated.post(
|
||||||
"/resource/:resourceId/roles",
|
"/resource/:resourceId/roles",
|
||||||
verifyResourceAccess,
|
verifyResourceAccess,
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ import {
|
|||||||
orgs,
|
orgs,
|
||||||
Role,
|
Role,
|
||||||
roles,
|
roles,
|
||||||
userOrgRoles,
|
|
||||||
userOrgs,
|
userOrgs,
|
||||||
users
|
users
|
||||||
} from "@server/db";
|
} from "@server/db";
|
||||||
@@ -571,28 +570,32 @@ export async function validateOidcCallback(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ensure IDP-provided role exists for existing auto-provisioned orgs (add only; never delete other roles)
|
// Update roles for existing auto-provisioned orgs where the role has changed
|
||||||
const userRolesInOrgs = await trx
|
const orgsToUpdate = autoProvisionedOrgs.filter(
|
||||||
.select()
|
(currentOrg) => {
|
||||||
.from(userOrgRoles)
|
const newOrg = userOrgInfo.find(
|
||||||
.where(eq(userOrgRoles.userId, userId!));
|
(newOrg) => newOrg.orgId === currentOrg.orgId
|
||||||
for (const currentOrg of autoProvisionedOrgs) {
|
);
|
||||||
const newRole = userOrgInfo.find(
|
return newOrg && newOrg.roleId !== currentOrg.roleId;
|
||||||
(newOrg) => newOrg.orgId === currentOrg.orgId
|
}
|
||||||
);
|
);
|
||||||
if (!newRole) continue;
|
|
||||||
const currentRolesInOrg = userRolesInOrgs.filter(
|
if (orgsToUpdate.length > 0) {
|
||||||
(r) => r.orgId === currentOrg.orgId
|
for (const org of orgsToUpdate) {
|
||||||
);
|
const newRole = userOrgInfo.find(
|
||||||
const hasIdpRole = currentRolesInOrg.some(
|
(newOrg) => newOrg.orgId === org.orgId
|
||||||
(r) => r.roleId === newRole.roleId
|
);
|
||||||
);
|
if (newRole) {
|
||||||
if (!hasIdpRole) {
|
await trx
|
||||||
await trx.insert(userOrgRoles).values({
|
.update(userOrgs)
|
||||||
userId: userId!,
|
.set({ roleId: newRole.roleId })
|
||||||
orgId: currentOrg.orgId,
|
.where(
|
||||||
roleId: newRole.roleId
|
and(
|
||||||
});
|
eq(userOrgs.userId, userId!),
|
||||||
|
eq(userOrgs.orgId, org.orgId)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -616,9 +619,9 @@ export async function validateOidcCallback(
|
|||||||
{
|
{
|
||||||
orgId: org.orgId,
|
orgId: org.orgId,
|
||||||
userId: userId!,
|
userId: userId!,
|
||||||
|
roleId: org.roleId,
|
||||||
autoProvisioned: true,
|
autoProvisioned: true,
|
||||||
},
|
},
|
||||||
org.roleId,
|
|
||||||
trx
|
trx
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -532,16 +532,6 @@ authenticated.post(
|
|||||||
user.addUserRole
|
user.addUserRole
|
||||||
);
|
);
|
||||||
|
|
||||||
authenticated.delete(
|
|
||||||
"/role/:roleId/remove/:userId",
|
|
||||||
verifyApiKeyRoleAccess,
|
|
||||||
verifyApiKeyUserAccess,
|
|
||||||
verifyLimits,
|
|
||||||
verifyApiKeyHasAction(ActionsEnum.removeUserRole),
|
|
||||||
logActionAudit(ActionsEnum.removeUserRole),
|
|
||||||
user.removeUserRole
|
|
||||||
);
|
|
||||||
|
|
||||||
authenticated.post(
|
authenticated.post(
|
||||||
"/resource/:resourceId/roles",
|
"/resource/:resourceId/roles",
|
||||||
verifyApiKeyResourceAccess,
|
verifyApiKeyResourceAccess,
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ export async function createNewt(
|
|||||||
|
|
||||||
const { newtId, secret } = parsedBody.data;
|
const { newtId, secret } = parsedBody.data;
|
||||||
|
|
||||||
if (req.user && (!req.userOrgRoleIds || req.userOrgRoleIds.length === 0)) {
|
if (req.user && !req.userOrgRoleId) {
|
||||||
return next(
|
return next(
|
||||||
createHttpError(HttpCode.FORBIDDEN, "User does not have a role")
|
createHttpError(HttpCode.FORBIDDEN, "User does not have a role")
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ export async function createNewt(
|
|||||||
|
|
||||||
const { newtId, secret } = parsedBody.data;
|
const { newtId, secret } = parsedBody.data;
|
||||||
|
|
||||||
if (req.user && (!req.userOrgRoleIds || req.userOrgRoleIds.length === 0)) {
|
if (req.user && !req.userOrgRoleId) {
|
||||||
return next(
|
return next(
|
||||||
createHttpError(HttpCode.FORBIDDEN, "User does not have a role")
|
createHttpError(HttpCode.FORBIDDEN, "User does not have a role")
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { db, idp, idpOidcConfig } from "@server/db";
|
import { db, idp, idpOidcConfig } from "@server/db";
|
||||||
import { roles, userOrgRoles, userOrgs, users } from "@server/db";
|
import { roles, userOrgs, users } from "@server/db";
|
||||||
import { and, eq } from "drizzle-orm";
|
import { and, eq } from "drizzle-orm";
|
||||||
import response from "@server/lib/response";
|
import response from "@server/lib/response";
|
||||||
import HttpCode from "@server/types/HttpCode";
|
import HttpCode from "@server/types/HttpCode";
|
||||||
@@ -14,7 +14,7 @@ import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
|
|||||||
import { CheckOrgAccessPolicyResult } from "@server/lib/checkOrgAccessPolicy";
|
import { CheckOrgAccessPolicyResult } from "@server/lib/checkOrgAccessPolicy";
|
||||||
|
|
||||||
async function queryUser(orgId: string, userId: string) {
|
async function queryUser(orgId: string, userId: string) {
|
||||||
const [userRow] = await db
|
const [user] = await db
|
||||||
.select({
|
.select({
|
||||||
orgId: userOrgs.orgId,
|
orgId: userOrgs.orgId,
|
||||||
userId: users.userId,
|
userId: users.userId,
|
||||||
@@ -22,7 +22,10 @@ async function queryUser(orgId: string, userId: string) {
|
|||||||
username: users.username,
|
username: users.username,
|
||||||
name: users.name,
|
name: users.name,
|
||||||
type: users.type,
|
type: users.type,
|
||||||
|
roleId: userOrgs.roleId,
|
||||||
|
roleName: roles.name,
|
||||||
isOwner: userOrgs.isOwner,
|
isOwner: userOrgs.isOwner,
|
||||||
|
isAdmin: roles.isAdmin,
|
||||||
twoFactorEnabled: users.twoFactorEnabled,
|
twoFactorEnabled: users.twoFactorEnabled,
|
||||||
autoProvisioned: userOrgs.autoProvisioned,
|
autoProvisioned: userOrgs.autoProvisioned,
|
||||||
idpId: users.idpId,
|
idpId: users.idpId,
|
||||||
@@ -32,40 +35,13 @@ async function queryUser(orgId: string, userId: string) {
|
|||||||
idpAutoProvision: idp.autoProvision
|
idpAutoProvision: idp.autoProvision
|
||||||
})
|
})
|
||||||
.from(userOrgs)
|
.from(userOrgs)
|
||||||
|
.leftJoin(roles, eq(userOrgs.roleId, roles.roleId))
|
||||||
.leftJoin(users, eq(userOrgs.userId, users.userId))
|
.leftJoin(users, eq(userOrgs.userId, users.userId))
|
||||||
.leftJoin(idp, eq(users.idpId, idp.idpId))
|
.leftJoin(idp, eq(users.idpId, idp.idpId))
|
||||||
.leftJoin(idpOidcConfig, eq(idp.idpId, idpOidcConfig.idpId))
|
.leftJoin(idpOidcConfig, eq(idp.idpId, idpOidcConfig.idpId))
|
||||||
.where(and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, orgId)))
|
.where(and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, orgId)))
|
||||||
.limit(1);
|
.limit(1);
|
||||||
|
return user;
|
||||||
if (!userRow) return undefined;
|
|
||||||
|
|
||||||
const roleRows = await db
|
|
||||||
.select({
|
|
||||||
roleId: userOrgRoles.roleId,
|
|
||||||
roleName: roles.name,
|
|
||||||
isAdmin: roles.isAdmin
|
|
||||||
})
|
|
||||||
.from(userOrgRoles)
|
|
||||||
.leftJoin(roles, eq(userOrgRoles.roleId, roles.roleId))
|
|
||||||
.where(
|
|
||||||
and(
|
|
||||||
eq(userOrgRoles.userId, userId),
|
|
||||||
eq(userOrgRoles.orgId, orgId)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
const isAdmin = roleRows.some((r) => r.isAdmin);
|
|
||||||
|
|
||||||
return {
|
|
||||||
...userRow,
|
|
||||||
isAdmin,
|
|
||||||
roleIds: roleRows.map((r) => r.roleId),
|
|
||||||
roles: roleRows.map((r) => ({
|
|
||||||
roleId: r.roleId,
|
|
||||||
name: r.roleName ?? ""
|
|
||||||
}))
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export type CheckOrgUserAccessResponse = CheckOrgAccessPolicyResult;
|
export type CheckOrgUserAccessResponse = CheckOrgAccessPolicyResult;
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import {
|
|||||||
orgs,
|
orgs,
|
||||||
roleActions,
|
roleActions,
|
||||||
roles,
|
roles,
|
||||||
userOrgRoles,
|
|
||||||
userOrgs,
|
userOrgs,
|
||||||
users,
|
users,
|
||||||
actions
|
actions
|
||||||
@@ -313,13 +312,9 @@ export async function createOrg(
|
|||||||
await trx.insert(userOrgs).values({
|
await trx.insert(userOrgs).values({
|
||||||
userId: req.user!.userId,
|
userId: req.user!.userId,
|
||||||
orgId: newOrg[0].orgId,
|
orgId: newOrg[0].orgId,
|
||||||
|
roleId: roleId,
|
||||||
isOwner: true
|
isOwner: true
|
||||||
});
|
});
|
||||||
await trx.insert(userOrgRoles).values({
|
|
||||||
userId: req.user!.userId,
|
|
||||||
orgId: newOrg[0].orgId,
|
|
||||||
roleId
|
|
||||||
});
|
|
||||||
ownerUserId = req.user!.userId;
|
ownerUserId = req.user!.userId;
|
||||||
} else {
|
} else {
|
||||||
// if org created by root api key, set the server admin as the owner
|
// if org created by root api key, set the server admin as the owner
|
||||||
@@ -337,13 +332,9 @@ export async function createOrg(
|
|||||||
await trx.insert(userOrgs).values({
|
await trx.insert(userOrgs).values({
|
||||||
userId: serverAdmin.userId,
|
userId: serverAdmin.userId,
|
||||||
orgId: newOrg[0].orgId,
|
orgId: newOrg[0].orgId,
|
||||||
|
roleId: roleId,
|
||||||
isOwner: true
|
isOwner: true
|
||||||
});
|
});
|
||||||
await trx.insert(userOrgRoles).values({
|
|
||||||
userId: serverAdmin.userId,
|
|
||||||
orgId: newOrg[0].orgId,
|
|
||||||
roleId
|
|
||||||
});
|
|
||||||
ownerUserId = serverAdmin.userId;
|
ownerUserId = serverAdmin.userId;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -117,26 +117,20 @@ export async function getOrgOverview(
|
|||||||
.from(userOrgs)
|
.from(userOrgs)
|
||||||
.where(eq(userOrgs.orgId, orgId));
|
.where(eq(userOrgs.orgId, orgId));
|
||||||
|
|
||||||
const roleIds = req.userOrgRoleIds ?? [];
|
const [role] = await db
|
||||||
const roleRows =
|
.select()
|
||||||
roleIds.length > 0
|
.from(roles)
|
||||||
? await db
|
.where(eq(roles.roleId, req.userOrg.roleId));
|
||||||
.select({ name: roles.name, isAdmin: roles.isAdmin })
|
|
||||||
.from(roles)
|
|
||||||
.where(inArray(roles.roleId, roleIds))
|
|
||||||
: [];
|
|
||||||
const userRoleName = roleRows.map((r) => r.name ?? "").join(", ") ?? "";
|
|
||||||
const isAdmin = roleRows.some((r) => r.isAdmin === true);
|
|
||||||
|
|
||||||
return response<GetOrgOverviewResponse>(res, {
|
return response<GetOrgOverviewResponse>(res, {
|
||||||
data: {
|
data: {
|
||||||
orgName: org[0].name,
|
orgName: org[0].name,
|
||||||
orgId: org[0].orgId,
|
orgId: org[0].orgId,
|
||||||
userRoleName,
|
userRoleName: role.name,
|
||||||
numSites,
|
numSites,
|
||||||
numUsers,
|
numUsers,
|
||||||
numResources,
|
numResources,
|
||||||
isAdmin,
|
isAdmin: role.isAdmin || false,
|
||||||
isOwner: req.userOrg?.isOwner || false
|
isOwner: req.userOrg?.isOwner || false
|
||||||
},
|
},
|
||||||
success: true,
|
success: true,
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { db, roles } from "@server/db";
|
import { db, roles } from "@server/db";
|
||||||
import { Org, orgs, userOrgRoles, userOrgs } from "@server/db";
|
import { Org, orgs, userOrgs } from "@server/db";
|
||||||
import response from "@server/lib/response";
|
import response from "@server/lib/response";
|
||||||
import HttpCode from "@server/types/HttpCode";
|
import HttpCode from "@server/types/HttpCode";
|
||||||
import createHttpError from "http-errors";
|
import createHttpError from "http-errors";
|
||||||
@@ -82,7 +82,10 @@ export async function listUserOrgs(
|
|||||||
const { userId } = parsedParams.data;
|
const { userId } = parsedParams.data;
|
||||||
|
|
||||||
const userOrganizations = await db
|
const userOrganizations = await db
|
||||||
.select({ orgId: userOrgs.orgId })
|
.select({
|
||||||
|
orgId: userOrgs.orgId,
|
||||||
|
roleId: userOrgs.roleId
|
||||||
|
})
|
||||||
.from(userOrgs)
|
.from(userOrgs)
|
||||||
.where(eq(userOrgs.userId, userId));
|
.where(eq(userOrgs.userId, userId));
|
||||||
|
|
||||||
@@ -113,27 +116,10 @@ export async function listUserOrgs(
|
|||||||
userOrgs,
|
userOrgs,
|
||||||
and(eq(userOrgs.orgId, orgs.orgId), eq(userOrgs.userId, userId))
|
and(eq(userOrgs.orgId, orgs.orgId), eq(userOrgs.userId, userId))
|
||||||
)
|
)
|
||||||
|
.leftJoin(roles, eq(userOrgs.roleId, roles.roleId))
|
||||||
.limit(limit)
|
.limit(limit)
|
||||||
.offset(offset);
|
.offset(offset);
|
||||||
|
|
||||||
const roleRows = await db
|
|
||||||
.select({
|
|
||||||
orgId: userOrgRoles.orgId,
|
|
||||||
isAdmin: roles.isAdmin
|
|
||||||
})
|
|
||||||
.from(userOrgRoles)
|
|
||||||
.leftJoin(roles, eq(userOrgRoles.roleId, roles.roleId))
|
|
||||||
.where(
|
|
||||||
and(
|
|
||||||
eq(userOrgRoles.userId, userId),
|
|
||||||
inArray(userOrgRoles.orgId, userOrgIds)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
const orgHasAdmin = new Set(
|
|
||||||
roleRows.filter((r) => r.isAdmin).map((r) => r.orgId)
|
|
||||||
);
|
|
||||||
|
|
||||||
const totalCountResult = await db
|
const totalCountResult = await db
|
||||||
.select({ count: sql<number>`cast(count(*) as integer)` })
|
.select({ count: sql<number>`cast(count(*) as integer)` })
|
||||||
.from(orgs)
|
.from(orgs)
|
||||||
@@ -147,8 +133,8 @@ export async function listUserOrgs(
|
|||||||
if (val.userOrgs && val.userOrgs.isOwner) {
|
if (val.userOrgs && val.userOrgs.isOwner) {
|
||||||
res.isOwner = val.userOrgs.isOwner;
|
res.isOwner = val.userOrgs.isOwner;
|
||||||
}
|
}
|
||||||
if (val.orgs && orgHasAdmin.has(val.orgs.orgId)) {
|
if (val.roles && val.roles.isAdmin) {
|
||||||
res.isAdmin = true;
|
res.isAdmin = val.roles.isAdmin;
|
||||||
}
|
}
|
||||||
if (val.userOrgs?.isOwner && val.orgs?.isBillingOrg) {
|
if (val.userOrgs?.isOwner && val.orgs?.isBillingOrg) {
|
||||||
res.isPrimaryOrg = val.orgs.isBillingOrg;
|
res.isPrimaryOrg = val.orgs.isBillingOrg;
|
||||||
|
|||||||
@@ -112,7 +112,7 @@ export async function createResource(
|
|||||||
|
|
||||||
const { orgId } = parsedParams.data;
|
const { orgId } = parsedParams.data;
|
||||||
|
|
||||||
if (req.user && (!req.userOrgRoleIds || req.userOrgRoleIds.length === 0)) {
|
if (req.user && !req.userOrgRoleId) {
|
||||||
return next(
|
return next(
|
||||||
createHttpError(HttpCode.FORBIDDEN, "User does not have a role")
|
createHttpError(HttpCode.FORBIDDEN, "User does not have a role")
|
||||||
);
|
);
|
||||||
@@ -278,7 +278,7 @@ async function createHttpResource(
|
|||||||
resourceId: newResource[0].resourceId
|
resourceId: newResource[0].resourceId
|
||||||
});
|
});
|
||||||
|
|
||||||
if (req.user && !req.userOrgRoleIds?.includes(adminRole[0].roleId)) {
|
if (req.user && req.userOrgRoleId != adminRole[0].roleId) {
|
||||||
// make sure the user can access the resource
|
// make sure the user can access the resource
|
||||||
await trx.insert(userResources).values({
|
await trx.insert(userResources).values({
|
||||||
userId: req.user?.userId!,
|
userId: req.user?.userId!,
|
||||||
@@ -371,7 +371,7 @@ async function createRawResource(
|
|||||||
resourceId: newResource[0].resourceId
|
resourceId: newResource[0].resourceId
|
||||||
});
|
});
|
||||||
|
|
||||||
if (req.user && !req.userOrgRoleIds?.includes(adminRole[0].roleId)) {
|
if (req.user && req.userOrgRoleId != adminRole[0].roleId) {
|
||||||
// make sure the user can access the resource
|
// make sure the user can access the resource
|
||||||
await trx.insert(userResources).values({
|
await trx.insert(userResources).values({
|
||||||
userId: req.user?.userId!,
|
userId: req.user?.userId!,
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import {
|
|||||||
resources,
|
resources,
|
||||||
userResources,
|
userResources,
|
||||||
roleResources,
|
roleResources,
|
||||||
userOrgRoles,
|
|
||||||
userOrgs,
|
userOrgs,
|
||||||
resourcePassword,
|
resourcePassword,
|
||||||
resourcePincode,
|
resourcePincode,
|
||||||
@@ -33,29 +32,22 @@ export async function getUserResources(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check user is in organization and get their role IDs
|
// First get the user's role in the organization
|
||||||
const [userOrg] = await db
|
const userOrgResult = await db
|
||||||
.select()
|
.select({
|
||||||
|
roleId: userOrgs.roleId
|
||||||
|
})
|
||||||
.from(userOrgs)
|
.from(userOrgs)
|
||||||
.where(and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, orgId)))
|
.where(and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, orgId)))
|
||||||
.limit(1);
|
.limit(1);
|
||||||
|
|
||||||
if (!userOrg) {
|
if (userOrgResult.length === 0) {
|
||||||
return next(
|
return next(
|
||||||
createHttpError(HttpCode.FORBIDDEN, "User not in organization")
|
createHttpError(HttpCode.FORBIDDEN, "User not in organization")
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const userRoleIds = await db
|
const userRoleId = userOrgResult[0].roleId;
|
||||||
.select({ roleId: userOrgRoles.roleId })
|
|
||||||
.from(userOrgRoles)
|
|
||||||
.where(
|
|
||||||
and(
|
|
||||||
eq(userOrgRoles.userId, userId),
|
|
||||||
eq(userOrgRoles.orgId, orgId)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
.then((rows) => rows.map((r) => r.roleId));
|
|
||||||
|
|
||||||
// Get resources accessible through direct assignment or role assignment
|
// Get resources accessible through direct assignment or role assignment
|
||||||
const directResourcesQuery = db
|
const directResourcesQuery = db
|
||||||
@@ -63,28 +55,20 @@ export async function getUserResources(
|
|||||||
.from(userResources)
|
.from(userResources)
|
||||||
.where(eq(userResources.userId, userId));
|
.where(eq(userResources.userId, userId));
|
||||||
|
|
||||||
const roleResourcesQuery =
|
const roleResourcesQuery = db
|
||||||
userRoleIds.length > 0
|
.select({ resourceId: roleResources.resourceId })
|
||||||
? db
|
.from(roleResources)
|
||||||
.select({ resourceId: roleResources.resourceId })
|
.where(eq(roleResources.roleId, userRoleId));
|
||||||
.from(roleResources)
|
|
||||||
.where(inArray(roleResources.roleId, userRoleIds))
|
|
||||||
: Promise.resolve([]);
|
|
||||||
|
|
||||||
const directSiteResourcesQuery = db
|
const directSiteResourcesQuery = db
|
||||||
.select({ siteResourceId: userSiteResources.siteResourceId })
|
.select({ siteResourceId: userSiteResources.siteResourceId })
|
||||||
.from(userSiteResources)
|
.from(userSiteResources)
|
||||||
.where(eq(userSiteResources.userId, userId));
|
.where(eq(userSiteResources.userId, userId));
|
||||||
|
|
||||||
const roleSiteResourcesQuery =
|
const roleSiteResourcesQuery = db
|
||||||
userRoleIds.length > 0
|
.select({ siteResourceId: roleSiteResources.siteResourceId })
|
||||||
? db
|
.from(roleSiteResources)
|
||||||
.select({
|
.where(eq(roleSiteResources.roleId, userRoleId));
|
||||||
siteResourceId: roleSiteResources.siteResourceId
|
|
||||||
})
|
|
||||||
.from(roleSiteResources)
|
|
||||||
.where(inArray(roleSiteResources.roleId, userRoleIds))
|
|
||||||
: Promise.resolve([]);
|
|
||||||
|
|
||||||
const [directResources, roleResourceResults, directSiteResourceResults, roleSiteResourceResults] = await Promise.all([
|
const [directResources, roleResourceResults, directSiteResourceResults, roleSiteResourceResults] = await Promise.all([
|
||||||
directResourcesQuery,
|
directResourcesQuery,
|
||||||
|
|||||||
@@ -276,7 +276,7 @@ export async function listResources(
|
|||||||
.where(
|
.where(
|
||||||
or(
|
or(
|
||||||
eq(userResources.userId, req.user!.userId),
|
eq(userResources.userId, req.user!.userId),
|
||||||
inArray(roleResources.roleId, req.userOrgRoleIds!)
|
eq(roleResources.roleId, req.userOrgRoleId!)
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { db } from "@server/db";
|
import { db } from "@server/db";
|
||||||
import { roles, userOrgRoles } from "@server/db";
|
import { roles, userOrgs } from "@server/db";
|
||||||
import { eq } from "drizzle-orm";
|
import { eq } from "drizzle-orm";
|
||||||
import response from "@server/lib/response";
|
import response from "@server/lib/response";
|
||||||
import HttpCode from "@server/types/HttpCode";
|
import HttpCode from "@server/types/HttpCode";
|
||||||
@@ -114,11 +114,11 @@ export async function deleteRole(
|
|||||||
}
|
}
|
||||||
|
|
||||||
await db.transaction(async (trx) => {
|
await db.transaction(async (trx) => {
|
||||||
// move all users from userOrgRoles with roleId to newRoleId
|
// move all users from the userOrgs table with roleId to newRoleId
|
||||||
await trx
|
await trx
|
||||||
.update(userOrgRoles)
|
.update(userOrgs)
|
||||||
.set({ roleId: newRoleId })
|
.set({ roleId: newRoleId })
|
||||||
.where(eq(userOrgRoles.roleId, roleId));
|
.where(eq(userOrgs.roleId, roleId));
|
||||||
|
|
||||||
// delete the old role
|
// delete the old role
|
||||||
await trx.delete(roles).where(eq(roles.roleId, roleId));
|
await trx.delete(roles).where(eq(roles.roleId, roleId));
|
||||||
|
|||||||
@@ -111,7 +111,7 @@ export async function createSite(
|
|||||||
|
|
||||||
const { orgId } = parsedParams.data;
|
const { orgId } = parsedParams.data;
|
||||||
|
|
||||||
if (req.user && (!req.userOrgRoleIds || req.userOrgRoleIds.length === 0)) {
|
if (req.user && !req.userOrgRoleId) {
|
||||||
return next(
|
return next(
|
||||||
createHttpError(HttpCode.FORBIDDEN, "User does not have a role")
|
createHttpError(HttpCode.FORBIDDEN, "User does not have a role")
|
||||||
);
|
);
|
||||||
@@ -399,7 +399,7 @@ export async function createSite(
|
|||||||
siteId: newSite.siteId
|
siteId: newSite.siteId
|
||||||
});
|
});
|
||||||
|
|
||||||
if (req.user && !req.userOrgRoleIds?.includes(adminRole[0].roleId)) {
|
if (req.user && req.userOrgRoleId != adminRole[0].roleId) {
|
||||||
// make sure the user can access the site
|
// make sure the user can access the site
|
||||||
trx.insert(userSites).values({
|
trx.insert(userSites).values({
|
||||||
userId: req.user?.userId!,
|
userId: req.user?.userId!,
|
||||||
|
|||||||
@@ -235,7 +235,7 @@ export async function listSites(
|
|||||||
.where(
|
.where(
|
||||||
or(
|
or(
|
||||||
eq(userSites.userId, req.user!.userId),
|
eq(userSites.userId, req.user!.userId),
|
||||||
inArray(roleSites.roleId, req.userOrgRoleIds!)
|
eq(roleSites.roleId, req.userOrgRoleId!)
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -165,9 +165,9 @@ export async function acceptInvite(
|
|||||||
org,
|
org,
|
||||||
{
|
{
|
||||||
userId: existingUser[0].userId,
|
userId: existingUser[0].userId,
|
||||||
orgId: existingInvite.orgId
|
orgId: existingInvite.orgId,
|
||||||
|
roleId: existingInvite.roleId
|
||||||
},
|
},
|
||||||
existingInvite.roleId,
|
|
||||||
trx
|
trx
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { clients, db } from "@server/db";
|
import { clients, db, UserOrg } from "@server/db";
|
||||||
import { userOrgRoles, userOrgs, roles } from "@server/db";
|
import { userOrgs, roles } from "@server/db";
|
||||||
import { eq, and } from "drizzle-orm";
|
import { eq, and } from "drizzle-orm";
|
||||||
import response from "@server/lib/response";
|
import response from "@server/lib/response";
|
||||||
import HttpCode from "@server/types/HttpCode";
|
import HttpCode from "@server/types/HttpCode";
|
||||||
@@ -111,23 +111,20 @@ export async function addUserRole(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let newUserRole: { userId: string; orgId: string; roleId: number } | null =
|
let newUserRole: UserOrg | null = null;
|
||||||
null;
|
|
||||||
await db.transaction(async (trx) => {
|
await db.transaction(async (trx) => {
|
||||||
const inserted = await trx
|
[newUserRole] = await trx
|
||||||
.insert(userOrgRoles)
|
.update(userOrgs)
|
||||||
.values({
|
.set({ roleId })
|
||||||
userId,
|
.where(
|
||||||
orgId: role.orgId,
|
and(
|
||||||
roleId
|
eq(userOrgs.userId, userId),
|
||||||
})
|
eq(userOrgs.orgId, role.orgId)
|
||||||
.onConflictDoNothing()
|
)
|
||||||
|
)
|
||||||
.returning();
|
.returning();
|
||||||
|
|
||||||
if (inserted.length > 0) {
|
// get the client associated with this user in this org
|
||||||
newUserRole = inserted[0];
|
|
||||||
}
|
|
||||||
|
|
||||||
const orgClients = await trx
|
const orgClients = await trx
|
||||||
.select()
|
.select()
|
||||||
.from(clients)
|
.from(clients)
|
||||||
@@ -136,15 +133,17 @@ export async function addUserRole(
|
|||||||
eq(clients.userId, userId),
|
eq(clients.userId, userId),
|
||||||
eq(clients.orgId, role.orgId)
|
eq(clients.orgId, role.orgId)
|
||||||
)
|
)
|
||||||
);
|
)
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
for (const orgClient of orgClients) {
|
for (const orgClient of orgClients) {
|
||||||
|
// we just changed the user's role, so we need to rebuild client associations and what they have access to
|
||||||
await rebuildClientAssociationsFromClient(orgClient, trx);
|
await rebuildClientAssociationsFromClient(orgClient, trx);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return response(res, {
|
return response(res, {
|
||||||
data: newUserRole ?? { userId, orgId: role.orgId, roleId },
|
data: newUserRole,
|
||||||
success: true,
|
success: true,
|
||||||
error: false,
|
error: false,
|
||||||
message: "Role added to user successfully",
|
message: "Role added to user successfully",
|
||||||
|
|||||||
@@ -221,16 +221,12 @@ export async function createOrgUser(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
await assignUserToOrg(
|
await assignUserToOrg(org, {
|
||||||
org,
|
orgId,
|
||||||
{
|
userId: existingUser.userId,
|
||||||
orgId,
|
roleId: role.roleId,
|
||||||
userId: existingUser.userId,
|
autoProvisioned: false
|
||||||
autoProvisioned: false,
|
}, trx);
|
||||||
},
|
|
||||||
role.roleId,
|
|
||||||
trx
|
|
||||||
);
|
|
||||||
} else {
|
} else {
|
||||||
userId = generateId(15);
|
userId = generateId(15);
|
||||||
|
|
||||||
@@ -248,16 +244,12 @@ export async function createOrgUser(
|
|||||||
})
|
})
|
||||||
.returning();
|
.returning();
|
||||||
|
|
||||||
await assignUserToOrg(
|
await assignUserToOrg(org, {
|
||||||
org,
|
orgId,
|
||||||
{
|
userId: newUser.userId,
|
||||||
orgId,
|
roleId: role.roleId,
|
||||||
userId: newUser.userId,
|
autoProvisioned: false
|
||||||
autoProvisioned: false,
|
}, trx);
|
||||||
},
|
|
||||||
role.roleId,
|
|
||||||
trx
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await calculateUserClientsForOrgs(userId, trx);
|
await calculateUserClientsForOrgs(userId, trx);
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { db, idp, idpOidcConfig } from "@server/db";
|
import { db, idp, idpOidcConfig } from "@server/db";
|
||||||
import { roles, userOrgRoles, userOrgs, users } from "@server/db";
|
import { roles, userOrgs, users } from "@server/db";
|
||||||
import { and, eq } from "drizzle-orm";
|
import { and, eq } from "drizzle-orm";
|
||||||
import response from "@server/lib/response";
|
import response from "@server/lib/response";
|
||||||
import HttpCode from "@server/types/HttpCode";
|
import HttpCode from "@server/types/HttpCode";
|
||||||
@@ -12,7 +12,7 @@ import { ActionsEnum, checkUserActionPermission } from "@server/auth/actions";
|
|||||||
import { OpenAPITags, registry } from "@server/openApi";
|
import { OpenAPITags, registry } from "@server/openApi";
|
||||||
|
|
||||||
async function queryUser(orgId: string, userId: string) {
|
async function queryUser(orgId: string, userId: string) {
|
||||||
const [userRow] = await db
|
const [user] = await db
|
||||||
.select({
|
.select({
|
||||||
orgId: userOrgs.orgId,
|
orgId: userOrgs.orgId,
|
||||||
userId: users.userId,
|
userId: users.userId,
|
||||||
@@ -20,7 +20,10 @@ async function queryUser(orgId: string, userId: string) {
|
|||||||
username: users.username,
|
username: users.username,
|
||||||
name: users.name,
|
name: users.name,
|
||||||
type: users.type,
|
type: users.type,
|
||||||
|
roleId: userOrgs.roleId,
|
||||||
|
roleName: roles.name,
|
||||||
isOwner: userOrgs.isOwner,
|
isOwner: userOrgs.isOwner,
|
||||||
|
isAdmin: roles.isAdmin,
|
||||||
twoFactorEnabled: users.twoFactorEnabled,
|
twoFactorEnabled: users.twoFactorEnabled,
|
||||||
autoProvisioned: userOrgs.autoProvisioned,
|
autoProvisioned: userOrgs.autoProvisioned,
|
||||||
idpId: users.idpId,
|
idpId: users.idpId,
|
||||||
@@ -30,40 +33,13 @@ async function queryUser(orgId: string, userId: string) {
|
|||||||
idpAutoProvision: idp.autoProvision
|
idpAutoProvision: idp.autoProvision
|
||||||
})
|
})
|
||||||
.from(userOrgs)
|
.from(userOrgs)
|
||||||
|
.leftJoin(roles, eq(userOrgs.roleId, roles.roleId))
|
||||||
.leftJoin(users, eq(userOrgs.userId, users.userId))
|
.leftJoin(users, eq(userOrgs.userId, users.userId))
|
||||||
.leftJoin(idp, eq(users.idpId, idp.idpId))
|
.leftJoin(idp, eq(users.idpId, idp.idpId))
|
||||||
.leftJoin(idpOidcConfig, eq(idp.idpId, idpOidcConfig.idpId))
|
.leftJoin(idpOidcConfig, eq(idp.idpId, idpOidcConfig.idpId))
|
||||||
.where(and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, orgId)))
|
.where(and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, orgId)))
|
||||||
.limit(1);
|
.limit(1);
|
||||||
|
return user;
|
||||||
if (!userRow) return undefined;
|
|
||||||
|
|
||||||
const roleRows = await db
|
|
||||||
.select({
|
|
||||||
roleId: userOrgRoles.roleId,
|
|
||||||
roleName: roles.name,
|
|
||||||
isAdmin: roles.isAdmin
|
|
||||||
})
|
|
||||||
.from(userOrgRoles)
|
|
||||||
.leftJoin(roles, eq(userOrgRoles.roleId, roles.roleId))
|
|
||||||
.where(
|
|
||||||
and(
|
|
||||||
eq(userOrgRoles.userId, userId),
|
|
||||||
eq(userOrgRoles.orgId, orgId)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
const isAdmin = roleRows.some((r) => r.isAdmin);
|
|
||||||
|
|
||||||
return {
|
|
||||||
...userRow,
|
|
||||||
isAdmin,
|
|
||||||
roleIds: roleRows.map((r) => r.roleId),
|
|
||||||
roles: roleRows.map((r) => ({
|
|
||||||
roleId: r.roleId,
|
|
||||||
name: r.roleName ?? ""
|
|
||||||
}))
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export type GetOrgUserResponse = NonNullable<
|
export type GetOrgUserResponse = NonNullable<
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ export * from "./getUser";
|
|||||||
export * from "./removeUserOrg";
|
export * from "./removeUserOrg";
|
||||||
export * from "./listUsers";
|
export * from "./listUsers";
|
||||||
export * from "./addUserRole";
|
export * from "./addUserRole";
|
||||||
export * from "./removeUserRole";
|
|
||||||
export * from "./inviteUser";
|
export * from "./inviteUser";
|
||||||
export * from "./acceptInvite";
|
export * from "./acceptInvite";
|
||||||
export * from "./getOrgUser";
|
export * from "./getOrgUser";
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { db, idpOidcConfig } from "@server/db";
|
import { db, idpOidcConfig } from "@server/db";
|
||||||
import { idp, roles, userOrgRoles, userOrgs, users } from "@server/db";
|
import { idp, roles, userOrgs, users } from "@server/db";
|
||||||
import response from "@server/lib/response";
|
import response from "@server/lib/response";
|
||||||
import HttpCode from "@server/types/HttpCode";
|
import HttpCode from "@server/types/HttpCode";
|
||||||
import createHttpError from "http-errors";
|
import createHttpError from "http-errors";
|
||||||
import { sql } from "drizzle-orm";
|
import { and, sql } from "drizzle-orm";
|
||||||
import logger from "@server/logger";
|
import logger from "@server/logger";
|
||||||
import { fromZodError } from "zod-validation-error";
|
import { fromZodError } from "zod-validation-error";
|
||||||
import { OpenAPITags, registry } from "@server/openApi";
|
import { OpenAPITags, registry } from "@server/openApi";
|
||||||
@@ -31,7 +31,7 @@ const listUsersSchema = z.strictObject({
|
|||||||
});
|
});
|
||||||
|
|
||||||
async function queryUsers(orgId: string, limit: number, offset: number) {
|
async function queryUsers(orgId: string, limit: number, offset: number) {
|
||||||
const rows = await db
|
return await db
|
||||||
.select({
|
.select({
|
||||||
id: users.userId,
|
id: users.userId,
|
||||||
email: users.email,
|
email: users.email,
|
||||||
@@ -41,6 +41,8 @@ async function queryUsers(orgId: string, limit: number, offset: number) {
|
|||||||
username: users.username,
|
username: users.username,
|
||||||
name: users.name,
|
name: users.name,
|
||||||
type: users.type,
|
type: users.type,
|
||||||
|
roleId: userOrgs.roleId,
|
||||||
|
roleName: roles.name,
|
||||||
isOwner: userOrgs.isOwner,
|
isOwner: userOrgs.isOwner,
|
||||||
idpName: idp.name,
|
idpName: idp.name,
|
||||||
idpId: users.idpId,
|
idpId: users.idpId,
|
||||||
@@ -50,39 +52,12 @@ async function queryUsers(orgId: string, limit: number, offset: number) {
|
|||||||
})
|
})
|
||||||
.from(users)
|
.from(users)
|
||||||
.leftJoin(userOrgs, eq(users.userId, userOrgs.userId))
|
.leftJoin(userOrgs, eq(users.userId, userOrgs.userId))
|
||||||
|
.leftJoin(roles, eq(userOrgs.roleId, roles.roleId))
|
||||||
.leftJoin(idp, eq(users.idpId, idp.idpId))
|
.leftJoin(idp, eq(users.idpId, idp.idpId))
|
||||||
.leftJoin(idpOidcConfig, eq(idpOidcConfig.idpId, idp.idpId))
|
.leftJoin(idpOidcConfig, eq(idpOidcConfig.idpId, idp.idpId))
|
||||||
.where(eq(userOrgs.orgId, orgId))
|
.where(eq(userOrgs.orgId, orgId))
|
||||||
.limit(limit)
|
.limit(limit)
|
||||||
.offset(offset);
|
.offset(offset);
|
||||||
|
|
||||||
const roleRows = await db
|
|
||||||
.select({
|
|
||||||
userId: userOrgRoles.userId,
|
|
||||||
roleId: userOrgRoles.roleId,
|
|
||||||
roleName: roles.name
|
|
||||||
})
|
|
||||||
.from(userOrgRoles)
|
|
||||||
.leftJoin(roles, eq(userOrgRoles.roleId, roles.roleId))
|
|
||||||
.where(eq(userOrgRoles.orgId, orgId));
|
|
||||||
|
|
||||||
const rolesByUser = new Map<
|
|
||||||
string,
|
|
||||||
{ roleId: number; roleName: string }[]
|
|
||||||
>();
|
|
||||||
for (const r of roleRows) {
|
|
||||||
const list = rolesByUser.get(r.userId) ?? [];
|
|
||||||
list.push({ roleId: r.roleId, roleName: r.roleName ?? "" });
|
|
||||||
rolesByUser.set(r.userId, list);
|
|
||||||
}
|
|
||||||
|
|
||||||
return rows.map((row) => {
|
|
||||||
const userRoles = rolesByUser.get(row.id) ?? [];
|
|
||||||
return {
|
|
||||||
...row,
|
|
||||||
roles: userRoles
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ListUsersResponse = {
|
export type ListUsersResponse = {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Request, Response, NextFunction } from "express";
|
import { Request, Response, NextFunction } from "express";
|
||||||
import { db, Olm, olms, orgs, userOrgRoles, userOrgs } from "@server/db";
|
import { db, Olm, olms, orgs, userOrgs } from "@server/db";
|
||||||
import { idp, users } from "@server/db";
|
import { idp, users } from "@server/db";
|
||||||
import { and, eq } from "drizzle-orm";
|
import { and, eq } from "drizzle-orm";
|
||||||
import response from "@server/lib/response";
|
import response from "@server/lib/response";
|
||||||
@@ -84,31 +84,16 @@ export async function myDevice(
|
|||||||
.from(olms)
|
.from(olms)
|
||||||
.where(and(eq(olms.userId, userId), eq(olms.olmId, olmId)));
|
.where(and(eq(olms.userId, userId), eq(olms.olmId, olmId)));
|
||||||
|
|
||||||
const userOrgRows = await db
|
const userOrganizations = await db
|
||||||
.select({
|
.select({
|
||||||
orgId: userOrgs.orgId,
|
orgId: userOrgs.orgId,
|
||||||
orgName: orgs.name
|
orgName: orgs.name,
|
||||||
|
roleId: userOrgs.roleId
|
||||||
})
|
})
|
||||||
.from(userOrgs)
|
.from(userOrgs)
|
||||||
.where(eq(userOrgs.userId, userId))
|
.where(eq(userOrgs.userId, userId))
|
||||||
.innerJoin(orgs, eq(userOrgs.orgId, orgs.orgId));
|
.innerJoin(orgs, eq(userOrgs.orgId, orgs.orgId));
|
||||||
|
|
||||||
const roleRows = await db
|
|
||||||
.select({
|
|
||||||
orgId: userOrgRoles.orgId,
|
|
||||||
roleId: userOrgRoles.roleId
|
|
||||||
})
|
|
||||||
.from(userOrgRoles)
|
|
||||||
.where(eq(userOrgRoles.userId, userId));
|
|
||||||
|
|
||||||
const roleByOrg = new Map(
|
|
||||||
roleRows.map((r) => [r.orgId, r.roleId])
|
|
||||||
);
|
|
||||||
const userOrganizations = userOrgRows.map((row) => ({
|
|
||||||
...row,
|
|
||||||
roleId: roleByOrg.get(row.orgId) ?? 0
|
|
||||||
}));
|
|
||||||
|
|
||||||
return response<MyDeviceResponse>(res, {
|
return response<MyDeviceResponse>(res, {
|
||||||
data: {
|
data: {
|
||||||
user,
|
user,
|
||||||
|
|||||||
@@ -1,157 +0,0 @@
|
|||||||
import { Request, Response, NextFunction } from "express";
|
|
||||||
import { z } from "zod";
|
|
||||||
import { db } from "@server/db";
|
|
||||||
import { userOrgRoles, userOrgs, roles, clients } from "@server/db";
|
|
||||||
import { eq, and } from "drizzle-orm";
|
|
||||||
import response from "@server/lib/response";
|
|
||||||
import HttpCode from "@server/types/HttpCode";
|
|
||||||
import createHttpError from "http-errors";
|
|
||||||
import logger from "@server/logger";
|
|
||||||
import { fromError } from "zod-validation-error";
|
|
||||||
import stoi from "@server/lib/stoi";
|
|
||||||
import { OpenAPITags, registry } from "@server/openApi";
|
|
||||||
import { rebuildClientAssociationsFromClient } from "@server/lib/rebuildClientAssociations";
|
|
||||||
|
|
||||||
const removeUserRoleParamsSchema = z.strictObject({
|
|
||||||
userId: z.string(),
|
|
||||||
roleId: z.string().transform(stoi).pipe(z.number())
|
|
||||||
});
|
|
||||||
|
|
||||||
registry.registerPath({
|
|
||||||
method: "delete",
|
|
||||||
path: "/role/{roleId}/remove/{userId}",
|
|
||||||
description: "Remove a role from a user. User must have at least one role left in the org.",
|
|
||||||
tags: [OpenAPITags.Role, OpenAPITags.User],
|
|
||||||
request: {
|
|
||||||
params: removeUserRoleParamsSchema
|
|
||||||
},
|
|
||||||
responses: {}
|
|
||||||
});
|
|
||||||
|
|
||||||
export async function removeUserRole(
|
|
||||||
req: Request,
|
|
||||||
res: Response,
|
|
||||||
next: NextFunction
|
|
||||||
): Promise<any> {
|
|
||||||
try {
|
|
||||||
const parsedParams = removeUserRoleParamsSchema.safeParse(req.params);
|
|
||||||
if (!parsedParams.success) {
|
|
||||||
return next(
|
|
||||||
createHttpError(
|
|
||||||
HttpCode.BAD_REQUEST,
|
|
||||||
fromError(parsedParams.error).toString()
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const { userId, roleId } = parsedParams.data;
|
|
||||||
|
|
||||||
if (req.user && !req.userOrg) {
|
|
||||||
return next(
|
|
||||||
createHttpError(
|
|
||||||
HttpCode.FORBIDDEN,
|
|
||||||
"You do not have access to this organization"
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const [role] = await db
|
|
||||||
.select()
|
|
||||||
.from(roles)
|
|
||||||
.where(eq(roles.roleId, roleId))
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
if (!role) {
|
|
||||||
return next(
|
|
||||||
createHttpError(HttpCode.BAD_REQUEST, "Invalid role ID")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const [existingUser] = await db
|
|
||||||
.select()
|
|
||||||
.from(userOrgs)
|
|
||||||
.where(
|
|
||||||
and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, role.orgId))
|
|
||||||
)
|
|
||||||
.limit(1);
|
|
||||||
|
|
||||||
if (!existingUser) {
|
|
||||||
return next(
|
|
||||||
createHttpError(
|
|
||||||
HttpCode.NOT_FOUND,
|
|
||||||
"User not found or does not belong to the specified organization"
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (existingUser.isOwner) {
|
|
||||||
return next(
|
|
||||||
createHttpError(
|
|
||||||
HttpCode.FORBIDDEN,
|
|
||||||
"Cannot change the roles of the owner of the organization"
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const remainingRoles = await db
|
|
||||||
.select({ roleId: userOrgRoles.roleId })
|
|
||||||
.from(userOrgRoles)
|
|
||||||
.where(
|
|
||||||
and(
|
|
||||||
eq(userOrgRoles.userId, userId),
|
|
||||||
eq(userOrgRoles.orgId, role.orgId)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
if (remainingRoles.length <= 1) {
|
|
||||||
const hasThisRole = remainingRoles.some((r) => r.roleId === roleId);
|
|
||||||
if (hasThisRole) {
|
|
||||||
return next(
|
|
||||||
createHttpError(
|
|
||||||
HttpCode.FORBIDDEN,
|
|
||||||
"User must have at least one role in the organization. Remove the last role is not allowed."
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
await db.transaction(async (trx) => {
|
|
||||||
await trx
|
|
||||||
.delete(userOrgRoles)
|
|
||||||
.where(
|
|
||||||
and(
|
|
||||||
eq(userOrgRoles.userId, userId),
|
|
||||||
eq(userOrgRoles.orgId, role.orgId),
|
|
||||||
eq(userOrgRoles.roleId, roleId)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
const orgClients = await trx
|
|
||||||
.select()
|
|
||||||
.from(clients)
|
|
||||||
.where(
|
|
||||||
and(
|
|
||||||
eq(clients.userId, userId),
|
|
||||||
eq(clients.orgId, role.orgId)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
for (const orgClient of orgClients) {
|
|
||||||
await rebuildClientAssociationsFromClient(orgClient, trx);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return response(res, {
|
|
||||||
data: { userId, orgId: role.orgId, roleId },
|
|
||||||
success: true,
|
|
||||||
error: false,
|
|
||||||
message: "Role removed from user successfully",
|
|
||||||
status: HttpCode.OK
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
logger.error(error);
|
|
||||||
return next(
|
|
||||||
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -5,5 +5,5 @@ import { Session } from "@server/db";
|
|||||||
export interface AuthenticatedRequest extends Request {
|
export interface AuthenticatedRequest extends Request {
|
||||||
user: User;
|
user: User;
|
||||||
session: Session;
|
session: Session;
|
||||||
userOrgRoleIds?: number[];
|
userOrgRoleId?: number;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
FormLabel,
|
FormLabel,
|
||||||
FormMessage
|
FormMessage
|
||||||
} from "@app/components/ui/form";
|
} from "@app/components/ui/form";
|
||||||
|
import { Input } from "@app/components/ui/input";
|
||||||
import {
|
import {
|
||||||
Select,
|
Select,
|
||||||
SelectContent,
|
SelectContent,
|
||||||
@@ -18,6 +19,7 @@ import {
|
|||||||
import { Checkbox } from "@app/components/ui/checkbox";
|
import { Checkbox } from "@app/components/ui/checkbox";
|
||||||
import { toast } from "@app/hooks/useToast";
|
import { toast } from "@app/hooks/useToast";
|
||||||
import { zodResolver } from "@hookform/resolvers/zod";
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
import { InviteUserResponse } from "@server/routers/user";
|
||||||
import { AxiosResponse } from "axios";
|
import { AxiosResponse } from "axios";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { useForm } from "react-hook-form";
|
import { useForm } from "react-hook-form";
|
||||||
@@ -42,9 +44,6 @@ import { useEnvContext } from "@app/hooks/useEnvContext";
|
|||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import IdpTypeBadge from "@app/components/IdpTypeBadge";
|
import IdpTypeBadge from "@app/components/IdpTypeBadge";
|
||||||
import { UserType } from "@server/types/UserTypes";
|
import { UserType } from "@server/types/UserTypes";
|
||||||
import { Badge } from "@app/components/ui/badge";
|
|
||||||
|
|
||||||
type UserRole = { roleId: number; name: string };
|
|
||||||
|
|
||||||
export default function AccessControlsPage() {
|
export default function AccessControlsPage() {
|
||||||
const { orgUser: user } = userOrgUserContext();
|
const { orgUser: user } = userOrgUserContext();
|
||||||
@@ -55,12 +54,12 @@ export default function AccessControlsPage() {
|
|||||||
|
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [roles, setRoles] = useState<{ roleId: number; name: string }[]>([]);
|
const [roles, setRoles] = useState<{ roleId: number; name: string }[]>([]);
|
||||||
const [userRoles, setUserRoles] = useState<UserRole[]>([]);
|
|
||||||
|
|
||||||
const t = useTranslations();
|
const t = useTranslations();
|
||||||
|
|
||||||
const formSchema = z.object({
|
const formSchema = z.object({
|
||||||
username: z.string(),
|
username: z.string(),
|
||||||
|
roleId: z.string().min(1, { message: t("accessRoleSelectPlease") }),
|
||||||
autoProvisioned: z.boolean()
|
autoProvisioned: z.boolean()
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -68,17 +67,11 @@ export default function AccessControlsPage() {
|
|||||||
resolver: zodResolver(formSchema),
|
resolver: zodResolver(formSchema),
|
||||||
defaultValues: {
|
defaultValues: {
|
||||||
username: user.username!,
|
username: user.username!,
|
||||||
|
roleId: user.roleId?.toString(),
|
||||||
autoProvisioned: user.autoProvisioned || false
|
autoProvisioned: user.autoProvisioned || false
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const currentRoleIds = user.roleIds ?? [];
|
|
||||||
const currentRoles: UserRole[] = user.roles ?? [];
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
setUserRoles(currentRoles);
|
|
||||||
}, [user.userId, currentRoleIds.join(",")]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
async function fetchRoles() {
|
async function fetchRoles() {
|
||||||
const res = await api
|
const res = await api
|
||||||
@@ -101,67 +94,32 @@ export default function AccessControlsPage() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fetchRoles();
|
fetchRoles();
|
||||||
|
|
||||||
|
form.setValue("roleId", user.roleId.toString());
|
||||||
form.setValue("autoProvisioned", user.autoProvisioned || false);
|
form.setValue("autoProvisioned", user.autoProvisioned || false);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
async function handleAddRole(roleId: number) {
|
|
||||||
setLoading(true);
|
|
||||||
try {
|
|
||||||
await api.post(`/role/${roleId}/add/${user.userId}`);
|
|
||||||
toast({
|
|
||||||
variant: "default",
|
|
||||||
title: t("userSaved"),
|
|
||||||
description: t("userSavedDescription")
|
|
||||||
});
|
|
||||||
const role = roles.find((r) => r.roleId === roleId);
|
|
||||||
if (role) setUserRoles((prev) => [...prev, role]);
|
|
||||||
} catch (e) {
|
|
||||||
toast({
|
|
||||||
variant: "destructive",
|
|
||||||
title: t("accessRoleErrorAdd"),
|
|
||||||
description: formatAxiosError(
|
|
||||||
e,
|
|
||||||
t("accessRoleErrorAddDescription")
|
|
||||||
)
|
|
||||||
});
|
|
||||||
}
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function handleRemoveRole(roleId: number) {
|
|
||||||
setLoading(true);
|
|
||||||
try {
|
|
||||||
await api.delete(`/role/${roleId}/remove/${user.userId}`);
|
|
||||||
toast({
|
|
||||||
variant: "default",
|
|
||||||
title: t("userSaved"),
|
|
||||||
description: t("userSavedDescription")
|
|
||||||
});
|
|
||||||
setUserRoles((prev) => prev.filter((r) => r.roleId !== roleId));
|
|
||||||
} catch (e) {
|
|
||||||
toast({
|
|
||||||
variant: "destructive",
|
|
||||||
title: t("accessRoleErrorAdd"),
|
|
||||||
description: formatAxiosError(
|
|
||||||
e,
|
|
||||||
t("accessRoleErrorAddDescription")
|
|
||||||
)
|
|
||||||
});
|
|
||||||
}
|
|
||||||
setLoading(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
async function onSubmit(values: z.infer<typeof formSchema>) {
|
async function onSubmit(values: z.infer<typeof formSchema>) {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await api.post(`/org/${orgId}/user/${user.userId}`, {
|
// Execute both API calls simultaneously
|
||||||
autoProvisioned: values.autoProvisioned
|
const [roleRes, userRes] = await Promise.all([
|
||||||
});
|
api.post<AxiosResponse<InviteUserResponse>>(
|
||||||
toast({
|
`/role/${values.roleId}/add/${user.userId}`
|
||||||
variant: "default",
|
),
|
||||||
title: t("userSaved"),
|
api.post(`/org/${orgId}/user/${user.userId}`, {
|
||||||
description: t("userSavedDescription")
|
autoProvisioned: values.autoProvisioned
|
||||||
});
|
})
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (roleRes.status === 200 && userRes.status === 200) {
|
||||||
|
toast({
|
||||||
|
variant: "default",
|
||||||
|
title: t("userSaved"),
|
||||||
|
description: t("userSavedDescription")
|
||||||
|
});
|
||||||
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
toast({
|
toast({
|
||||||
variant: "destructive",
|
variant: "destructive",
|
||||||
@@ -172,14 +130,10 @@ export default function AccessControlsPage() {
|
|||||||
)
|
)
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
const availableRolesToAdd = roles.filter(
|
|
||||||
(r) => !userRoles.some((ur) => ur.roleId === r.roleId)
|
|
||||||
);
|
|
||||||
const canRemoveRole = userRoles.length > 1;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<SettingsContainer>
|
<SettingsContainer>
|
||||||
<SettingsSection>
|
<SettingsSection>
|
||||||
@@ -200,6 +154,7 @@ export default function AccessControlsPage() {
|
|||||||
className="space-y-4"
|
className="space-y-4"
|
||||||
id="access-controls-form"
|
id="access-controls-form"
|
||||||
>
|
>
|
||||||
|
{/* IDP Type Display */}
|
||||||
{user.type !== UserType.Internal &&
|
{user.type !== UserType.Internal &&
|
||||||
user.idpType && (
|
user.idpType && (
|
||||||
<div className="flex items-center space-x-2 mb-4">
|
<div className="flex items-center space-x-2 mb-4">
|
||||||
@@ -216,72 +171,49 @@ export default function AccessControlsPage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<FormItem>
|
<FormField
|
||||||
<FormLabel>{t("role")}</FormLabel>
|
control={form.control}
|
||||||
<div className="flex flex-wrap gap-2 items-center">
|
name="roleId"
|
||||||
{userRoles.map((r) => (
|
render={({ field }) => (
|
||||||
<Badge
|
<FormItem>
|
||||||
key={r.roleId}
|
<FormLabel>{t("role")}</FormLabel>
|
||||||
variant="secondary"
|
|
||||||
className="flex items-center gap-1"
|
|
||||||
>
|
|
||||||
{r.name}
|
|
||||||
{canRemoveRole && (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={() =>
|
|
||||||
handleRemoveRole(
|
|
||||||
r.roleId
|
|
||||||
)
|
|
||||||
}
|
|
||||||
disabled={loading}
|
|
||||||
className="ml-1 rounded hover:bg-muted"
|
|
||||||
aria-label={`Remove ${r.name}`}
|
|
||||||
>
|
|
||||||
×
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</Badge>
|
|
||||||
))}
|
|
||||||
{availableRolesToAdd.length > 0 && (
|
|
||||||
<Select
|
<Select
|
||||||
onValueChange={(value) => {
|
onValueChange={(value) => {
|
||||||
handleAddRole(
|
field.onChange(value);
|
||||||
parseInt(value, 10)
|
// If auto provision is enabled, set it to false when role changes
|
||||||
);
|
if (user.idpAutoProvision) {
|
||||||
|
form.setValue(
|
||||||
|
"autoProvisioned",
|
||||||
|
false
|
||||||
|
);
|
||||||
|
}
|
||||||
}}
|
}}
|
||||||
disabled={loading}
|
value={field.value}
|
||||||
>
|
>
|
||||||
<SelectTrigger className="w-[180px]">
|
<FormControl>
|
||||||
<SelectValue
|
<SelectTrigger>
|
||||||
placeholder={t(
|
<SelectValue
|
||||||
"accessRoleSelect"
|
placeholder={t(
|
||||||
)}
|
"accessRoleSelect"
|
||||||
/>
|
)}
|
||||||
</SelectTrigger>
|
/>
|
||||||
|
</SelectTrigger>
|
||||||
|
</FormControl>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
{availableRolesToAdd.map(
|
{roles.map((role) => (
|
||||||
(role) => (
|
<SelectItem
|
||||||
<SelectItem
|
key={role.roleId}
|
||||||
key={
|
value={role.roleId.toString()}
|
||||||
role.roleId
|
>
|
||||||
}
|
{role.name}
|
||||||
value={role.roleId.toString()}
|
</SelectItem>
|
||||||
>
|
))}
|
||||||
{role.name}
|
|
||||||
</SelectItem>
|
|
||||||
)
|
|
||||||
)}
|
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
)}
|
<FormMessage />
|
||||||
</div>
|
</FormItem>
|
||||||
{userRoles.length === 0 && (
|
|
||||||
<p className="text-sm text-muted-foreground">
|
|
||||||
{t("accessRoleSelectPlease")}
|
|
||||||
</p>
|
|
||||||
)}
|
)}
|
||||||
</FormItem>
|
/>
|
||||||
|
|
||||||
{user.idpAutoProvision && (
|
{user.idpAutoProvision && (
|
||||||
<FormField
|
<FormField
|
||||||
@@ -299,9 +231,7 @@ export default function AccessControlsPage() {
|
|||||||
</FormControl>
|
</FormControl>
|
||||||
<div className="space-y-1 leading-none">
|
<div className="space-y-1 leading-none">
|
||||||
<FormLabel>
|
<FormLabel>
|
||||||
{t(
|
{t("autoProvisioned")}
|
||||||
"autoProvisioned"
|
|
||||||
)}
|
|
||||||
</FormLabel>
|
</FormLabel>
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-sm text-muted-foreground">
|
||||||
{t(
|
{t(
|
||||||
|
|||||||
@@ -88,9 +88,7 @@ export default async function UsersPage(props: UsersPageProps) {
|
|||||||
status: t("userConfirmed"),
|
status: t("userConfirmed"),
|
||||||
role: user.isOwner
|
role: user.isOwner
|
||||||
? t("accessRoleOwner")
|
? t("accessRoleOwner")
|
||||||
: user.roles?.length
|
: user.roleName || t("accessRoleMember"),
|
||||||
? user.roles.map((r) => r.roleName).join(", ")
|
|
||||||
: t("accessRoleMember"),
|
|
||||||
isOwner: user.isOwner || false
|
isOwner: user.isOwner || false
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -5,11 +5,13 @@ import { SidebarNav } from "@app/components/SidebarNav";
|
|||||||
import { OrgSelector } from "@app/components/OrgSelector";
|
import { OrgSelector } from "@app/components/OrgSelector";
|
||||||
import { cn } from "@app/lib/cn";
|
import { cn } from "@app/lib/cn";
|
||||||
import { ListUserOrgsResponse } from "@server/routers/org";
|
import { ListUserOrgsResponse } from "@server/routers/org";
|
||||||
|
import SupporterStatus from "@app/components/SupporterStatus";
|
||||||
import { Button } from "@app/components/ui/button";
|
import { Button } from "@app/components/ui/button";
|
||||||
import { ArrowRight, Menu, Server } from "lucide-react";
|
import { ExternalLink, Menu, Server } from "lucide-react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { usePathname } from "next/navigation";
|
import { usePathname } from "next/navigation";
|
||||||
import { useUserContext } from "@app/hooks/useUserContext";
|
import { useUserContext } from "@app/hooks/useUserContext";
|
||||||
|
import { useEnvContext } from "@app/hooks/useEnvContext";
|
||||||
import { useTranslations } from "next-intl";
|
import { useTranslations } from "next-intl";
|
||||||
import ProfileIcon from "@app/components/ProfileIcon";
|
import ProfileIcon from "@app/components/ProfileIcon";
|
||||||
import ThemeSwitcher from "@app/components/ThemeSwitcher";
|
import ThemeSwitcher from "@app/components/ThemeSwitcher";
|
||||||
@@ -42,6 +44,7 @@ export function LayoutMobileMenu({
|
|||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
const isAdminPage = pathname?.startsWith("/admin");
|
const isAdminPage = pathname?.startsWith("/admin");
|
||||||
const { user } = useUserContext();
|
const { user } = useUserContext();
|
||||||
|
const { env } = useEnvContext();
|
||||||
const t = useTranslations();
|
const t = useTranslations();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -80,7 +83,7 @@ export function LayoutMobileMenu({
|
|||||||
<div className="px-3 pt-3">
|
<div className="px-3 pt-3">
|
||||||
{!isAdminPage &&
|
{!isAdminPage &&
|
||||||
user.serverAdmin && (
|
user.serverAdmin && (
|
||||||
<div className="mb-1">
|
<div className="py-2">
|
||||||
<Link
|
<Link
|
||||||
href="/admin"
|
href="/admin"
|
||||||
className={cn(
|
className={cn(
|
||||||
@@ -95,12 +98,11 @@ export function LayoutMobileMenu({
|
|||||||
<span className="flex-shrink-0 mr-2">
|
<span className="flex-shrink-0 mr-2">
|
||||||
<Server className="h-4 w-4" />
|
<Server className="h-4 w-4" />
|
||||||
</span>
|
</span>
|
||||||
<span className="flex-1">
|
<span>
|
||||||
{t(
|
{t(
|
||||||
"serverAdmin"
|
"serverAdmin"
|
||||||
)}
|
)}
|
||||||
</span>
|
</span>
|
||||||
<ArrowRight className="h-4 w-4 shrink-0 ml-auto opacity-70" />
|
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@@ -113,6 +115,22 @@ export function LayoutMobileMenu({
|
|||||||
</div>
|
</div>
|
||||||
<div className="sticky bottom-0 left-0 right-0 h-8 pointer-events-none bg-gradient-to-t from-card to-transparent" />
|
<div className="sticky bottom-0 left-0 right-0 h-8 pointer-events-none bg-gradient-to-t from-card to-transparent" />
|
||||||
</div>
|
</div>
|
||||||
|
<div className="px-3 pt-3 pb-3 space-y-4 border-t shrink-0">
|
||||||
|
<SupporterStatus />
|
||||||
|
{env?.app?.version && (
|
||||||
|
<div className="text-xs text-muted-foreground text-center">
|
||||||
|
<Link
|
||||||
|
href={`https://github.com/fosrl/pangolin/releases/tag/${env.app.version}`}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="flex items-center justify-center gap-1"
|
||||||
|
>
|
||||||
|
v{env.app.version}
|
||||||
|
<ExternalLink size={12} />
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</SheetContent>
|
</SheetContent>
|
||||||
</Sheet>
|
</Sheet>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -146,46 +146,6 @@ export function LayoutSidebar({
|
|||||||
/>
|
/>
|
||||||
<div className="flex-1 overflow-y-auto relative">
|
<div className="flex-1 overflow-y-auto relative">
|
||||||
<div className="px-2 pt-3">
|
<div className="px-2 pt-3">
|
||||||
{!isAdminPage && user.serverAdmin && (
|
|
||||||
<div
|
|
||||||
className={cn(
|
|
||||||
"shrink-0",
|
|
||||||
isSidebarCollapsed ? "mb-4" : "mb-1"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<Link
|
|
||||||
href="/admin"
|
|
||||||
className={cn(
|
|
||||||
"flex items-center transition-colors text-muted-foreground hover:text-foreground text-sm w-full hover:bg-secondary/80 dark:hover:bg-secondary/50 rounded-md",
|
|
||||||
isSidebarCollapsed
|
|
||||||
? "px-2 py-2 justify-center"
|
|
||||||
: "px-3 py-1.5"
|
|
||||||
)}
|
|
||||||
title={
|
|
||||||
isSidebarCollapsed
|
|
||||||
? t("serverAdmin")
|
|
||||||
: undefined
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<span
|
|
||||||
className={cn(
|
|
||||||
"shrink-0",
|
|
||||||
!isSidebarCollapsed && "mr-2"
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
<Server className="h-4 w-4" />
|
|
||||||
</span>
|
|
||||||
{!isSidebarCollapsed && (
|
|
||||||
<>
|
|
||||||
<span className="flex-1">
|
|
||||||
{t("serverAdmin")}
|
|
||||||
</span>
|
|
||||||
<ArrowRight className="h-4 w-4 shrink-0 ml-auto opacity-70" />
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<SidebarNav
|
<SidebarNav
|
||||||
sections={navItems}
|
sections={navItems}
|
||||||
isCollapsed={isSidebarCollapsed}
|
isCollapsed={isSidebarCollapsed}
|
||||||
@@ -196,6 +156,40 @@ export function LayoutSidebar({
|
|||||||
<div className="sticky bottom-0 left-0 right-0 h-8 pointer-events-none bg-gradient-to-t from-card to-transparent" />
|
<div className="sticky bottom-0 left-0 right-0 h-8 pointer-events-none bg-gradient-to-t from-card to-transparent" />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{!isAdminPage && user.serverAdmin && (
|
||||||
|
<div className="shrink-0 px-2 pb-2">
|
||||||
|
<Link
|
||||||
|
href="/admin"
|
||||||
|
className={cn(
|
||||||
|
"flex items-center transition-colors text-muted-foreground hover:text-foreground text-sm w-full hover:bg-secondary/80 dark:hover:bg-secondary/50 rounded-md",
|
||||||
|
isSidebarCollapsed
|
||||||
|
? "px-2 py-2 justify-center"
|
||||||
|
: "px-3 py-1.5"
|
||||||
|
)}
|
||||||
|
title={
|
||||||
|
isSidebarCollapsed ? t("serverAdmin") : undefined
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"shrink-0",
|
||||||
|
!isSidebarCollapsed && "mr-2"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Server className="h-4 w-4" />
|
||||||
|
</span>
|
||||||
|
{!isSidebarCollapsed && (
|
||||||
|
<>
|
||||||
|
<span className="flex-1">
|
||||||
|
{t("serverAdmin")}
|
||||||
|
</span>
|
||||||
|
<ArrowRight className="h-4 w-4 shrink-0 ml-auto opacity-70" />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{isSidebarCollapsed && (
|
{isSidebarCollapsed && (
|
||||||
<div className="shrink-0 flex justify-center py-2">
|
<div className="shrink-0 flex justify-center py-2">
|
||||||
<TooltipProvider>
|
<TooltipProvider>
|
||||||
@@ -224,7 +218,7 @@ export function LayoutSidebar({
|
|||||||
|
|
||||||
<div className="w-full border-t border-border mb-3" />
|
<div className="w-full border-t border-border mb-3" />
|
||||||
|
|
||||||
<div className="p-4 pt-1 flex flex-col shrink-0">
|
<div className="p-4 pt-0 mt-0 flex flex-col shrink-0">
|
||||||
{canShowProductUpdates && (
|
{canShowProductUpdates && (
|
||||||
<div className="mb-3 empty:mb-0">
|
<div className="mb-3 empty:mb-0">
|
||||||
<ProductUpdates isCollapsed={isSidebarCollapsed} />
|
<ProductUpdates isCollapsed={isSidebarCollapsed} />
|
||||||
|
|||||||
Reference in New Issue
Block a user