feat: New Organization Schema along with the ability to invite existing users to an organization (#13002)
* Add profile table Copy to profile table Update schema Migrations * wip * Get switcher working * Add organization seeder * wip * Remove dead code * Fix unit tests * relevantProfile -> profile * cache bust * One more comment * Squash migrations * Copy to profile table * Update schema * Fix existing user invite flow * Add profile table * Copy to profile table * Update schema * Format * Add profile table Copy to profile table Update schema Migrations * Format * wip Get switcher working Add organization seeder wip Remove dead code Fix unit tests relevantProfile -> profile cache bust One more comment Squash migrations Copy to profile table Update schema Fix existing user invite flow Add profile table Copy to profile table Update schema chore: small improvements to signup (#13227) * removed features on mobile, better background color * nit * dark mode nits New Crowdin translations by Github Action fix: event reschedule workflow trigger (#13122) * fix event reschedule workflow trigger * uncomment previously failed test * review fix --------- Co-authored-by: Joe Au-Yeung <[email protected]> Co-authored-by: CarinaWolli <[email protected]> chore: added community support to help (#13213) refactor: Abstract `handleSeats` from `handleNewBooking` (#12062) * Refactor createBooking * Type fix * Abstract handleSeats * Create Invitee type * Create OrganizerUser type * Abstract addVideoCallDataToEvt * Abstract createLoggerWithEventDetails * Abstract `handleAppStatus` from handler * Create ReqAppsStatus type * Move `deleteMeeting` and `getCalendar` * Set parameters for `handleSeats` * Typescript refactor * Change function params from req * Type fix --------- Co-authored-by: Morgan <[email protected]> Co-authored-by: Erik <[email protected]> fix: Dynamic group booking org-migration redirect (#13223) * fix: Dynamic group booking redirect * Fix flaky private team test test: Check availability tab and all your functions (teste2e-availability) (#12434) * add changes * add changes * add changes * add changes * Requested changes * Change way to grab element --------- Co-authored-by: gitstart-calcom <[email protected]> Co-authored-by: gitstart-calcom <[email protected]> Co-authored-by: Morgan <[email protected]> Co-authored-by: Keith Williams <[email protected]> Co-authored-by: Joe Au-Yeung <[email protected]> fix: Reschedule a cancelled booking (#13170) * fix: Reschedule a cancelled booking * canceled instead of cancelled --------- Co-authored-by: Joe Au-Yeung <[email protected]> Co-authored-by: Carina Wollendorfer <[email protected]> v3.7.0 test: In Team Event type when location is Organizer Default App and U… (#12939) * test: In Team Event type when location is Organizer Default App and User Metadata is emoty * chore: use variable * fix: type error test: add test for invalid cal video (#13103) * test: add test for invalid cal video * chore: add confirm * chore: fix type error * chore: update code * test: add unit test * chore: type error * chore * chore: type * chore: fix test * chore --------- Co-authored-by: Carina Wollendorfer <[email protected]> chore: add error message for no availability (#13230) * chore: add error message for no default user availability * chore: check only availability * chore: change message * chore: add eventType fix: Team revert with members (#13228) refactor: Refactor seats logic (#12905) * Refactor createBooking * Type fix * Abstract handleSeats * Create Invitee type * Create OrganizerUser type * Abstract addVideoCallDataToEvt * Abstract createLoggerWithEventDetails * Abstract `handleAppStatus` from handler * Create ReqAppsStatus type * Move `deleteMeeting` and `getCalendar` * Set parameters for `handleSeats` * Typescript refactor * Change function params from req * Type fix * Move handleSeats * Abstract lastAttendeeDeleteBooking * Create function for rescheduling seated events * Fix imports on reschedule seats function * Fix imports * Import handleSeats function * Fix rescheduleUid type * Refactor owner reschedule to new time slot * Refactor combine two booking times together * Reschedule as an attendee * Refactor createNewSeat * Remove old handleSeats * Remove lastAttendeeDeleteBooking from handleNewBooking * Test for new attendee right params are passed * Unit test params for reschedule * Typo fix * Clean up * Create new seat test * Test when attendee already signs up for booking * Type fix * Test reschedule move attendee to existing booking * On reschedule create new booking * Test on last attendee cancel booking * Owner reschedule to new time slot * Owner rescheduling, merge two bookings together * Test: when merging more than available seats, then fail * Test: fail when event is full * Remove duplicate E2E tests * Clean up * Rename `addVideoCallDataToEvt` to `addVideoCallDataToEvent` * Refactor `calcAppsStatus` * Assign `evt` to resutl of `addVideoCallDataToEvent` * Use prisma.transaction when moving attendees * Clean create seat call * Use ErrorCode enum * Use attendeeRescheduledSeatedBooking function * Await function * Prevent double triggering of workflows * Use inviteeToAdd in createNewSeat * Remove unused error code * Remove old handleSeats file * Type fix * Type fix * Type fix * Type fix * Type fix * Type fix * Type fix * Type fix --------- Co-authored-by: Morgan <[email protected]> Co-authored-by: Peer Richelsen <[email protected]> Co-authored-by: Erik <[email protected]> feat: Allow admins to filter bookings only by attendee emails (#13236) * chore: Allow admins to filter bookings only by attendee emails * Fix type error Fixed [CAL-2930] Org branding isnt centered in shell #13225 (#13237) Add profile table Copy to profile table Update schema Migrations Format * wip * Add profile relation everywhere * Fix schema * Fix invite handler * Add profileId during eventTypec reation * Get dashboard working with profile relatioon * Add workflow create repository * Add profileId to host * Add profileId to credential table * Add destinationCalendar repository * Add profileId to membership * Revert all profile related changes * Add acme and dunder * Fix membership profileId usgae * Various fixes * Some renaming * Fix failing tests * Debugging next-aut * Consolidate migrations * Testing fixes * Fix unit tests * Self review feedback * PR feedback * Fix orgMigration as well * Add profile schema and copy users to it * Remove migrations from here * Fix type issues * Fix type error after main merge * Remove movedFromUserId * Add missing migration file * Self review addressed * Joe's review addressed * Fix profile switcher --------- Co-authored-by: Joe Au-Yeung <[email protected]>
This commit is contained in:
178 files changed
+4091
-1262
No files matched your search
@@ -5,8 +5,12 @@ import { getToken } from "next-auth/jwt";
|
||||
|
||||
import checkLicense from "@calcom/features/ee/common/server/checkLicense";
|
||||
import { CAL_URL } from "@calcom/lib/constants";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import prisma from "@calcom/prisma";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["getServerSession"] });
|
||||
/**
|
||||
* Stores the session in memory using the stringified token as the key.
|
||||
*
|
||||
@@ -29,6 +33,7 @@ export async function getServerSession(options: {
|
||||
res?: NextApiResponse | GetServerSidePropsContext["res"];
|
||||
authOptions?: AuthOptions;
|
||||
}) {
|
||||
log.debug("Getting server session");
|
||||
const { req, authOptions: { secret } = {} } = options;
|
||||
|
||||
const token = await getToken({
|
||||
@@ -37,6 +42,7 @@ export async function getServerSession(options: {
|
||||
});
|
||||
|
||||
if (!token || !token.email || !token.sub) {
|
||||
log.debug("Couldnt get token");
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -46,7 +52,7 @@ export async function getServerSession(options: {
|
||||
return cachedSession;
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
const userFromDb = await prisma.user.findUnique({
|
||||
where: {
|
||||
email: token.email.toLowerCase(),
|
||||
},
|
||||
@@ -54,12 +60,29 @@ export async function getServerSession(options: {
|
||||
// cacheStrategy: { ttl: 60, swr: 1 },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
if (!userFromDb) {
|
||||
log.debug("No user found");
|
||||
return null;
|
||||
}
|
||||
|
||||
const hasValidLicense = await checkLicense(prisma);
|
||||
|
||||
let upId = token.upId;
|
||||
|
||||
if (!upId) {
|
||||
upId = `usr-${userFromDb.id}`;
|
||||
}
|
||||
|
||||
if (!upId) {
|
||||
log.error("No upId found for session", { userId: userFromDb.id });
|
||||
return null;
|
||||
}
|
||||
|
||||
const user = await UserRepository.enrichUserWithTheProfile({
|
||||
user: userFromDb,
|
||||
upId,
|
||||
});
|
||||
|
||||
const session: Session = {
|
||||
hasValidLicense,
|
||||
expires: new Date(typeof token.exp === "number" ? token.exp * 1000 : Date.now()).toISOString(),
|
||||
@@ -75,7 +98,10 @@ export async function getServerSession(options: {
|
||||
belongsToActiveTeam: token.belongsToActiveTeam,
|
||||
org: token.org,
|
||||
locale: user.locale ?? undefined,
|
||||
profile: user.profile,
|
||||
},
|
||||
profileId: token.profileId,
|
||||
upId,
|
||||
};
|
||||
|
||||
if (token?.impersonatedBy?.id) {
|
||||
@@ -98,5 +124,6 @@ export async function getServerSession(options: {
|
||||
|
||||
CACHE.set(JSON.stringify(token), session);
|
||||
|
||||
log.debug("Returned session", safeStringify(session));
|
||||
return session;
|
||||
}
|
||||
@@ -75,21 +75,5 @@ export default function CalComAdapter(prismaClient: PrismaClient) {
|
||||
// @NOTE: All methods below here are not being used but leaved if they are required
|
||||
unlinkAccount: (provider_providerAccountId: Prisma.AccountProviderProviderAccountIdCompoundUniqueInput) =>
|
||||
prismaClient.account.delete({ where: { provider_providerAccountId } }),
|
||||
async getSessionAndUser(sessionToken: string) {
|
||||
const userAndSession = await prismaClient.session.findUnique({
|
||||
where: { sessionToken },
|
||||
include: { user: true },
|
||||
});
|
||||
if (!userAndSession) return null;
|
||||
const { user, ...session } = userAndSession;
|
||||
return { user, session };
|
||||
},
|
||||
createSession: (data: Prisma.SessionCreateInput) => prismaClient.session.create({ data }),
|
||||
updateSession: (data: Prisma.SessionUpdateInput) =>
|
||||
prismaClient.session.update({
|
||||
where: { sessionToken: typeof data.sessionToken === "string" ? data.sessionToken : undefined },
|
||||
data,
|
||||
}),
|
||||
deleteSession: (sessionToken: string) => prismaClient.session.delete({ where: { sessionToken } }),
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { Membership, Team, UserPermissionRole } from "@prisma/client";
|
||||
import type { AuthOptions, Session } from "next-auth";
|
||||
import type { JWT } from "next-auth/jwt";
|
||||
import { encode } from "next-auth/jwt";
|
||||
import type { Provider } from "next-auth/providers";
|
||||
import CredentialsProvider from "next-auth/providers/credentials";
|
||||
@@ -11,11 +12,15 @@ import ImpersonationProvider from "@calcom/features/ee/impersonation/lib/Imperso
|
||||
import { getOrgFullOrigin, subdomainSuffix } from "@calcom/features/ee/organizations/lib/orgDomains";
|
||||
import { clientSecretVerifier, hostedCal, isSAMLLoginEnabled } from "@calcom/features/ee/sso/lib/saml";
|
||||
import { checkRateLimitAndThrowError } from "@calcom/lib/checkRateLimitAndThrowError";
|
||||
import { IS_TEAM_BILLING_ENABLED, WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { ENABLE_PROFILE_SWITCHER, IS_TEAM_BILLING_ENABLED, WEBAPP_URL } from "@calcom/lib/constants";
|
||||
import { symmetricDecrypt, symmetricEncrypt } from "@calcom/lib/crypto";
|
||||
import { defaultCookies } from "@calcom/lib/default-cookies";
|
||||
import { isENVDev } from "@calcom/lib/env";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { randomString } from "@calcom/lib/random";
|
||||
import { safeStringify } from "@calcom/lib/safeStringify";
|
||||
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
|
||||
import { UserRepository } from "@calcom/lib/server/repository/user";
|
||||
import slugify from "@calcom/lib/slugify";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { IdentityProvider, MembershipRole } from "@calcom/prisma/enums";
|
||||
@@ -26,6 +31,7 @@ import { isPasswordValid } from "./isPasswordValid";
|
||||
import CalComAdapter from "./next-auth-custom-adapter";
|
||||
import { verifyPassword } from "./verifyPassword";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["next-auth-options"] });
|
||||
const GOOGLE_API_CREDENTIALS = process.env.GOOGLE_API_CREDENTIALS || "{}";
|
||||
const { client_id: GOOGLE_CLIENT_ID, client_secret: GOOGLE_CLIENT_SECRET } =
|
||||
JSON.parse(GOOGLE_API_CREDENTIALS)?.web || {};
|
||||
@@ -100,38 +106,7 @@ const providers: Provider[] = [
|
||||
throw new Error(ErrorCode.InternalServerError);
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: {
|
||||
email: credentials.email.toLowerCase(),
|
||||
},
|
||||
select: {
|
||||
locked: true,
|
||||
role: true,
|
||||
id: true,
|
||||
username: true,
|
||||
name: true,
|
||||
email: true,
|
||||
metadata: true,
|
||||
identityProvider: true,
|
||||
password: true,
|
||||
organizationId: true,
|
||||
twoFactorEnabled: true,
|
||||
twoFactorSecret: true,
|
||||
backupCodes: true,
|
||||
locale: true,
|
||||
organization: {
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
teams: {
|
||||
include: {
|
||||
team: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const user = await UserRepository.findByEmailAndIncludeProfiles({ email: credentials.email });
|
||||
// Don't leak information about it being username or password that is invalid
|
||||
if (!user) {
|
||||
throw new Error(ErrorCode.IncorrectEmailPassword);
|
||||
@@ -253,8 +228,8 @@ const providers: Provider[] = [
|
||||
name: user.name,
|
||||
role: validateRole(user.role),
|
||||
belongsToActiveTeam: hasActiveTeams,
|
||||
organizationId: user.organizationId,
|
||||
locale: user.locale,
|
||||
profile: user.allProfiles[0],
|
||||
};
|
||||
},
|
||||
}),
|
||||
@@ -291,15 +266,28 @@ if (isSAMLLoginEnabled) {
|
||||
params: { grant_type: "authorization_code" },
|
||||
},
|
||||
userinfo: `${WEBAPP_URL}/api/auth/saml/userinfo`,
|
||||
profile: (profile) => {
|
||||
profile: async (profile: {
|
||||
id?: number;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
email?: string;
|
||||
locale?: string;
|
||||
}) => {
|
||||
const user = await UserRepository.findByEmailAndIncludeProfiles({ email: profile.email || "" });
|
||||
if (!user) {
|
||||
throw new Error(ErrorCode.UserNotFound);
|
||||
}
|
||||
|
||||
const [userProfile] = user.allProfiles;
|
||||
return {
|
||||
id: profile.id || "",
|
||||
id: profile.id || 0,
|
||||
firstName: profile.firstName || "",
|
||||
lastName: profile.lastName || "",
|
||||
email: profile.email || "",
|
||||
name: `${profile.firstName || ""} ${profile.lastName || ""}`.trim(),
|
||||
email_verified: true,
|
||||
locale: profile.locale,
|
||||
profile: userProfile,
|
||||
};
|
||||
},
|
||||
options: {
|
||||
@@ -351,6 +339,12 @@ if (isSAMLLoginEnabled) {
|
||||
}
|
||||
|
||||
const { id, firstName, lastName, email } = userInfo;
|
||||
const user = await UserRepository.findByEmailAndIncludeProfiles({ email });
|
||||
if (!user) {
|
||||
throw new Error(ErrorCode.UserNotFound);
|
||||
}
|
||||
|
||||
const [profile] = user.allProfiles;
|
||||
|
||||
return {
|
||||
id: id as unknown as number,
|
||||
@@ -359,6 +353,7 @@ if (isSAMLLoginEnabled) {
|
||||
email,
|
||||
name: `${firstName} ${lastName}`.trim(),
|
||||
email_verified: true,
|
||||
profile,
|
||||
};
|
||||
},
|
||||
})
|
||||
@@ -427,15 +422,31 @@ export const AUTH_OPTIONS: AuthOptions = {
|
||||
},
|
||||
providers,
|
||||
callbacks: {
|
||||
async jwt({ token, user, account, trigger, session }) {
|
||||
async jwt({
|
||||
// Always available but with a little difference in value
|
||||
token,
|
||||
// Available only in case of signIn, signUp or useSession().update call.
|
||||
trigger,
|
||||
// Available when useSession().update is called. The value will be the POST data
|
||||
session,
|
||||
// Available only in the first call once the user signs in. Not available in subsequent calls
|
||||
user,
|
||||
// Available only in the first call once the user signs in. Not available in subsequent calls
|
||||
account,
|
||||
}) {
|
||||
log.debug("callbacks:jwt", safeStringify({ token, user, account, trigger, session }));
|
||||
|
||||
// The data available in 'session' depends on what data was supplied in update method call of session
|
||||
if (trigger === "update") {
|
||||
return {
|
||||
...token,
|
||||
profileId: session?.profileId ?? token.profileId ?? null,
|
||||
upId: session?.upId ?? token.upId ?? null,
|
||||
locale: session?.locale ?? token.locale ?? "en",
|
||||
name: session?.name ?? token.name,
|
||||
username: session?.username ?? token.username,
|
||||
email: session?.email ?? token.email,
|
||||
};
|
||||
} as JWT;
|
||||
}
|
||||
const autoMergeIdentities = async () => {
|
||||
const existingUser = await prisma.user.findFirst({
|
||||
@@ -446,16 +457,9 @@ export const AUTH_OPTIONS: AuthOptions = {
|
||||
username: true,
|
||||
name: true,
|
||||
email: true,
|
||||
organization: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
metadata: true,
|
||||
},
|
||||
},
|
||||
role: true,
|
||||
locale: true,
|
||||
movedToProfileId: true,
|
||||
teams: {
|
||||
include: {
|
||||
team: true,
|
||||
@@ -470,24 +474,41 @@ export const AUTH_OPTIONS: AuthOptions = {
|
||||
|
||||
// Check if the existingUser has any active teams
|
||||
const belongsToActiveTeam = checkIfUserBelongsToActiveTeam(existingUser);
|
||||
const { teams: _teams, organization, ...existingUserWithoutTeamsField } = existingUser;
|
||||
const { teams: _teams, ...existingUserWithoutTeamsField } = existingUser;
|
||||
const allProfiles = await ProfileRepository.findAllProfilesForUserIncludingMovedUser(existingUser);
|
||||
log.debug(
|
||||
"callbacks:jwt:autoMergeIdentities",
|
||||
safeStringify({
|
||||
allProfiles,
|
||||
})
|
||||
);
|
||||
const { upId } = determineProfile({ profiles: allProfiles, token });
|
||||
|
||||
const parsedOrgMetadata = teamMetadataSchema.parse(organization?.metadata ?? {});
|
||||
const profile = await ProfileRepository.findByUpId(upId);
|
||||
if (!profile) {
|
||||
throw new Error("Profile not found");
|
||||
}
|
||||
|
||||
const profileOrg = profile?.organization;
|
||||
|
||||
return {
|
||||
...existingUserWithoutTeamsField,
|
||||
...token,
|
||||
profileId: profile.id,
|
||||
upId,
|
||||
belongsToActiveTeam,
|
||||
org: organization
|
||||
// All organizations in the token would be too big to store. It breaks the sessions request.
|
||||
// So, we just set the currently switched organization only here.
|
||||
org: profileOrg
|
||||
? {
|
||||
id: organization.id,
|
||||
name: organization.name,
|
||||
slug: organization.slug ?? parsedOrgMetadata?.requestedSlug ?? "",
|
||||
fullDomain: getOrgFullOrigin(organization.slug ?? parsedOrgMetadata?.requestedSlug ?? ""),
|
||||
id: profileOrg.id,
|
||||
name: profileOrg.name,
|
||||
slug: profileOrg.slug ?? profileOrg.requestedSlug ?? "",
|
||||
fullDomain: getOrgFullOrigin(profileOrg.slug ?? profileOrg.requestedSlug ?? ""),
|
||||
domainSuffix: subdomainSuffix(),
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
: null,
|
||||
} as JWT;
|
||||
};
|
||||
if (!user) {
|
||||
return await autoMergeIdentities();
|
||||
@@ -512,7 +533,9 @@ export const AUTH_OPTIONS: AuthOptions = {
|
||||
belongsToActiveTeam: user?.belongsToActiveTeam,
|
||||
org: user?.org,
|
||||
locale: user?.locale,
|
||||
};
|
||||
profileId: user.profile?.id ?? token.profileId ?? null,
|
||||
upId: user.profile?.upId ?? token.upId ?? null,
|
||||
} as JWT;
|
||||
}
|
||||
|
||||
// The arguments above are from the provider so we need to look up the
|
||||
@@ -551,15 +574,23 @@ export const AUTH_OPTIONS: AuthOptions = {
|
||||
belongsToActiveTeam: token?.belongsToActiveTeam as boolean,
|
||||
org: token?.org,
|
||||
locale: existingUser.locale,
|
||||
};
|
||||
} as JWT;
|
||||
}
|
||||
|
||||
if (account.type === "email") {
|
||||
return await autoMergeIdentities();
|
||||
}
|
||||
|
||||
return token;
|
||||
},
|
||||
async session({ session, token }) {
|
||||
async session({ session, token, user }) {
|
||||
log.debug("callbacks:session - Session callback called", safeStringify({ session, token, user }));
|
||||
const hasValidLicense = await checkLicense(prisma);
|
||||
const profileId = token.profileId;
|
||||
const calendsoSession: Session = {
|
||||
...session,
|
||||
profileId,
|
||||
upId: token.upId || session.upId,
|
||||
hasValidLicense,
|
||||
user: {
|
||||
...session.user,
|
||||
@@ -576,7 +607,19 @@ export const AUTH_OPTIONS: AuthOptions = {
|
||||
return calendsoSession;
|
||||
},
|
||||
async signIn(params) {
|
||||
const { user, account, profile } = params;
|
||||
const {
|
||||
/**
|
||||
* Available when Credentials provider is used - Has the value returned by authorize callback
|
||||
*/
|
||||
user,
|
||||
/**
|
||||
* Available when Credentials provider is used - Has the value submitted as the body of the HTTP POST submission
|
||||
*/
|
||||
profile,
|
||||
account,
|
||||
} = params;
|
||||
|
||||
log.debug("callbacks:signin", safeStringify(params));
|
||||
|
||||
if (account?.provider === "email") {
|
||||
return true;
|
||||
@@ -814,6 +857,9 @@ export const AUTH_OPTIONS: AuthOptions = {
|
||||
|
||||
return false;
|
||||
},
|
||||
/**
|
||||
* Used to handle the navigation right after successful login or logout
|
||||
*/
|
||||
async redirect({ url, baseUrl }) {
|
||||
// Allows relative callback URLs
|
||||
if (url.startsWith("/")) return `${baseUrl}${url}`;
|
||||
@@ -823,3 +869,27 @@ export const AUTH_OPTIONS: AuthOptions = {
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Identifies the profile the user should be logged into.
|
||||
*/
|
||||
const determineProfile = ({
|
||||
token,
|
||||
profiles,
|
||||
}: {
|
||||
token: JWT;
|
||||
profiles: { id: number | null; upId: string }[];
|
||||
}) => {
|
||||
// If profile switcher is disabled, we can only show the first profile.
|
||||
if (!ENABLE_PROFILE_SWITCHER) {
|
||||
return profiles[0];
|
||||
}
|
||||
|
||||
if (token.upId) {
|
||||
// Otherwise use what's in the token
|
||||
return { profileId: token.profileId, upId: token.upId as string };
|
||||
}
|
||||
|
||||
// If there is just one profile it has to be the one we want to log into.
|
||||
return profiles[0];
|
||||
};
|
||||
@@ -127,6 +127,9 @@ async function handler(req: RequestWithUsernameStatus, res: NextApiResponse) {
|
||||
where: {
|
||||
id: foundToken.teamId,
|
||||
},
|
||||
include: {
|
||||
parent: true,
|
||||
},
|
||||
});
|
||||
if (team) {
|
||||
const teamMetadata = teamMetadataSchema.parse(team?.metadata);
|
||||
@@ -157,10 +160,10 @@ async function handler(req: RequestWithUsernameStatus, res: NextApiResponse) {
|
||||
closeComUpsertTeamUser(team, user, membership.role);
|
||||
|
||||
// Accept any child team invites for orgs.
|
||||
if (team.parentId) {
|
||||
if (team.parent) {
|
||||
await joinAnyChildTeamOnOrgInvite({
|
||||
userId: user.id,
|
||||
orgId: team.parentId,
|
||||
org: team.parent,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,6 +68,9 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||
where: {
|
||||
id: foundToken.teamId,
|
||||
},
|
||||
include: {
|
||||
parent: true,
|
||||
},
|
||||
});
|
||||
if (team) {
|
||||
const teamMetadata = teamMetadataSchema.parse(team?.metadata);
|
||||
@@ -97,10 +100,10 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
|
||||
closeComUpsertTeamUser(team, user, membership.role);
|
||||
|
||||
// Accept any child team invites for orgs.
|
||||
if (team.parentId) {
|
||||
if (team.parent) {
|
||||
await joinAnyChildTeamOnOrgInvite({
|
||||
userId: user.id,
|
||||
orgId: team.parentId,
|
||||
org: team.parent,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,7 +84,11 @@ const usernameCheck = async (usernameRaw: string) => {
|
||||
const username = slugify(usernameRaw);
|
||||
|
||||
const user = await prisma.user.findFirst({
|
||||
where: { username, organizationId: null },
|
||||
where: {
|
||||
username,
|
||||
// Simply remove it when we drop organizationId column
|
||||
organizationId: null,
|
||||
},
|
||||
select: {
|
||||
username: true,
|
||||
},
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import type z from "zod";
|
||||
|
||||
import { updateNewTeamMemberEventTypes } from "@calcom/lib/server/queries";
|
||||
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { Team, User } from "@calcom/prisma/client";
|
||||
import { MembershipRole } from "@calcom/prisma/enums";
|
||||
import type { teamMetadataSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
import { getOrgUsernameFromEmail } from "./getOrgUsernameFromEmail";
|
||||
|
||||
export const createOrUpdateMemberships = async ({
|
||||
teamMetadata,
|
||||
user,
|
||||
@@ -17,13 +20,39 @@ export const createOrUpdateMemberships = async ({
|
||||
}) => {
|
||||
return await prisma.$transaction(async (tx) => {
|
||||
if (teamMetadata?.isOrganization) {
|
||||
await tx.user.update({
|
||||
const dbUser = await tx.user.update({
|
||||
where: {
|
||||
id: user.id,
|
||||
},
|
||||
data: {
|
||||
organizationId: team.id,
|
||||
},
|
||||
select: {
|
||||
username: true,
|
||||
email: true,
|
||||
},
|
||||
});
|
||||
|
||||
// Ideally dbUser.username should never be null, but just in case.
|
||||
// This method being called only during signup means that dbUser.username should be the correct org username
|
||||
const orgUsername =
|
||||
dbUser.username || getOrgUsernameFromEmail(dbUser.email, teamMetadata?.orgAutoAcceptEmail ?? null);
|
||||
await tx.profile.upsert({
|
||||
create: {
|
||||
uid: ProfileRepository.generateProfileUid(),
|
||||
userId: user.id,
|
||||
organizationId: team.id,
|
||||
username: orgUsername,
|
||||
},
|
||||
update: {
|
||||
username: orgUsername,
|
||||
},
|
||||
where: {
|
||||
userId_organizationId: {
|
||||
userId: user.id,
|
||||
organizationId: team.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
const membership = await tx.membership.upsert({
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import slugify from "@calcom/lib/slugify";
|
||||
|
||||
export const getOrgUsernameFromEmail = (email: string, autoAcceptEmailDomain: string) => {
|
||||
export const getOrgUsernameFromEmail = (email: string, autoAcceptEmailDomain: string | null) => {
|
||||
const [emailUser, emailDomain = ""] = email.split("@");
|
||||
const username =
|
||||
emailDomain === autoAcceptEmailDomain
|
||||
|
||||
@@ -1,38 +1,58 @@
|
||||
import { updateNewTeamMemberEventTypes } from "@calcom/lib/server/queries";
|
||||
import prisma from "@calcom/prisma";
|
||||
import { ProfileRepository } from "@calcom/lib/server/repository/profile";
|
||||
import { prisma } from "@calcom/prisma";
|
||||
import type { Team } from "@calcom/prisma/client";
|
||||
import { teamMetadataSchema } from "@calcom/prisma/zod-utils";
|
||||
|
||||
export async function joinOrganization({
|
||||
organizationId,
|
||||
userId,
|
||||
}: {
|
||||
userId: number;
|
||||
organizationId: number;
|
||||
}) {
|
||||
return await prisma.user.update({
|
||||
import { getOrgUsernameFromEmail } from "./getOrgUsernameFromEmail";
|
||||
|
||||
export async function joinAnyChildTeamOnOrgInvite({ userId, org }: { userId: number; org: Team }) {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: {
|
||||
id: userId,
|
||||
},
|
||||
data: {
|
||||
organizationId: organizationId,
|
||||
},
|
||||
});
|
||||
}
|
||||
if (!user) {
|
||||
throw new Error("User not found");
|
||||
}
|
||||
|
||||
const orgMetadata = teamMetadataSchema.parse(org.metadata);
|
||||
|
||||
const orgUsername =
|
||||
user.username || getOrgUsernameFromEmail(user.email, orgMetadata?.orgAutoAcceptEmail ?? null);
|
||||
|
||||
export async function joinAnyChildTeamOnOrgInvite({ userId, orgId }: { userId: number; orgId: number }) {
|
||||
await prisma.$transaction([
|
||||
// Simply remove this update when we remove the `organizationId` field from the user table
|
||||
prisma.user.update({
|
||||
where: {
|
||||
id: userId,
|
||||
},
|
||||
data: {
|
||||
organizationId: orgId,
|
||||
organizationId: org.id,
|
||||
},
|
||||
}),
|
||||
prisma.profile.upsert({
|
||||
create: {
|
||||
uid: ProfileRepository.generateProfileUid(),
|
||||
userId: userId,
|
||||
organizationId: org.id,
|
||||
username: orgUsername,
|
||||
},
|
||||
update: {
|
||||
username: orgUsername,
|
||||
},
|
||||
where: {
|
||||
userId_organizationId: {
|
||||
userId: user.id,
|
||||
organizationId: org.id,
|
||||
},
|
||||
},
|
||||
}),
|
||||
prisma.membership.updateMany({
|
||||
where: {
|
||||
userId,
|
||||
team: {
|
||||
id: orgId,
|
||||
id: org.id,
|
||||
},
|
||||
accepted: false,
|
||||
},
|
||||
@@ -44,7 +64,7 @@ export async function joinAnyChildTeamOnOrgInvite({ userId, orgId }: { userId: n
|
||||
where: {
|
||||
userId,
|
||||
team: {
|
||||
parentId: orgId,
|
||||
parentId: org.id,
|
||||
},
|
||||
accepted: false,
|
||||
},
|
||||
@@ -54,5 +74,5 @@ export async function joinAnyChildTeamOnOrgInvite({ userId, orgId }: { userId: n
|
||||
}),
|
||||
]);
|
||||
|
||||
await updateNewTeamMemberEventTypes(userId, orgId);
|
||||
await updateNewTeamMemberEventTypes(userId, org.id);
|
||||
}
|
||||
Reference in new issue
Block a user