feat: add onboarding and user invitations
This commit is contained in:
parent
24351eb897
commit
762cfe2b16
37 changed files with 5208 additions and 384 deletions
|
|
@ -21,7 +21,11 @@ async function getAuthorization(userId: string) {
|
|||
.where(eq(userRole.userId, userId));
|
||||
|
||||
return {
|
||||
roles: Array.from(new Map(rows.map((row) => [row.roleId, { id: row.roleId, name: row.roleName }])).values()),
|
||||
roles: Array.from(
|
||||
new Map(
|
||||
rows.map((row) => [row.roleId, { id: row.roleId, name: row.roleName }]),
|
||||
).values(),
|
||||
),
|
||||
permissions: Array.from(new Set(rows.map((row) => row.permissionName))),
|
||||
};
|
||||
}
|
||||
|
|
@ -31,12 +35,15 @@ export async function createContext({ context }: CreateContextOptions) {
|
|||
headers: context.request.headers,
|
||||
});
|
||||
|
||||
const authorization = session ? await getAuthorization(session.user.id) : { roles: [], permissions: [] };
|
||||
const authorization = session
|
||||
? await getAuthorization(session.user.id)
|
||||
: { roles: [], permissions: [] };
|
||||
|
||||
return {
|
||||
auth: null,
|
||||
auth,
|
||||
session,
|
||||
authorization,
|
||||
requestHeaders: context.request.headers,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -35,6 +35,13 @@ export function requirePermission(permission: Permission) {
|
|||
});
|
||||
}
|
||||
|
||||
if (ctx.session.user.mustChangePassword) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "Change the initial password before using Minmon",
|
||||
});
|
||||
}
|
||||
|
||||
if (!ctx.authorization.permissions.includes(permission)) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
|
|
|
|||
67
packages/api/src/lib/invitation-token.ts
Normal file
67
packages/api/src/lib/invitation-token.ts
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
import { env } from "@minmon/env/server";
|
||||
|
||||
const textEncoder = new TextEncoder();
|
||||
const inviteKeyMaterial = textEncoder.encode(
|
||||
`${env.BETTER_AUTH_SECRET}:minmon-user-invitations:v1`,
|
||||
);
|
||||
|
||||
const inviteKeyPromise = crypto.subtle
|
||||
.digest("SHA-256", inviteKeyMaterial)
|
||||
.then((digest) =>
|
||||
crypto.subtle.importKey("raw", digest, { name: "AES-GCM" }, false, [
|
||||
"encrypt",
|
||||
"decrypt",
|
||||
]),
|
||||
);
|
||||
|
||||
function encodeBytes(value: ArrayBuffer | Uint8Array) {
|
||||
return Buffer.from(
|
||||
value instanceof Uint8Array ? value : new Uint8Array(value),
|
||||
).toString("base64url");
|
||||
}
|
||||
|
||||
function decodeBytes(value: string) {
|
||||
return new Uint8Array(Buffer.from(value, "base64url"));
|
||||
}
|
||||
|
||||
export async function hashInvitationToken(token: string) {
|
||||
const digest = await crypto.subtle.digest(
|
||||
"SHA-256",
|
||||
textEncoder.encode(token),
|
||||
);
|
||||
return Buffer.from(digest).toString("hex");
|
||||
}
|
||||
|
||||
export async function createInvitationToken() {
|
||||
const tokenBytes = crypto.getRandomValues(new Uint8Array(32));
|
||||
const token = encodeBytes(tokenBytes);
|
||||
const tokenHash = await hashInvitationToken(token);
|
||||
const tokenIvBytes = crypto.getRandomValues(new Uint8Array(12));
|
||||
const key = await inviteKeyPromise;
|
||||
const encrypted = await crypto.subtle.encrypt(
|
||||
{ name: "AES-GCM", iv: tokenIvBytes },
|
||||
key,
|
||||
textEncoder.encode(token),
|
||||
);
|
||||
|
||||
return {
|
||||
token,
|
||||
tokenHash,
|
||||
tokenEncrypted: encodeBytes(encrypted),
|
||||
tokenIv: encodeBytes(tokenIvBytes),
|
||||
};
|
||||
}
|
||||
|
||||
export async function decryptInvitationToken(
|
||||
tokenEncrypted: string,
|
||||
tokenIv: string,
|
||||
) {
|
||||
const key = await inviteKeyPromise;
|
||||
const decrypted = await crypto.subtle.decrypt(
|
||||
{ name: "AES-GCM", iv: decodeBytes(tokenIv) },
|
||||
key,
|
||||
decodeBytes(tokenEncrypted),
|
||||
);
|
||||
|
||||
return new TextDecoder().decode(decrypted);
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@ import { publicProcedure, router } from "../index";
|
|||
import { dashboardRouter } from "./dashboard";
|
||||
import { domainsRouter } from "./domains";
|
||||
import { notesRouter } from "./notes";
|
||||
import { onboardingRouter } from "./onboarding";
|
||||
import { serversRouter } from "./servers";
|
||||
import { servicesRouter } from "./services";
|
||||
import { usersRouter } from "./users";
|
||||
|
|
@ -11,6 +12,7 @@ export const appRouter = router({
|
|||
healthCheck: publicProcedure.query(() => {
|
||||
return "OK";
|
||||
}),
|
||||
onboarding: onboardingRouter,
|
||||
dashboard: dashboardRouter,
|
||||
servers: serversRouter,
|
||||
services: servicesRouter,
|
||||
|
|
|
|||
119
packages/api/src/routers/onboarding.ts
Normal file
119
packages/api/src/routers/onboarding.ts
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
import {
|
||||
account,
|
||||
db,
|
||||
permission,
|
||||
role,
|
||||
rolePermission,
|
||||
user,
|
||||
userRole,
|
||||
} from "@minmon/db";
|
||||
import { hashCredentialPassword } from "@minmon/db/auth-utils";
|
||||
import { permissions, roleDefinitions } from "@minmon/db/rbac";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { sql } from "drizzle-orm";
|
||||
|
||||
import { publicProcedure, router } from "../index";
|
||||
import { onboardingCreateAdminSchema } from "./schemas";
|
||||
import { createEntityId } from "./utils";
|
||||
|
||||
const ADMIN_ROLE_ID = "role_admin";
|
||||
|
||||
export const onboardingRouter = router({
|
||||
status: publicProcedure.query(async () => {
|
||||
const [existingUser] = await db.select({ id: user.id }).from(user).limit(1);
|
||||
return { needsSetup: !existingUser };
|
||||
}),
|
||||
|
||||
createAdmin: publicProcedure
|
||||
.input(onboardingCreateAdminSchema)
|
||||
.mutation(async ({ input }) => {
|
||||
const passwordHash = await hashCredentialPassword(input.password);
|
||||
const userId = createEntityId();
|
||||
const accountId = createEntityId();
|
||||
const email = input.email.trim().toLowerCase();
|
||||
|
||||
return db.transaction(async (tx) => {
|
||||
await tx.execute(sql`select pg_advisory_xact_lock(612984117)`);
|
||||
|
||||
const [existingUser] = await tx
|
||||
.select({ id: user.id })
|
||||
.from(user)
|
||||
.limit(1);
|
||||
if (existingUser) {
|
||||
throw new TRPCError({
|
||||
code: "CONFLICT",
|
||||
message: "Minmon setup has already been completed",
|
||||
});
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
|
||||
await tx
|
||||
.insert(permission)
|
||||
.values(
|
||||
permissions.map((name) => ({
|
||||
id: name,
|
||||
name,
|
||||
description: `Allows ${name.replace(".", " ")}`,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})),
|
||||
)
|
||||
.onConflictDoNothing();
|
||||
|
||||
await tx
|
||||
.insert(role)
|
||||
.values(
|
||||
roleDefinitions.map((definition) => ({
|
||||
id: definition.id,
|
||||
name: definition.name,
|
||||
description: definition.description,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})),
|
||||
)
|
||||
.onConflictDoNothing();
|
||||
|
||||
await tx
|
||||
.insert(rolePermission)
|
||||
.values(
|
||||
roleDefinitions.flatMap((definition) =>
|
||||
definition.permissions.map((permissionName) => ({
|
||||
roleId: definition.id,
|
||||
permissionId: permissionName,
|
||||
createdAt: now,
|
||||
})),
|
||||
),
|
||||
)
|
||||
.onConflictDoNothing();
|
||||
|
||||
await tx.insert(user).values({
|
||||
id: userId,
|
||||
name: input.name,
|
||||
email,
|
||||
emailVerified: false,
|
||||
mustChangePassword: false,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
await tx.insert(account).values({
|
||||
id: accountId,
|
||||
accountId: userId,
|
||||
providerId: "credential",
|
||||
userId,
|
||||
password: passwordHash,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
await tx.insert(userRole).values({
|
||||
userId,
|
||||
roleId: ADMIN_ROLE_ID,
|
||||
createdAt: now,
|
||||
});
|
||||
|
||||
return { userId, email };
|
||||
});
|
||||
}),
|
||||
});
|
||||
|
|
@ -10,7 +10,12 @@ export const ipv4Schema = z
|
|||
"Must be a valid IPv4 address",
|
||||
);
|
||||
|
||||
export const optionalTextSchema = z.string().trim().max(5000).nullable().optional();
|
||||
export const optionalTextSchema = z
|
||||
.string()
|
||||
.trim()
|
||||
.max(5000)
|
||||
.nullable()
|
||||
.optional();
|
||||
|
||||
export const hostnameSchema = z
|
||||
.string()
|
||||
|
|
@ -23,10 +28,27 @@ export const hostnameSchema = z
|
|||
);
|
||||
|
||||
export const serverStatusSchema = z.enum(["active", "maintenance", "inactive"]);
|
||||
export const serviceTypeSchema = z.enum(["web_app", "mail", "database", "api", "proxy", "other"]);
|
||||
export const serviceProtocolSchema = z.enum(["http", "https", "tcp", "udp", "other"]);
|
||||
export const serviceTypeSchema = z.enum([
|
||||
"web_app",
|
||||
"mail",
|
||||
"database",
|
||||
"api",
|
||||
"proxy",
|
||||
"other",
|
||||
]);
|
||||
export const serviceProtocolSchema = z.enum([
|
||||
"http",
|
||||
"https",
|
||||
"tcp",
|
||||
"udp",
|
||||
"other",
|
||||
]);
|
||||
export const serviceStatusSchema = z.enum(["active", "down", "maintenance"]);
|
||||
export const domainCheckStatusSchema = z.enum(["MATCH", "MISMATCH", "UNRESOLVED"]);
|
||||
export const domainCheckStatusSchema = z.enum([
|
||||
"MATCH",
|
||||
"MISMATCH",
|
||||
"UNRESOLVED",
|
||||
]);
|
||||
|
||||
export const byIdSchema = z.object({
|
||||
id: entityIdSchema,
|
||||
|
|
@ -114,6 +136,47 @@ export const updateUserRolesSchema = z.object({
|
|||
export const userCreateSchema = z.object({
|
||||
name: z.string().trim().min(2, "Name must be at least 2 characters").max(120),
|
||||
email: z.email("Invalid email address").max(255),
|
||||
password: z.string().min(8, "Password must be at least 8 characters").max(255),
|
||||
password: z
|
||||
.string()
|
||||
.min(8, "Password must be at least 8 characters")
|
||||
.max(255),
|
||||
roleIds: z.array(entityIdSchema).min(1, "Select at least one role"),
|
||||
});
|
||||
|
||||
export const onboardingCreateAdminSchema = z.object({
|
||||
name: z.string().trim().min(2, "Name must be at least 2 characters").max(120),
|
||||
email: z.email("Invalid email address").max(255),
|
||||
password: z
|
||||
.string()
|
||||
.min(8, "Password must be at least 8 characters")
|
||||
.max(255),
|
||||
});
|
||||
|
||||
export const userInvitationCreateSchema = z.object({
|
||||
roleIds: z.array(entityIdSchema).min(1, "Select at least one role"),
|
||||
});
|
||||
|
||||
export const invitationTokenSchema = z.object({
|
||||
token: z
|
||||
.string()
|
||||
.min(32, "Invalid invitation link")
|
||||
.max(128, "Invalid invitation link")
|
||||
.regex(/^[A-Za-z0-9_-]+$/, "Invalid invitation link"),
|
||||
});
|
||||
|
||||
export const userInvitationAcceptSchema = invitationTokenSchema.extend({
|
||||
name: z.string().trim().min(2, "Name must be at least 2 characters").max(120),
|
||||
email: z.email("Invalid email address").max(255),
|
||||
password: z
|
||||
.string()
|
||||
.min(8, "Password must be at least 8 characters")
|
||||
.max(255),
|
||||
});
|
||||
|
||||
export const changeInitialPasswordSchema = z.object({
|
||||
currentPassword: z.string().min(1, "Enter your current password").max(255),
|
||||
newPassword: z
|
||||
.string()
|
||||
.min(8, "Password must be at least 8 characters")
|
||||
.max(255),
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,11 +1,42 @@
|
|||
import { db, account, role, user, userRole } from "@minmon/db";
|
||||
import { auth } from "@minmon/auth";
|
||||
import {
|
||||
account,
|
||||
db,
|
||||
role,
|
||||
session,
|
||||
user,
|
||||
userInvitation,
|
||||
userInvitationRole,
|
||||
userRole,
|
||||
} from "@minmon/db";
|
||||
import { hashCredentialPassword } from "@minmon/db/auth-utils";
|
||||
import { asc, eq } from "drizzle-orm";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { and, asc, count, desc, eq, isNull, ne, sql } from "drizzle-orm";
|
||||
|
||||
import { permissionedProcedure, protectedProcedure, router } from "../index";
|
||||
import { byIdSchema, updateUserRolesSchema, userCreateSchema } from "./schemas";
|
||||
import {
|
||||
createInvitationToken,
|
||||
decryptInvitationToken,
|
||||
hashInvitationToken,
|
||||
} from "../lib/invitation-token";
|
||||
import {
|
||||
permissionedProcedure,
|
||||
protectedProcedure,
|
||||
publicProcedure,
|
||||
router,
|
||||
} from "../index";
|
||||
import {
|
||||
byIdSchema,
|
||||
changeInitialPasswordSchema,
|
||||
invitationTokenSchema,
|
||||
updateUserRolesSchema,
|
||||
userCreateSchema,
|
||||
userInvitationAcceptSchema,
|
||||
userInvitationCreateSchema,
|
||||
} from "./schemas";
|
||||
import { badRequest, createEntityId, notFound } from "./utils";
|
||||
|
||||
const ADMIN_ROLE_ID = "role_admin";
|
||||
|
||||
async function getUsersWithRoles() {
|
||||
const [users, assignments] = await Promise.all([
|
||||
db
|
||||
|
|
@ -14,6 +45,7 @@ async function getUsersWithRoles() {
|
|||
name: user.name,
|
||||
email: user.email,
|
||||
emailVerified: user.emailVerified,
|
||||
mustChangePassword: user.mustChangePassword,
|
||||
image: user.image,
|
||||
createdAt: user.createdAt,
|
||||
updatedAt: user.updatedAt,
|
||||
|
|
@ -35,16 +67,84 @@ async function getUsersWithRoles() {
|
|||
...item,
|
||||
roles: assignments
|
||||
.filter((assignment) => assignment.userId === item.id)
|
||||
.map((assignment) => ({ id: assignment.roleId, name: assignment.roleName })),
|
||||
.map((assignment) => ({
|
||||
id: assignment.roleId,
|
||||
name: assignment.roleName,
|
||||
})),
|
||||
}));
|
||||
}
|
||||
|
||||
async function getInvitationsWithRoles() {
|
||||
const [invitations, assignments] = await Promise.all([
|
||||
db
|
||||
.select({
|
||||
id: userInvitation.id,
|
||||
tokenEncrypted: userInvitation.tokenEncrypted,
|
||||
tokenIv: userInvitation.tokenIv,
|
||||
createdByUserId: userInvitation.createdByUserId,
|
||||
acceptedUserId: userInvitation.acceptedUserId,
|
||||
revokedAt: userInvitation.revokedAt,
|
||||
acceptedAt: userInvitation.acceptedAt,
|
||||
createdAt: userInvitation.createdAt,
|
||||
updatedAt: userInvitation.updatedAt,
|
||||
})
|
||||
.from(userInvitation)
|
||||
.orderBy(desc(userInvitation.createdAt), desc(userInvitation.id)),
|
||||
db
|
||||
.select({
|
||||
invitationId: userInvitationRole.invitationId,
|
||||
roleId: role.id,
|
||||
roleName: role.name,
|
||||
})
|
||||
.from(userInvitationRole)
|
||||
.innerJoin(role, eq(role.id, userInvitationRole.roleId))
|
||||
.orderBy(asc(role.name)),
|
||||
]);
|
||||
|
||||
return Promise.all(
|
||||
invitations.map(async (invitation) => {
|
||||
const status = invitation.acceptedAt
|
||||
? ("accepted" as const)
|
||||
: invitation.revokedAt
|
||||
? ("revoked" as const)
|
||||
: ("pending" as const);
|
||||
const token =
|
||||
status === "pending"
|
||||
? await decryptInvitationToken(
|
||||
invitation.tokenEncrypted,
|
||||
invitation.tokenIv,
|
||||
).catch(() => null)
|
||||
: null;
|
||||
|
||||
return {
|
||||
id: invitation.id,
|
||||
createdByUserId: invitation.createdByUserId,
|
||||
acceptedUserId: invitation.acceptedUserId,
|
||||
revokedAt: invitation.revokedAt,
|
||||
acceptedAt: invitation.acceptedAt,
|
||||
createdAt: invitation.createdAt,
|
||||
updatedAt: invitation.updatedAt,
|
||||
status,
|
||||
token,
|
||||
roles: assignments
|
||||
.filter((assignment) => assignment.invitationId === invitation.id)
|
||||
.map((assignment) => ({
|
||||
id: assignment.roleId,
|
||||
name: assignment.roleName,
|
||||
})),
|
||||
};
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async function validateRoleIds(roleIds: string[]) {
|
||||
const roles = await db.select({ id: role.id }).from(role);
|
||||
const validRoleIds = new Set(roles.map((item) => item.id));
|
||||
const uniqueRoleIds = Array.from(new Set(roleIds));
|
||||
|
||||
const invalidRoleId = uniqueRoleIds.find((roleId) => !validRoleIds.has(roleId));
|
||||
const invalidRoleId = uniqueRoleIds.find(
|
||||
(roleId) => !validRoleIds.has(roleId),
|
||||
);
|
||||
if (invalidRoleId) {
|
||||
notFound(`Role not found: ${invalidRoleId}`);
|
||||
}
|
||||
|
|
@ -53,13 +153,26 @@ async function validateRoleIds(roleIds: string[]) {
|
|||
}
|
||||
|
||||
export const usersRouter = router({
|
||||
me: protectedProcedure.query(({ ctx }) => ({
|
||||
user: ctx.session.user,
|
||||
roles: ctx.authorization.roles,
|
||||
permissions: ctx.authorization.permissions,
|
||||
})),
|
||||
me: protectedProcedure.query(async ({ ctx }) => {
|
||||
const [currentUser] = await db
|
||||
.select({ mustChangePassword: user.mustChangePassword })
|
||||
.from(user)
|
||||
.where(eq(user.id, ctx.session.user.id))
|
||||
.limit(1);
|
||||
|
||||
list: permissionedProcedure("users.read").query(async () => getUsersWithRoles()),
|
||||
return {
|
||||
user: {
|
||||
...ctx.session.user,
|
||||
mustChangePassword: currentUser?.mustChangePassword ?? false,
|
||||
},
|
||||
roles: ctx.authorization.roles,
|
||||
permissions: ctx.authorization.permissions,
|
||||
};
|
||||
}),
|
||||
|
||||
list: permissionedProcedure("users.read").query(async () =>
|
||||
getUsersWithRoles(),
|
||||
),
|
||||
|
||||
roles: permissionedProcedure("users.read").query(async () =>
|
||||
db
|
||||
|
|
@ -75,7 +188,12 @@ export const usersRouter = router({
|
|||
create: permissionedProcedure("users.create")
|
||||
.input(userCreateSchema)
|
||||
.mutation(async ({ input }) => {
|
||||
const [existingUser] = await db.select({ id: user.id }).from(user).where(eq(user.email, input.email)).limit(1);
|
||||
const email = input.email.trim().toLowerCase();
|
||||
const [existingUser] = await db
|
||||
.select({ id: user.id })
|
||||
.from(user)
|
||||
.where(eq(sql<string>`lower(${user.email})`, email))
|
||||
.limit(1);
|
||||
|
||||
if (existingUser) {
|
||||
badRequest("A user with this email already exists");
|
||||
|
|
@ -83,74 +201,429 @@ export const usersRouter = router({
|
|||
|
||||
const uniqueRoleIds = await validateRoleIds(input.roleIds);
|
||||
const userId = createEntityId();
|
||||
const now = new Date();
|
||||
const passwordHash = await hashCredentialPassword(input.password);
|
||||
|
||||
await db.insert(user).values({
|
||||
id: userId,
|
||||
name: input.name,
|
||||
email: input.email,
|
||||
emailVerified: true,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
await db.transaction(async (tx) => {
|
||||
const now = new Date();
|
||||
|
||||
await db.insert(account).values({
|
||||
id: createEntityId(),
|
||||
accountId: userId,
|
||||
providerId: "credential",
|
||||
userId,
|
||||
password: passwordHash,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
await tx.insert(user).values({
|
||||
id: userId,
|
||||
name: input.name,
|
||||
email,
|
||||
emailVerified: false,
|
||||
mustChangePassword: true,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
await db.insert(userRole).values(
|
||||
uniqueRoleIds.map((roleId) => ({
|
||||
await tx.insert(account).values({
|
||||
id: createEntityId(),
|
||||
accountId: userId,
|
||||
providerId: "credential",
|
||||
userId,
|
||||
roleId,
|
||||
})),
|
||||
);
|
||||
password: passwordHash,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
await tx.insert(userRole).values(
|
||||
uniqueRoleIds.map((roleId) => ({
|
||||
userId,
|
||||
roleId,
|
||||
})),
|
||||
);
|
||||
});
|
||||
|
||||
const users = await getUsersWithRoles();
|
||||
return users.find((item) => item.id === userId);
|
||||
}),
|
||||
|
||||
invitations: router({
|
||||
list: permissionedProcedure("users.create").query(async () =>
|
||||
getInvitationsWithRoles(),
|
||||
),
|
||||
|
||||
create: permissionedProcedure("users.create")
|
||||
.input(userInvitationCreateSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const uniqueRoleIds = await validateRoleIds(input.roleIds);
|
||||
const invitationId = createEntityId();
|
||||
const invitationToken = await createInvitationToken();
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
const now = new Date();
|
||||
|
||||
await tx.insert(userInvitation).values({
|
||||
id: invitationId,
|
||||
tokenHash: invitationToken.tokenHash,
|
||||
tokenEncrypted: invitationToken.tokenEncrypted,
|
||||
tokenIv: invitationToken.tokenIv,
|
||||
createdByUserId: ctx.session.user.id,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
await tx.insert(userInvitationRole).values(
|
||||
uniqueRoleIds.map((roleId) => ({
|
||||
invitationId,
|
||||
roleId,
|
||||
createdAt: now,
|
||||
})),
|
||||
);
|
||||
});
|
||||
|
||||
const invitations = await getInvitationsWithRoles();
|
||||
return invitations.find((invitation) => invitation.id === invitationId);
|
||||
}),
|
||||
|
||||
revoke: permissionedProcedure("users.create")
|
||||
.input(byIdSchema)
|
||||
.mutation(async ({ input }) => {
|
||||
const now = new Date();
|
||||
const [revoked] = await db
|
||||
.update(userInvitation)
|
||||
.set({ revokedAt: now, updatedAt: now })
|
||||
.where(
|
||||
and(
|
||||
eq(userInvitation.id, input.id),
|
||||
isNull(userInvitation.revokedAt),
|
||||
isNull(userInvitation.acceptedAt),
|
||||
),
|
||||
)
|
||||
.returning({ id: userInvitation.id });
|
||||
|
||||
if (!revoked) {
|
||||
badRequest("Only a pending invitation can be revoked");
|
||||
}
|
||||
|
||||
return { id: input.id };
|
||||
}),
|
||||
|
||||
reissue: permissionedProcedure("users.create")
|
||||
.input(byIdSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const invitationToken = await createInvitationToken();
|
||||
const replacementId = createEntityId();
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
const now = new Date();
|
||||
const [replaced] = await tx
|
||||
.update(userInvitation)
|
||||
.set({ revokedAt: now, updatedAt: now })
|
||||
.where(
|
||||
and(
|
||||
eq(userInvitation.id, input.id),
|
||||
isNull(userInvitation.revokedAt),
|
||||
isNull(userInvitation.acceptedAt),
|
||||
),
|
||||
)
|
||||
.returning({ id: userInvitation.id });
|
||||
|
||||
if (!replaced) {
|
||||
badRequest("Only a pending invitation can be replaced");
|
||||
}
|
||||
|
||||
const assignedRoles = await tx
|
||||
.select({ roleId: userInvitationRole.roleId })
|
||||
.from(userInvitationRole)
|
||||
.where(eq(userInvitationRole.invitationId, input.id));
|
||||
|
||||
if (!assignedRoles.length) {
|
||||
badRequest("The invitation has no roles to carry forward");
|
||||
}
|
||||
|
||||
await tx.insert(userInvitation).values({
|
||||
id: replacementId,
|
||||
tokenHash: invitationToken.tokenHash,
|
||||
tokenEncrypted: invitationToken.tokenEncrypted,
|
||||
tokenIv: invitationToken.tokenIv,
|
||||
createdByUserId: ctx.session.user.id,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
await tx.insert(userInvitationRole).values(
|
||||
assignedRoles.map(({ roleId }) => ({
|
||||
invitationId: replacementId,
|
||||
roleId,
|
||||
createdAt: now,
|
||||
})),
|
||||
);
|
||||
});
|
||||
|
||||
const invitations = await getInvitationsWithRoles();
|
||||
return invitations.find(
|
||||
(invitation) => invitation.id === replacementId,
|
||||
);
|
||||
}),
|
||||
|
||||
inspect: publicProcedure
|
||||
.input(invitationTokenSchema)
|
||||
.query(async ({ input }) => {
|
||||
const tokenHash = await hashInvitationToken(input.token);
|
||||
const [invitation] = await db
|
||||
.select({
|
||||
id: userInvitation.id,
|
||||
revokedAt: userInvitation.revokedAt,
|
||||
acceptedAt: userInvitation.acceptedAt,
|
||||
})
|
||||
.from(userInvitation)
|
||||
.where(eq(userInvitation.tokenHash, tokenHash))
|
||||
.limit(1);
|
||||
|
||||
if (!invitation) {
|
||||
return { status: "invalid" as const, roles: [] };
|
||||
}
|
||||
|
||||
const assignedRoles = await db
|
||||
.select({ id: role.id, name: role.name })
|
||||
.from(userInvitationRole)
|
||||
.innerJoin(role, eq(role.id, userInvitationRole.roleId))
|
||||
.where(eq(userInvitationRole.invitationId, invitation.id))
|
||||
.orderBy(asc(role.name));
|
||||
|
||||
return {
|
||||
status: invitation.acceptedAt
|
||||
? ("accepted" as const)
|
||||
: invitation.revokedAt
|
||||
? ("revoked" as const)
|
||||
: ("pending" as const),
|
||||
roles: assignedRoles,
|
||||
};
|
||||
}),
|
||||
|
||||
accept: publicProcedure
|
||||
.input(userInvitationAcceptSchema)
|
||||
.mutation(async ({ input }) => {
|
||||
const tokenHash = await hashInvitationToken(input.token);
|
||||
const [activeInvitation] = await db
|
||||
.select({ id: userInvitation.id })
|
||||
.from(userInvitation)
|
||||
.where(
|
||||
and(
|
||||
eq(userInvitation.tokenHash, tokenHash),
|
||||
isNull(userInvitation.revokedAt),
|
||||
isNull(userInvitation.acceptedAt),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (!activeInvitation) {
|
||||
badRequest("This invitation link is invalid or no longer active");
|
||||
}
|
||||
|
||||
const email = input.email.trim().toLowerCase();
|
||||
const passwordHash = await hashCredentialPassword(input.password);
|
||||
const userId = createEntityId();
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
const now = new Date();
|
||||
const [claimedInvitation] = await tx
|
||||
.update(userInvitation)
|
||||
.set({ acceptedAt: now, updatedAt: now })
|
||||
.where(
|
||||
and(
|
||||
eq(userInvitation.tokenHash, tokenHash),
|
||||
isNull(userInvitation.revokedAt),
|
||||
isNull(userInvitation.acceptedAt),
|
||||
),
|
||||
)
|
||||
.returning({ id: userInvitation.id });
|
||||
|
||||
if (!claimedInvitation) {
|
||||
badRequest("This invitation link has already been used or revoked");
|
||||
}
|
||||
|
||||
const assignedRoles = await tx
|
||||
.select({ roleId: userInvitationRole.roleId })
|
||||
.from(userInvitationRole)
|
||||
.where(eq(userInvitationRole.invitationId, claimedInvitation.id));
|
||||
|
||||
if (!assignedRoles.length) {
|
||||
badRequest("This invitation no longer grants an access role");
|
||||
}
|
||||
|
||||
const [existingUser] = await tx
|
||||
.select({ id: user.id })
|
||||
.from(user)
|
||||
.where(eq(sql<string>`lower(${user.email})`, email))
|
||||
.limit(1);
|
||||
|
||||
if (existingUser) {
|
||||
badRequest("A user with this email already exists");
|
||||
}
|
||||
|
||||
await tx.insert(user).values({
|
||||
id: userId,
|
||||
name: input.name,
|
||||
email,
|
||||
emailVerified: false,
|
||||
mustChangePassword: false,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
await tx.insert(account).values({
|
||||
id: createEntityId(),
|
||||
accountId: userId,
|
||||
providerId: "credential",
|
||||
userId,
|
||||
password: passwordHash,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
|
||||
await tx.insert(userRole).values(
|
||||
assignedRoles.map(({ roleId }) => ({
|
||||
userId,
|
||||
roleId,
|
||||
createdAt: now,
|
||||
})),
|
||||
);
|
||||
|
||||
await tx
|
||||
.update(userInvitation)
|
||||
.set({ acceptedUserId: userId, updatedAt: now })
|
||||
.where(eq(userInvitation.id, claimedInvitation.id));
|
||||
});
|
||||
|
||||
return { userId, email };
|
||||
}),
|
||||
}),
|
||||
|
||||
updateRoles: permissionedProcedure("users.assignRoles")
|
||||
.input(updateUserRolesSchema)
|
||||
.mutation(async ({ input }) => {
|
||||
const [existingUser] = await db.select({ id: user.id }).from(user).where(eq(user.id, input.userId)).limit(1);
|
||||
|
||||
if (!existingUser) {
|
||||
notFound("User not found");
|
||||
}
|
||||
|
||||
const uniqueRoleIds = await validateRoleIds(input.roleIds);
|
||||
|
||||
await db.delete(userRole).where(eq(userRole.userId, input.userId));
|
||||
await db.insert(userRole).values(
|
||||
uniqueRoleIds.map((roleId) => ({
|
||||
userId: input.userId,
|
||||
roleId,
|
||||
})),
|
||||
);
|
||||
await db.transaction(async (tx) => {
|
||||
await tx.execute(sql`select pg_advisory_xact_lock(612984119)`);
|
||||
|
||||
const [existingUser] = await tx
|
||||
.select({ id: user.id })
|
||||
.from(user)
|
||||
.where(eq(user.id, input.userId))
|
||||
.limit(1);
|
||||
|
||||
if (!existingUser) {
|
||||
notFound("User not found");
|
||||
}
|
||||
|
||||
const existingRoles = await tx
|
||||
.select({ roleId: userRole.roleId })
|
||||
.from(userRole)
|
||||
.where(eq(userRole.userId, input.userId));
|
||||
const removesAdmin =
|
||||
existingRoles.some(({ roleId }) => roleId === ADMIN_ROLE_ID) &&
|
||||
!uniqueRoleIds.includes(ADMIN_ROLE_ID);
|
||||
|
||||
if (removesAdmin) {
|
||||
const [adminCount] = await tx
|
||||
.select({ value: count() })
|
||||
.from(userRole)
|
||||
.where(eq(userRole.roleId, ADMIN_ROLE_ID));
|
||||
|
||||
if ((adminCount?.value ?? 0) <= 1) {
|
||||
badRequest("Minmon must always have at least one administrator");
|
||||
}
|
||||
}
|
||||
|
||||
await tx.delete(userRole).where(eq(userRole.userId, input.userId));
|
||||
await tx.insert(userRole).values(
|
||||
uniqueRoleIds.map((roleId) => ({
|
||||
userId: input.userId,
|
||||
roleId,
|
||||
})),
|
||||
);
|
||||
});
|
||||
|
||||
const updated = await getUsersWithRoles();
|
||||
return updated.find((item) => item.id === input.userId);
|
||||
}),
|
||||
|
||||
delete: permissionedProcedure("users.delete").input(byIdSchema).mutation(async ({ ctx, input }) => {
|
||||
if (ctx.session.user.id === input.id) {
|
||||
badRequest("You cannot delete your own user account while signed in");
|
||||
}
|
||||
changeInitialPassword: protectedProcedure
|
||||
.input(changeInitialPasswordSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
try {
|
||||
await auth.api.changePassword({
|
||||
body: {
|
||||
currentPassword: input.currentPassword,
|
||||
newPassword: input.newPassword,
|
||||
revokeOtherSessions: false,
|
||||
},
|
||||
headers: ctx.requestHeaders,
|
||||
});
|
||||
} catch {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message:
|
||||
"The current password is incorrect or the new password is invalid",
|
||||
});
|
||||
}
|
||||
|
||||
const [existingUser] = await db.select({ id: user.id }).from(user).where(eq(user.id, input.id)).limit(1);
|
||||
await db.transaction(async (tx) => {
|
||||
await tx
|
||||
.update(user)
|
||||
.set({ mustChangePassword: false, updatedAt: new Date() })
|
||||
.where(eq(user.id, ctx.session.user.id));
|
||||
await tx
|
||||
.delete(session)
|
||||
.where(
|
||||
and(
|
||||
eq(session.userId, ctx.session.user.id),
|
||||
ne(session.id, ctx.session.session.id),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
if (!existingUser) {
|
||||
notFound("User not found");
|
||||
}
|
||||
return { status: true };
|
||||
}),
|
||||
|
||||
await db.delete(user).where(eq(user.id, input.id));
|
||||
return { id: input.id };
|
||||
}),
|
||||
delete: permissionedProcedure("users.delete")
|
||||
.input(byIdSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
if (ctx.session.user.id === input.id) {
|
||||
badRequest("You cannot delete your own user account while signed in");
|
||||
}
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
await tx.execute(sql`select pg_advisory_xact_lock(612984119)`);
|
||||
|
||||
const [existingUser] = await tx
|
||||
.select({ id: user.id })
|
||||
.from(user)
|
||||
.where(eq(user.id, input.id))
|
||||
.limit(1);
|
||||
|
||||
if (!existingUser) {
|
||||
notFound("User not found");
|
||||
}
|
||||
|
||||
const [adminRole] = await tx
|
||||
.select({ roleId: userRole.roleId })
|
||||
.from(userRole)
|
||||
.where(
|
||||
and(
|
||||
eq(userRole.userId, input.id),
|
||||
eq(userRole.roleId, ADMIN_ROLE_ID),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (adminRole) {
|
||||
const [adminCount] = await tx
|
||||
.select({ value: count() })
|
||||
.from(userRole)
|
||||
.where(eq(userRole.roleId, ADMIN_ROLE_ID));
|
||||
|
||||
if ((adminCount?.value ?? 0) <= 1) {
|
||||
badRequest("The last administrator cannot be deleted");
|
||||
}
|
||||
}
|
||||
|
||||
await tx.delete(user).where(eq(user.id, input.id));
|
||||
});
|
||||
|
||||
return { id: input.id };
|
||||
}),
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue