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

Remove userId from MembershipResource interface #4570

Merged
merged 4 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
3 changes: 2 additions & 1 deletion front/admin/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
import { MembershipResource } from "@app/lib/resources/membership_resource";
import { generateModelSId } from "@app/lib/utils";
import logger from "@app/logger/logger";
import { renderUserType } from "@app/lib/api/user";

const { DUST_DATA_SOURCES_BUCKET = "", SERVICE_ACCOUNT } = process.env;

Expand Down Expand Up @@ -127,7 +128,7 @@ const user = async (command: string, args: parseArgs.ParsedArgs) => {
console.log(` email: ${u.email}`);

const memberships = await MembershipResource.getLatestMemberships({
userIds: [u.id],
users: [renderUserType(u)],
});

const workspaces = await Workspace.findAll({
Expand Down
16 changes: 8 additions & 8 deletions front/lib/amplitude/node/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import type {
AgentConfigurationType,
AgentMessageType,
DataSourceType,
ModelId,
UserMessageType,
UserType,
WorkspaceType,
Expand All @@ -25,7 +24,7 @@ import {
import { isGlobalAgentId } from "@app/lib/api/assistant/global_agents";
import type { Authenticator } from "@app/lib/auth";
import { subscriptionForWorkspace } from "@app/lib/auth";
import { User, Workspace } from "@app/lib/models";
import { Workspace } from "@app/lib/models";
import { countActiveSeatsInWorkspace } from "@app/lib/plans/workspace_usage";
import { MembershipResource } from "@app/lib/resources/membership_resource";

Expand All @@ -52,12 +51,13 @@ export function getBackendClient() {
return BACKEND_CLIENT;
}

export async function trackUserMemberships(userId: ModelId) {
export async function trackUserMemberships(user: UserType) {
const amplitude = getBackendClient();
const user = await User.findByPk(userId);
const memberships = await MembershipResource.getActiveMemberships({
userIds: [userId],
});
const memberships = user
? await MembershipResource.getActiveMemberships({
users: [user],
})
: [];
const groups: string[] = [];
for (const membership of memberships) {
const workspace = await Workspace.findByPk(membership.workspaceId);
Expand All @@ -70,7 +70,7 @@ export async function trackUserMemberships(userId: ModelId) {
}
if (groups.length > 0) {
amplitude.client.setGroup(GROUP_TYPE, groups, {
user_id: `user-${userId}`,
user_id: `user-${user.id}`,
});
}
}
Expand Down
23 changes: 12 additions & 11 deletions front/lib/api/assistant/recent_authors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@ import type {
AgentRecentAuthors,
LightAgentConfigurationType,
UserType,
UserTypeWithWorkspaces,
} from "@dust-tt/types";
import { removeNulls } from "@dust-tt/types";
import { Sequelize } from "sequelize";

import { getMembers } from "@app/lib/api/workspace";
import type { Authenticator } from "@app/lib/auth";
import { AgentConfiguration } from "@app/lib/models";
import { AgentConfiguration, User } from "@app/lib/models";
import { safeRedisClient } from "@app/lib/redis";
import { renderUserType } from "@app/lib/user";

// We keep the most recent authorIds for 3 days.
const recentAuthorIdsKeyTTL = 60 * 60 * 24 * 3; // 3 days.
Expand Down Expand Up @@ -173,14 +172,16 @@ export async function getAgentsRecentAuthors({
{}
);

const authorByUserId: Record<number, UserTypeWithWorkspaces> = (
await getMembers(auth, {
userIds: removeNulls(
Array.from(new Set(Object.values(recentAuthorsIdsByAgentId).flat()))
),
const authorByUserId: Record<number, UserType> = (
await User.findAll({
where: {
id: removeNulls(
Array.from(new Set(Object.values(recentAuthorsIdsByAgentId).flat()))
),
},
})
).reduce<Record<number, UserTypeWithWorkspaces>>((acc, member) => {
acc[member.id] = member;
).reduce<Record<number, UserType>>((acc, user) => {
acc[user.id] = renderUserType(user);
return acc;
}, {});

Expand All @@ -190,7 +191,7 @@ export async function getAgentsRecentAuthors({
return [DUST_OWNED_ASSISTANTS_AUTHOR_NAME];
}
return renderAuthors(
recentAuthorIds.map((id) => authorByUserId[id]),
removeNulls(recentAuthorIds.map((id) => authorByUserId[id])),
currentUserId
);
});
Expand Down
38 changes: 25 additions & 13 deletions front/lib/api/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,21 @@ import { User, UserMetadata } from "@app/lib/models";

import { MembershipResource } from "../resources/membership_resource";

export function renderUserType(user: User): UserType {
return {
sId: user.sId,
id: user.id,
createdAt: user.createdAt.getTime(),
provider: user.provider,
username: user.username,
email: user.email,
firstName: user.firstName,
lastName: user.lastName,
fullName: user.firstName + (user.lastName ? ` ${user.lastName}` : ""),
image: user.imageUrl,
};
}

/**
* This function checks that the user had at least one membership in the past for this workspace
* otherwise returns null, preventing retrieving user information from their sId.
Expand All @@ -30,26 +45,23 @@ export async function getUserForWorkspace(

const membership =
await MembershipResource.getLatestMembershipOfUserInWorkspace({
userId: user.id,
user: renderUserType(user),
workspace: owner,
});

if (!membership) {
return null;
}

return {
sId: user.sId,
id: user.id,
createdAt: user.createdAt.getTime(),
provider: user.provider,
username: user.username,
email: user.email,
firstName: user.firstName,
lastName: user.lastName,
fullName: user.firstName + (user.lastName ? ` ${user.lastName}` : ""),
image: user.imageUrl,
};
return renderUserType(user);
}

export async function deleteUser(user: UserType): Promise<void> {
await User.destroy({
where: {
id: user.id,
},
});
}

/**
Expand Down
4 changes: 0 additions & 4 deletions front/lib/api/workspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,11 +105,9 @@ export async function getMembers(
{
roles,
activeOnly,
userIds,
}: {
roles?: MembershipRoleType[];
activeOnly?: boolean;
userIds?: ModelId[];
} = {}
): Promise<UserTypeWithWorkspaces[]> {
const owner = auth.workspace();
Expand All @@ -121,12 +119,10 @@ export async function getMembers(
? await MembershipResource.getActiveMemberships({
workspace: owner,
roles,
userIds,
})
: await MembershipResource.getLatestMemberships({
workspace: owner,
roles,
userIds,
});

const users = await User.findAll({
Expand Down
23 changes: 4 additions & 19 deletions front/lib/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import type {
NextApiResponse,
} from "next";

import { renderUserType } from "@app/lib/api/user";
import { isDevelopment } from "@app/lib/development";
import type { SessionWithUser } from "@app/lib/iam/provider";
import { isValidSession } from "@app/lib/iam/provider";
Expand All @@ -37,14 +38,13 @@ import {
import type { PlanAttributes } from "@app/lib/plans/free_plans";
import { FREE_NO_PLAN_DATA } from "@app/lib/plans/free_plans";
import { isUpgraded } from "@app/lib/plans/plan_codes";
import { renderSubscriptionFromModels } from "@app/lib/plans/subscription";
import { getTrialVersionForPlan, isTrial } from "@app/lib/plans/trial";
import { MembershipResource } from "@app/lib/resources/membership_resource";
import { new_id } from "@app/lib/utils";
import { renderLightWorkspaceType } from "@app/lib/workspace";
import logger from "@app/logger/logger";

import { renderSubscriptionFromModels } from "./plans/subscription";

const {
DUST_DEVELOPMENT_WORKSPACE_ID,
DUST_DEVELOPMENT_SYSTEM_API_KEY,
Expand Down Expand Up @@ -132,7 +132,7 @@ export class Authenticator {
(async (): Promise<RoleType> => {
const membership =
await MembershipResource.getActiveMembershipOfUserInWorkspace({
userId: user.id,
user: renderUserType(user),
workspace: renderLightWorkspaceType({ workspace }),
});
return membership &&
Expand Down Expand Up @@ -424,22 +424,7 @@ export class Authenticator {
* @returns
*/
user(): UserType | null {
return this._user
? {
sId: this._user.sId,
id: this._user.id,
createdAt: this._user.createdAt.getTime(),
provider: this._user.provider,
username: this._user.username,
email: this._user.email,
fullName:
this._user.firstName +
(this._user.lastName ? ` ${this._user.lastName}` : ""),
firstName: this._user.firstName,
lastName: this._user.lastName || null,
image: this._user.imageUrl,
}
: null;
return this._user ? renderUserType(this._user) : null;
}

isDustSuperUser(): boolean {
Expand Down
5 changes: 2 additions & 3 deletions front/lib/iam/invitations.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import type { Result } from "@dust-tt/types";
import type { Result, UserType } from "@dust-tt/types";
import { Err, Ok } from "@dust-tt/types";
import { verify } from "jsonwebtoken";

import { AuthFlowError } from "@app/lib/iam/errors";
import type { User } from "@app/lib/models";
import { MembershipInvitation } from "@app/lib/models";

const { DUST_INVITE_TOKEN_SECRET = "" } = process.env;
Expand Down Expand Up @@ -38,7 +37,7 @@ export async function getPendingMembershipInvitationForToken(

export async function markInvitationAsConsumed(
membershipInvite: MembershipInvitation,
user: User
user: UserType
) {
membershipInvite.status = "consumed";
membershipInvite.invitedUserId = user.id;
Expand Down
3 changes: 2 additions & 1 deletion front/lib/iam/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type {
} from "next";
import type { ParsedUrlQuery } from "querystring";

import { renderUserType } from "@app/lib/api/user";
import { Authenticator, getSession } from "@app/lib/auth";
import type { SessionWithUser } from "@app/lib/iam/provider";
import { isValidSession } from "@app/lib/iam/provider";
Expand Down Expand Up @@ -37,7 +38,7 @@ export async function getUserFromSession(
}

const memberships = await MembershipResource.getActiveMemberships({
userIds: [user.id],
users: [renderUserType(user)],
});
const workspaces = await Workspace.findAll({
where: {
Expand Down
7 changes: 4 additions & 3 deletions front/lib/iam/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { UserProviderType, UserType } from "@dust-tt/types";
import { sanitizeString } from "@dust-tt/types";

import { trackSignup } from "@app/lib/amplitude/node";
import { renderUserType } from "@app/lib/api/user";
import type { ExternalUser, SessionWithUser } from "@app/lib/iam/provider";
import { User } from "@app/lib/models/user";
import { guessFirstandLastNameFromFullName } from "@app/lib/user";
Expand Down Expand Up @@ -94,7 +95,7 @@ export async function maybeUpdateFromExternalUser(

export async function createOrUpdateUser(
session: SessionWithUser
): Promise<{ user: User; created: boolean }> {
): Promise<{ user: UserType; created: boolean }> {
const { user: externalUser } = session;

const user = await fetchUserFromSession(session);
Expand Down Expand Up @@ -124,7 +125,7 @@ export async function createOrUpdateUser(

await user.save();

return { user, created: false };
return { user: renderUserType(user), created: false };
} else {
const { firstName, lastName } = guessFirstandLastNameFromFullName(
externalUser.name
Expand Down Expand Up @@ -154,6 +155,6 @@ export async function createOrUpdateUser(
fullName: u.name,
} satisfies UserType);

return { user: u, created: true };
return { user: renderUserType(u), created: true };
}
}
Loading
Loading