refactor: update user permissions and API queries

This commit is contained in:
Mauricio Siu
2025-02-21 00:30:55 -06:00
parent 63638bde33
commit 24c9d3f7ad
5 changed files with 50 additions and 42 deletions

View File

@@ -52,7 +52,7 @@ interface Props {
export const AddUserPermissions = ({ userId }: Props) => { export const AddUserPermissions = ({ userId }: Props) => {
const { data: projects } = api.project.all.useQuery(); const { data: projects } = api.project.all.useQuery();
const { data, refetch } = api.auth.one.useQuery( const { data, refetch } = api.user.one.useQuery(
{ {
userId, userId,
}, },

View File

@@ -1,7 +1,6 @@
CREATE TABLE "user_temp" ( CREATE TABLE "user_temp" (
"id" text PRIMARY KEY NOT NULL, "id" text PRIMARY KEY NOT NULL,
"name" text DEFAULT '' NOT NULL, "name" text DEFAULT '' NOT NULL,
"token" text NOT NULL,
"isRegistered" boolean DEFAULT false NOT NULL, "isRegistered" boolean DEFAULT false NOT NULL,
"expirationDate" text NOT NULL, "expirationDate" text NOT NULL,
"createdAt" text NOT NULL, "createdAt" text NOT NULL,
@@ -82,6 +81,7 @@ CREATE TABLE "member" (
"user_id" text NOT NULL, "user_id" text NOT NULL,
"role" text NOT NULL, "role" text NOT NULL,
"created_at" timestamp NOT NULL, "created_at" timestamp NOT NULL,
"token" text NOT NULL,
"canCreateProjects" boolean DEFAULT false NOT NULL, "canCreateProjects" boolean DEFAULT false NOT NULL,
"canAccessToSSHKeys" boolean DEFAULT false NOT NULL, "canAccessToSSHKeys" boolean DEFAULT false NOT NULL,
"canCreateServices" boolean DEFAULT false NOT NULL, "canCreateServices" boolean DEFAULT false NOT NULL,
@@ -148,7 +148,6 @@ WITH inserted_users AS (
INSERT INTO user_temp ( INSERT INTO user_temp (
id, id,
email, email,
token,
"email_verified", "email_verified",
"updated_at", "updated_at",
"serverIp", "serverIp",
@@ -174,7 +173,6 @@ WITH inserted_users AS (
SELECT SELECT
a."adminId", a."adminId",
auth.email, auth.email,
COALESCE(auth.token, ''),
true, true,
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP,
a."serverIp", a."serverIp",
@@ -247,7 +245,6 @@ inserted_members AS (
INSERT INTO user_temp ( INSERT INTO user_temp (
id, id,
email, email,
token,
"email_verified", "email_verified",
"updated_at", "updated_at",
image, image,
@@ -258,7 +255,6 @@ inserted_members AS (
SELECT SELECT
u."userId", u."userId",
auth.email, auth.email,
COALESCE(u.token, ''),
true, true,
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP,
auth.image, auth.image,
@@ -302,6 +298,7 @@ inserted_admin_members AS (
"user_id", "user_id",
role, role,
"created_at", "created_at",
"token",
"canAccessToAPI", "canAccessToAPI",
"canAccessToDocker", "canAccessToDocker",
"canAccessToGitProviders", "canAccessToGitProviders",
@@ -320,6 +317,7 @@ inserted_admin_members AS (
a."adminId", a."adminId",
'owner', 'owner',
NOW(), NOW(),
COALESCE(auth.token, ''),
true, -- Los admins tienen todos los permisos por defecto true, -- Los admins tienen todos los permisos por defecto
true, true,
true, true,
@@ -333,6 +331,7 @@ inserted_admin_members AS (
'{}' '{}'
FROM admin a FROM admin a
JOIN inserted_orgs o ON o."owner_id" = a."adminId" JOIN inserted_orgs o ON o."owner_id" = a."adminId"
JOIN auth ON auth.id = a."authId"
RETURNING * RETURNING *
) )
-- Insertar miembros regulares en las organizaciones -- Insertar miembros regulares en las organizaciones
@@ -342,6 +341,7 @@ INSERT INTO member (
"user_id", "user_id",
role, role,
"created_at", "created_at",
"token",
"canAccessToAPI", "canAccessToAPI",
"canAccessToDocker", "canAccessToDocker",
"canAccessToGitProviders", "canAccessToGitProviders",
@@ -360,6 +360,7 @@ SELECT
u."userId", u."userId",
'member', 'member',
NOW(), NOW(),
COALESCE(auth.token, ''),
COALESCE(u."canAccessToAPI", false), COALESCE(u."canAccessToAPI", false),
COALESCE(u."canAccessToDocker", false), COALESCE(u."canAccessToDocker", false),
COALESCE(u."canAccessToGitProviders", false), COALESCE(u."canAccessToGitProviders", false),
@@ -373,7 +374,8 @@ SELECT
COALESCE(u."accesedServices", '{}') COALESCE(u."accesedServices", '{}')
FROM "user" u FROM "user" u
JOIN admin a ON u."adminId" = a."adminId" JOIN admin a ON u."adminId" = a."adminId"
JOIN inserted_orgs o ON o."owner_id" = a."adminId"; JOIN inserted_orgs o ON o."owner_id" = a."adminId"
JOIN auth ON auth.id = u."authId";
-- Migration tables foreign keys -- Migration tables foreign keys
@@ -411,7 +413,7 @@ ALTER TABLE "git_provider" ADD CONSTRAINT "git_provider_userId_user_temp_id_fk"
ALTER TABLE "server" ADD CONSTRAINT "server_userId_user_temp_id_fk" FOREIGN KEY ("userId") REFERENCES "public"."user_temp"("id") ON DELETE cascade ON UPDATE no action; ALTER TABLE "server" ADD CONSTRAINT "server_userId_user_temp_id_fk" FOREIGN KEY ("userId") REFERENCES "public"."user_temp"("id") ON DELETE cascade ON UPDATE no action;
ALTER TABLE "user_temp" ALTER COLUMN "token" SET DEFAULT '';--> statement-breakpoint ALTER TABLE "member" ALTER COLUMN "token" SET DEFAULT '';--> statement-breakpoint
ALTER TABLE "user_temp" ADD COLUMN "created_at" timestamp DEFAULT now(); ALTER TABLE "user_temp" ADD COLUMN "created_at" timestamp DEFAULT now();

View File

@@ -748,13 +748,6 @@
"notNull": true, "notNull": true,
"default": "''" "default": "''"
}, },
"token": {
"name": "token",
"type": "text",
"primaryKey": false,
"notNull": true,
"default": "''"
},
"isRegistered": { "isRegistered": {
"name": "isRegistered", "name": "isRegistered",
"type": "boolean", "type": "boolean",
@@ -4494,6 +4487,13 @@
"primaryKey": false, "primaryKey": false,
"notNull": true, "notNull": true,
"default": "ARRAY[]::text[]" "default": "ARRAY[]::text[]"
},
"token": {
"name": "token",
"type": "text",
"primaryKey": false,
"notNull": true,
"default": "''"
} }
}, },
"indexes": {}, "indexes": {},

View File

@@ -18,7 +18,7 @@ import {
member, member,
} from "@dokploy/server/db/schema"; } from "@dokploy/server/db/schema";
import { TRPCError } from "@trpc/server"; import { TRPCError } from "@trpc/server";
import { and, eq } from "drizzle-orm"; import { and, asc, desc, eq } from "drizzle-orm";
import { z } from "zod"; import { z } from "zod";
import { import {
adminProcedure, adminProcedure,
@@ -33,6 +33,7 @@ export const userRouter = createTRPCRouter({
with: { with: {
user: true, user: true,
}, },
orderBy: [asc(member.createdAt)],
}); });
}), }),
one: protectedProcedure one: protectedProcedure
@@ -42,14 +43,17 @@ export const userRouter = createTRPCRouter({
}), }),
) )
.query(async ({ input, ctx }) => { .query(async ({ input, ctx }) => {
const user = await findUserById(input.userId); const memberResult = await db.query.member.findFirst({
// if (user.adminId !== ctx.user.adminId) { where: and(
// throw new TRPCError({ eq(member.userId, input.userId),
// code: "UNAUTHORIZED", eq(member.organizationId, ctx.session?.activeOrganizationId || ""),
// message: "You are not allowed to access this user", ),
// }); with: {
// } user: true,
return user; },
});
return memberResult;
}), }),
get: protectedProcedure.query(async ({ ctx }) => { get: protectedProcedure.query(async ({ ctx }) => {
const memberResult = await db.query.member.findFirst({ const memberResult = await db.query.member.findFirst({
@@ -111,9 +115,12 @@ export const userRouter = createTRPCRouter({
}); });
} }
await updateUser(user.id, { await db
...input, .update(member)
}); .set({
...input,
})
.where(eq(member.userId, input.id));
} catch (error) { } catch (error) {
throw error; throw error;
} }

View File

@@ -29,7 +29,6 @@ export const users_temp = pgTable("user_temp", {
.primaryKey() .primaryKey()
.$defaultFn(() => nanoid()), .$defaultFn(() => nanoid()),
name: text("name").notNull().default(""), name: text("name").notNull().default(""),
token: text("token").notNull().default(""),
isRegistered: boolean("isRegistered").notNull().default(false), isRegistered: boolean("isRegistered").notNull().default(false),
expirationDate: text("expirationDate") expirationDate: text("expirationDate")
.notNull() .notNull()
@@ -128,16 +127,7 @@ export const usersRelations = relations(users_temp, ({ one, many }) => ({
const createSchema = createInsertSchema(users_temp, { const createSchema = createInsertSchema(users_temp, {
id: z.string().min(1), id: z.string().min(1),
token: z.string().min(1),
isRegistered: z.boolean().optional(), isRegistered: z.boolean().optional(),
// accessedProjects: z.array(z.string()).optional(),
// accessedServices: z.array(z.string()).optional(),
// canCreateProjects: z.boolean().optional(),
// canCreateServices: z.boolean().optional(),
// canDeleteProjects: z.boolean().optional(),
// canDeleteServices: z.boolean().optional(),
// canAccessToDocker: z.boolean().optional(),
// canAccessToTraefikFiles: z.boolean().optional(),
}); });
export const apiCreateUserInvitation = createSchema.pick({}).extend({ export const apiCreateUserInvitation = createSchema.pick({}).extend({
@@ -150,11 +140,7 @@ export const apiRemoveUser = createSchema
}) })
.required(); .required();
export const apiFindOneToken = createSchema export const apiFindOneToken = createSchema.pick({}).required();
.pick({
token: true,
})
.required();
export const apiAssignPermissions = createSchema export const apiAssignPermissions = createSchema
.pick({ .pick({
@@ -171,6 +157,19 @@ export const apiAssignPermissions = createSchema
// canAccessToSSHKeys: true, // canAccessToSSHKeys: true,
// canAccessToGitProviders: true, // canAccessToGitProviders: true,
}) })
.extend({
accessedProjects: z.array(z.string()).optional(),
accessedServices: z.array(z.string()).optional(),
canCreateProjects: z.boolean().optional(),
canCreateServices: z.boolean().optional(),
canDeleteProjects: z.boolean().optional(),
canDeleteServices: z.boolean().optional(),
canAccessToDocker: z.boolean().optional(),
canAccessToTraefikFiles: z.boolean().optional(),
canAccessToAPI: z.boolean().optional(),
canAccessToSSHKeys: z.boolean().optional(),
canAccessToGitProviders: z.boolean().optional(),
})
.required(); .required();
export const apiFindOneUser = createSchema export const apiFindOneUser = createSchema