Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Invitation revocation sId refactor #4562

Merged
merged 2 commits into from
Apr 4, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 59 additions & 36 deletions front/lib/api/invitation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type {
UserType,
WorkspaceType,
} from "@dust-tt/types";
import { sanitizeString } from "@dust-tt/types";
import { Err, sanitizeString } from "@dust-tt/types";
import sgMail from "@sendgrid/mail";
import { sign } from "jsonwebtoken";

Expand All @@ -19,13 +19,70 @@ function typeFromModel(
invitation: MembershipInvitation
): MembershipInvitationType {
return {
sId: invitation.sId,
id: invitation.id,
inviteEmail: invitation.inviteEmail,
status: invitation.status,
initialRole: invitation.initialRole,
};
}

export async function getInvitation({
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we extract auth from the object?

auth,
invitationId,
}: {
auth: Authenticator;
invitationId: string;
}): Promise<MembershipInvitationType | null> {
const owner = auth.workspace();
if (!owner || !auth.isAdmin()) {
return null;
}

const invitation = await MembershipInvitation.findOne({
where: {
workspaceId: owner.id,
sId: invitationId,
},
});

if (!invitation) {
return null;
}

return typeFromModel(invitation);
}

export async function updateInvitationStatus({
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here?

auth,
invitation,
status,
}: {
auth: Authenticator;
invitation: MembershipInvitationType;
status: "pending" | "consumed" | "revoked";
}): Promise<MembershipInvitationType> {
const owner = auth.workspace();
if (!owner || !auth.isAdmin()) {
throw new Error("Unauthorized attempt to update invitation status.");
}

const existingInvitation = await MembershipInvitation.findOne({
where: {
workspaceId: owner.id,
id: invitation.id,
},
});

if (!existingInvitation) {
throw new Err("Invitaion unexpectedly not found.");
}

await existingInvitation.update({ status });

return typeFromModel(existingInvitation);
}

export async function updateOrCreateInvitation(
owner: WorkspaceType,
inviteEmail: string,
Expand Down Expand Up @@ -58,41 +115,6 @@ export async function updateOrCreateInvitation(
);
}

export async function updateInvitation(
owner: WorkspaceType,
id: number,
status: "pending" | "consumed" | "revoked"
): Promise<MembershipInvitationType> {
const invitation = await MembershipInvitation.findOne({
where: {
id,
workspaceId: owner.id,
},
});

if (!invitation) {
throw new Error("Invitation not found");
}

await invitation.update({
status,
});

return typeFromModel(invitation);
}

export async function deleteInvitation(
owner: WorkspaceType,
id: number
): Promise<void> {
await MembershipInvitation.destroy({
where: {
id,
workspaceId: owner.id,
},
});
}

export async function sendWorkspaceInvitationEmail(
owner: WorkspaceType,
user: UserType,
Expand Down Expand Up @@ -146,6 +168,7 @@ export async function getPendingInvitations(

return invitations.map((i) => {
return {
sId: i.sId,
id: i.id,
status: i.status,
inviteEmail: i.inviteEmail,
Expand Down
2 changes: 1 addition & 1 deletion front/lib/models/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ User.init(
},
sId: {
type: DataTypes.STRING,
allowNull: true,
allowNull: false,
},
provider: {
type: DataTypes.STRING,
Expand Down
2 changes: 1 addition & 1 deletion front/lib/models/workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ MembershipInvitation.init(
},
sId: {
type: DataTypes.STRING,
allowNull: true,
allowNull: false,
},
inviteEmail: {
type: DataTypes.STRING,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,26 @@ import type {
MembershipInvitationType,
WithAPIErrorReponse,
} from "@dust-tt/types";
import { isLeft } from "fp-ts/lib/Either";
import * as t from "io-ts";
import * as reporter from "io-ts-reporters";
import type { NextApiRequest, NextApiResponse } from "next";

import { getInvitation, updateInvitationStatus } from "@app/lib/api/invitation";
import { Authenticator, getSession } from "@app/lib/auth";
import { MembershipInvitation } from "@app/lib/models";
import { apiError, withLogging } from "@app/logger/withlogging";

export type GetMemberInvitationsResponseBody = {
invitations: MembershipInvitationType[];
export type PostMemberInvitationsResponseBody = {
invitation: MembershipInvitationType;
};

export const PostMemberInvitationBodySchema = t.type({
status: t.literal("revoked"),
});

async function handler(
req: NextApiRequest,
res: NextApiResponse<WithAPIErrorReponse<GetMemberInvitationsResponseBody>>
res: NextApiResponse<WithAPIErrorReponse<PostMemberInvitationsResponseBody>>
): Promise<void> {
const session = await getSession(req, res);
const auth = await Authenticator.fromSession(
Expand Down Expand Up @@ -44,8 +51,19 @@ async function handler(
});
}

const invitationId = parseInt(req.query.invitationId as string);
if (isNaN(invitationId)) {
if (!(typeof req.query.iId === "string")) {
return apiError(req, res, {
status_code: 400,
api_error: {
type: "invalid_request_error",
message: "Invalid query parameters, `iId` (string) is required.",
},
});
}

const invitationId = req.query.iId;
let invitation = await getInvitation({ auth, invitationId });
if (!invitation) {
return apiError(req, res, {
status_code: 404,
api_error: {
Expand All @@ -57,47 +75,27 @@ async function handler(

switch (req.method) {
case "POST":
if (
!req.body ||
!typeof (req.body.status === "string") ||
// For now we only allow revoking invitations.
req.body.status !== "revoked"
) {
const bodyValidation = PostMemberInvitationBodySchema.decode(req.body);
if (isLeft(bodyValidation)) {
const pathError = reporter.formatValidationErrors(bodyValidation.left);
return apiError(req, res, {
status_code: 400,
api_error: {
type: "invalid_request_error",
message:
'The request body is invalid, expects { status: "revoked" }.',
message: `The request body is invalid: ${pathError}`,
},
});
}
const body = bodyValidation.right;

const invitation = await MembershipInvitation.findOne({
where: { id: invitationId },
invitation = await updateInvitationStatus({
auth,
invitation,
status: body.status,
});

if (!invitation) {
return apiError(req, res, {
status_code: 404,
api_error: {
type: "invitation_not_found",
message: "The invitation requested was not found.",
},
});
}

invitation.status = req.body.status;
await invitation.save();
res.status(200).json({
invitations: [
{
id: invitation.id,
status: invitation.status,
inviteEmail: invitation.inviteEmail,
initialRole: invitation.initialRole,
},
],
invitation,
});
return;

Expand Down
2 changes: 1 addition & 1 deletion front/pages/w/[wId]/members/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -809,7 +809,7 @@ function RevokeInvitationModal({
invitation: MembershipInvitationType
): Promise<void> {
const res = await fetch(
`/api/w/${owner.sId}/invitations/${invitation.id}`,
`/api/w/${owner.sId}/invitations/${invitation.sId}`,
{
method: "POST",
headers: {
Expand Down
1 change: 1 addition & 0 deletions types/src/front/membership_invitation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { ModelId } from "../shared/model_id";
import { ActiveRoleType } from "./user";

export type MembershipInvitationType = {
sId: string;
id: ModelId;
status: "pending" | "consumed" | "revoked";
inviteEmail: string;
Expand Down
Loading