Skip to content

Commit

Permalink
🐛 Check permission for API update user
Browse files Browse the repository at this point in the history
  • Loading branch information
lethemanh committed Jan 22, 2025
1 parent ac8b777 commit 4210974
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
21 changes: 20 additions & 1 deletion tdrive/backend/node/src/services/user/web/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import gr from "../../global-resolver";
import config from "config";
import { getLogger } from "../../../core/platform/framework";
import { UpdateUser } from "../services/users/types";
import { hasCompanyAdminLevel } from "../../../utils/company";

export class UsersCrudController
implements
Expand Down Expand Up @@ -372,9 +373,27 @@ export class UsersCrudController
request: FastifyRequest<{ Body: UpdateUser; Params: UserParameters }>,
reply: FastifyReply,
): Promise<ResourceCreateResponse<UserObject>> {
const id = request.params.id;
const context = getExecutionContext(request);

const id = request.params.id;
const [currentUserCompanies, requestedUserCompanies] = await Promise.all(
[context.user.id, request.params.id].map(userId =>
gr.services.users.getUserCompanies({ id: userId }),
),
);
const currentUserCompaniesIds = new Set(currentUserCompanies.map(a => a.group_id));
const sameCompanies = requestedUserCompanies.filter(a =>
currentUserCompaniesIds.has(a.group_id),
);
const roles = await Promise.all(
sameCompanies.map(a => gr.services.companies.getUserRole(a.group_id, context.user?.id)),
);

if (!roles.some(role => hasCompanyAdminLevel(role) === true)) {
reply.unauthorized(`User ${context.user?.id} is not allowed to update user ${id}`);
return;
}

const user = await gr.services.users.get({ id });
if (!user) {
reply.notFound(`User ${id} not found`);
Expand Down
2 changes: 1 addition & 1 deletion tdrive/backend/node/src/services/user/web/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ const routes: FastifyPluginCallback = (fastify: FastifyInstance, options, next)
fastify.route({
method: "PUT",
url: `${usersUrl}/:id`,
preValidation: [fastify.authenticateOptional],
preValidation: [fastify.authenticate],
handler: usersController.update.bind(usersController),
});

Expand Down

0 comments on commit 4210974

Please sign in to comment.