This repository has been archived on 2024-09-23. You can view files and clone it, but cannot push or open issues or pull requests.
rocketchat-scim/GroupEndpoint.ts
2022-02-15 13:38:33 +01:00

81 lines
2.9 KiB
TypeScript

import { HttpStatusCode } from "@rocket.chat/apps-engine/definition/accessors";
import { IApiResponse } from "@rocket.chat/apps-engine/definition/api";
import { Context } from "./Context";
import { SCIMGroup } from "./scim/Group";
import { SCIMUser } from "./scim/User";
import { IScimEndpoint, ScimEndpoint } from "./ScimEndpoint";
export class GroupEndpoint extends ScimEndpoint implements IScimEndpoint {
public path = "Groups/:id";
public async _get(ctx: Context): Promise<IApiResponse> {
const getTeamInfo = async () => {
const teamRaw = await ctx.rc.team.info(ctx.id());
this.handleError(teamRaw);
return teamRaw.teamInfo;
};
const getTeamMembers = async () => {
const membersRaw = await ctx.rc.team.members(ctx.id());
this.handleError(membersRaw);
return membersRaw.members;
};
const teamArgs = await Promise.all([getTeamInfo(), getTeamMembers()]);
const group = SCIMGroup.fromRC(...teamArgs);
return this.success(group);
}
public async _put(ctx: Context): Promise<IApiResponse> {
const membersRaw = await ctx.rc.team.members(ctx.id());
this.handleError(membersRaw);
const targetIds = new Set<string>(
SCIMGroup.fromPlain(ctx.content()).members.map((x) => x.value),
);
const currentIds = new Set<string>(
membersRaw.members.map((x: ITeamMember) => x.user._id),
);
const removeMember = async (userId: string) => {
const removeMembersRaw = await ctx.rc.team.removeMember({
userId,
teamId: ctx.id(),
});
this.handleError(removeMembersRaw);
};
const addMembers = async (userIds: Array<string>) => {
const addMembersRaw = await ctx.rc.team.addMembers({
teamId: ctx.id(),
members: userIds.map((userId) => ({
userId,
roles: ["member"],
})),
});
this.handleError(addMembersRaw);
};
const promises: Array<Promise<void>> = [];
for (const currentId of currentIds) {
if (!targetIds.has(currentId)) {
promises.push(removeMember(currentId));
}
}
const addMemberIds: Array<string> = [];
for (const targetId of targetIds) {
if (!currentIds.has(targetId)) {
addMemberIds.push(targetId);
}
}
if (addMemberIds.length > 0) {
promises.push(addMembers(addMemberIds));
}
await Promise.all(promises);
return this._get(ctx);
}
public async _delete(ctx: Context): Promise<IApiResponse> {
const o = await ctx.rc.team.delete({ teamId: ctx.id() });
this.handleError(o);
return this.response({
status: HttpStatusCode.NO_CONTENT,
});
}
}