Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat: simplified wht signup flow

=b0f0d0152f10
diff --git a/backend/src/ee/services/license/license-dal.ts b/backend/src/ee/services/license/license-dal.ts
index 853f3a9949..d5689260d5 100644
--- a/backend/src/ee/services/license/license-dal.ts
+++ b/backend/src/ee/services/license/license-dal.ts
@@ -1,17 +1,18 @@
import { Knex } from "knex";
import { TDbClient } from "@app/db";
-import { AccessScope, OrgMembershipStatus, TableName } from "@app/db/schemas";
+import { AccessScope, TableName } from "@app/db/schemas";
import { DatabaseError } from "@app/lib/errors";
export type TLicenseDALFactory = ReturnType<typeof licenseDALFactory>;
+// TODO(auth-revamp): check the count
export const licenseDALFactory = (db: TDbClient) => {
const countOfOrgMembers = async (orgId: string | null, tx?: Knex) => {
try {
const doc = await (tx || db.replicaNode())(TableName.Membership)
.join(TableName.Organization, `${TableName.Organization}.id`, `${TableName.Membership}.scopeOrgId`)
- .where({ status: OrgMembershipStatus.Accepted, scope: AccessScope.Organization })
+ .where({ scope: AccessScope.Organization })
.andWhere((bd) => {
if (orgId) {
void bd.where(`${TableName.Membership}.scopeOrgId`, orgId);
@@ -19,6 +20,7 @@ export const licenseDALFactory = (db: TDbClient) => {
})
.join(TableName.Users, `${TableName.Membership}.actorUserId`, `${TableName.Users}.id`)
.where(`${TableName.Users}.isGhost`, false)
+ .where(`${TableName.Users}.isAccepted`, true)
.whereNull(`${TableName.Organization}.rootOrgId`)
.count();
return Number(doc?.[0]?.count ?? 0);
@@ -52,7 +54,7 @@ export const licenseDALFactory = (db: TDbClient) => {
// count org users
const userDoc = await (tx || db.replicaNode())(TableName.Membership)
.join(TableName.Organization, `${TableName.Organization}.id`, `${TableName.Membership}.scopeOrgId`)
- .where({ status: OrgMembershipStatus.Accepted, scope: AccessScope.Organization })
+ .where({ scope: AccessScope.Organization })
.whereNotNull(`${TableName.Membership}.actorUserId`)
.andWhere((bd) => {
if (orgId) {
@@ -61,6 +63,7 @@ export const licenseDALFactory = (db: TDbClient) => {
})
.join(TableName.Users, `${TableName.Membership}.actorUserId`, `${TableName.Users}.id`)
.where(`${TableName.Users}.isGhost`, false)
+ .where(`${TableName.Users}.isAccepted`, true)
.whereNull(`${TableName.Organization}.rootOrgId`)
.count();
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 31018cdb89..7df02dc95c 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1105,14 +1105,8 @@ export const registerRoutes = async (
smtpService,
authDAL,
userDAL,
- userGroupMembershipDAL,
- projectKeyDAL,
- projectDAL,
- projectBotDAL,
orgDAL,
- orgService,
- licenseService,
- membershipGroupDAL
+ orgService
});
const microsoftTeamsService = microsoftTeamsServiceFactory({
diff --git a/backend/src/server/routes/v3/signup-router.ts b/backend/src/server/routes/v3/signup-router.ts
index 9480a80741..d88dd52a81 100644
--- a/backend/src/server/routes/v3/signup-router.ts
+++ b/backend/src/server/routes/v3/signup-router.ts
@@ -95,121 +95,15 @@ export const registerSignupRouter = async (server: FastifyZodProvider) => {
rateLimit: authRateLimit
},
schema: {
- operationId: "completeEmailAccountSignupV3",
- body: z
- .object({
- email: z.string().trim(),
- firstName: z.string().trim(),
- lastName: z.string().trim().optional(),
- providerAuthToken: z.string().trim().optional().nullish(),
- attributionSource: z.string().trim().optional(),
- password: z.string()
- })
- .and(
- z.preprocess(
- (data) => {
- if (typeof data === "object" && data && "useDefaultOrg" in data === false) {
- return { ...data, useDefaultOrg: false };
- }
- return data;
- },
- z.discriminatedUnion("useDefaultOrg", [
- z.object({ useDefaultOrg: z.literal(true) }),
- z.object({
- useDefaultOrg: z.literal(false),
- organizationName: GenericResourceNameSchema
- })
- ])
- )
- ),
- response: {
- 200: z.object({
- message: z.string(),
- user: UsersSchema,
- token: z.string(),
- organizationId: z.string().nullish()
- })
- }
- },
- handler: async (req, res) => {
- const userAgent = req.headers["user-agent"];
- if (!userAgent) throw new Error("user agent header is required");
- const appCfg = getConfig();
-
- const { user, accessToken, refreshToken, organizationId, authMethod } =
- await server.services.signup.completeEmailAccountSignup({
- ...req.body,
- ip: req.realIp,
- userAgent,
- authorization: req.headers.authorization as string
- });
-
- if (user.email) {
- void server.services.telemetry.sendLoopsEvent(user.email, user.firstName || "", user.lastName || "");
- void server.services.telemetry.sendHubSpotSignupEvent(
- user.email,
- authMethod,
- user.firstName || "",
- user.lastName || ""
- );
- }
-
- void server.services.telemetry.sendPostHogEvents({
- event: PostHogEventTypes.UserSignedUp,
- distinctId: user.username ?? "",
- ...(organizationId ? { organizationId } : {}),
- properties: {
- username: user.username,
- email: user.email ?? "",
- attributionSource: req.body.attributionSource
- }
- });
-
- const signupDistinctId = user.username ?? user.email ?? "";
- if (signupDistinctId) {
- void server.services.telemetry.identifyUser(
- signupDistinctId,
- {
- email: user.email ?? undefined,
- username: user.username,
- userId: user.id,
- firstName: user.firstName ?? undefined,
- lastName: user.lastName ?? undefined,
- isEmailVerified: user.isEmailVerified ?? undefined,
- isMfaEnabled: user.isMfaEnabled ?? undefined,
- superAdmin: user.superAdmin ?? undefined
- },
- { skipDedup: true }
- );
- }
-
- void res.setCookie("jid", refreshToken, {
- httpOnly: true,
- path: "/",
- sameSite: "strict",
- secure: appCfg.HTTPS_ENABLED
- });
-
- addAuthOriginDomainCookie(res);
-
- return { message: "Successfully set up account", user, token: accessToken, organizationId };
- }
- });
-
- server.route({
- url: "/complete-account/invite",
- method: "POST",
- config: {
- rateLimit: authRateLimit
- },
- schema: {
- operationId: "completeAccountInviteV3",
+ operationId: "completeAccountSignupV3",
body: z.object({
- email: z.string().email().trim(),
- password: z.string(),
+ email: z.string().trim(),
firstName: z.string().trim(),
lastName: z.string().trim().optional(),
- tokenMetadata: z.string().optional()
+ providerAuthToken: z.string().trim().optional().nullish(),
+ attributionSource: z.string().trim().optional(),
+ password: z.string(),
+ organizationName: GenericResourceNameSchema.optional()
}),
response: {
200: z.object({
@@ -224,7 +118,7 @@ export const registerSignupRouter = async (server: FastifyZodProvider) => {
if (!userAgent) throw new Error("user agent header is required");
const appCfg = getConfig();
- const { user, accessToken, refreshToken, organizationId } = await server.services.signup.completeAccountInvite({
+ const { user, accessToken, refreshToken, authMethod } = await server.services.signup.completeAccountSignup({
...req.body,
ip: req.realIp,
userAgent,
@@ -235,7 +129,7 @@ export const registerSignupRouter = async (server: FastifyZodProvider) => {
void server.services.telemetry.sendLoopsEvent(user.email, user.firstName || "", user.lastName || "");
void server.services.telemetry.sendHubSpotSignupEvent(
user.email,
- "invite",
+ authMethod,
user.firstName || "",
user.lastName || ""
);
@@ -248,14 +142,14 @@ export const registerSignupRouter = async (server: FastifyZodProvider) => {
properties: {
username: user.username,
email: user.email ?? "",
- attributionSource: "Team Invite"
+ attributionSource: req.body.attributionSource
}
});
- const inviteDistinctId = user.username ?? user.email ?? "";
- if (inviteDistinctId) {
+ const signupDistinctId = user.username ?? user.email ?? "";
+ if (signupDistinctId) {
void server.services.telemetry.identifyUser(
- inviteDistinctId,
+ signupDistinctId,
{
email: user.email ?? undefined,
username: user.username,
@@ -276,7 +170,6 @@ export const registerSignupRouter = async (server: FastifyZodProvider) => {
sameSite: "strict",
secure: appCfg.HTTPS_ENABLED
});
- // TODO(akhilmhdh-pg): add telemetry service
addAuthOriginDomainCookie(res);
diff --git a/backend/src/services/auth-token/auth-token-service.ts b/backend/src/services/auth-token/auth-token-service.ts
index 331c51d8f3..37c91f3987 100644
--- a/backend/src/services/auth-token/auth-token-service.ts
+++ b/backend/src/services/auth-token/auth-token-service.ts
@@ -123,6 +123,7 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAu
return token;
};
+ const DUMMY_HASH = "$2b$10$N9qo8uLOickgx2ZMRZoMyeIjZAgcfl7p92ldGxad68LJZdL17lhWy";
const validateTokenForUser = async ({
type,
userId,
@@ -130,16 +131,22 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgDAL, keyStore }: TAu
orgId
}: TValidateTokenForUserDTO): Promise<TAuthTokens | undefined> => {
const token = await tokenDAL.findOne({ type, userId, orgId: orgId || null });
- // validate token
+
+ // Always perform a hash comparison, even if no token exists.
+ // Use a dummy hash so the timing is indistinguishable.
+ const hashToCompare = token?.tokenHash ?? DUMMY_HASH;
+ const isValidToken = await crypto.hashing().compareHash(code, hashToCompare);
+
+ // Now perform the logical checks *after* the constant-time work is done.
if (!token) throw new Error("Failed to find token");
- if (token?.expiresAt && new Date(token.expiresAt) < new Date()) {
+
+ if (token.expiresAt && new Date(token.expiresAt) < new Date()) {
await tokenDAL.delete({ type, userId, orgId });
throw new Error("Token expired. Please try again");
}
- const isValidToken = await crypto.hashing().compareHash(code, token.tokenHash);
if (!isValidToken) {
- if (token?.triesLeft) {
+ if (token.triesLeft) {
if (token.triesLeft === 1) {
await tokenDAL.deleteTokenForUser({ type, userId, orgId: orgId || null });
} else {
diff --git a/backend/src/services/auth/auth-signup-service.ts b/backend/src/services/auth/auth-signup-service.ts
index 613911c113..64aa2611a1 100644
--- a/backend/src/services/auth/auth-signup-service.ts
+++ b/backend/src/services/auth/auth-signup-service.ts
@@ -1,20 +1,11 @@
-import { AccessScope, OrgMembershipStatus, TableName } from "@app/db/schemas";
-import { convertPendingGroupAdditionsToGroupMemberships } from "@app/ee/services/group/group-fns";
-import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
-import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
-import { isAuthMethodSaml } from "@app/ee/services/permission/permission-fns";
+import { AccessScope } from "@app/db/schemas";
import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto/cryptography";
-import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
-import { getMinExpiresIn } from "@app/lib/fn";
+import { BadRequestError, ForbiddenRequestError } from "@app/lib/errors";
import { isDisposableEmail } from "@app/lib/validator";
-import { TProjectDALFactory } from "@app/services/project/project-dal";
-import { TProjectBotDALFactory } from "@app/services/project-bot/project-bot-dal";
-import { TProjectKeyDALFactory } from "@app/services/project-key/project-key-dal";
import { TAuthTokenServiceFactory } from "../auth-token/auth-token-service";
import { TokenType } from "../auth-token/auth-token-types";
-import { TMembershipGroupDALFactory } from "../membership-group/membership-group-dal";
import { TOrgDALFactory } from "../org/org-dal";
import { TOrgServiceFactory } from "../org/org-service";
import { SmtpTemplates, TSmtpService } from "../smtp/smtp-service";
@@ -22,46 +13,27 @@ import { getServerCfg } from "../super-admin/super-admin-service";
import { TUserDALFactory } from "../user/user-dal";
import { UserEncryption } from "../user/user-types";
import { TAuthDALFactory } from "./auth-dal";
-import { validateProviderAuthToken, validateSignUpAuthorization } from "./auth-fns";
-import { TCompleteAccountInviteDTO, TCompleteAccountSignupDTO } from "./auth-signup-type";
+import { validateSignUpAuthorization } from "./auth-fns";
+import { TCompleteAccountSignupDTO } from "./auth-signup-type";
import { AuthMethod, AuthTokenType } from "./auth-type";
type TAuthSignupDep = {
authDAL: TAuthDALFactory;
userDAL: TUserDALFactory;
- userGroupMembershipDAL: Pick<
- TUserGroupMembershipDALFactory,
- | "find"
- | "transaction"
- | "insertMany"
- | "deletePendingUserGroupMembershipsByUserIds"
- | "findUserGroupMembershipsInProject"
- >;
- projectKeyDAL: Pick<TProjectKeyDALFactory, "find" | "findLatestProjectKey" | "insertMany">;
- projectDAL: Pick<TProjectDALFactory, "findProjectGhostUser" | "findProjectById" | "findById">;
- projectBotDAL: Pick<TProjectBotDALFactory, "findOne">;
orgService: Pick<TOrgServiceFactory, "createOrganization" | "findOrganizationById">;
orgDAL: TOrgDALFactory;
tokenService: TAuthTokenServiceFactory;
smtpService: TSmtpService;
- licenseService: Pick<TLicenseServiceFactory, "updateSubscriptionOrgMemberCount">;
- membershipGroupDAL: TMembershipGroupDALFactory;
};
export type TAuthSignupFactory = ReturnType<typeof authSignupServiceFactory>;
export const authSignupServiceFactory = ({
authDAL,
userDAL,
- userGroupMembershipDAL,
- projectKeyDAL,
- projectDAL,
- projectBotDAL,
tokenService,
smtpService,
orgService,
- orgDAL,
- membershipGroupDAL,
- licenseService
+ orgDAL
}: TAuthSignupDep) => {
// first step of signup. create user and send email
const beginEmailSignupProcess = async (email: string) => {
@@ -72,9 +44,7 @@ export const authSignupServiceFactory = ({
}
// akhilmhdh: case sensitive email resolution
- const usersByUsername = await userDAL.findUserByUsername(sanitizedEmail);
- let user =
- usersByUsername?.length > 1 ? usersByUsername.find((el) => el.username === sanitizedEmail) : usersByUsername?.[0];
+ let user = await userDAL.findOne({ username: sanitizedEmail });
if (user && user.isAccepted) {
// Send informational email for existing accounts instead of throwing error
// This prevents user enumeration vulnerability
@@ -91,6 +61,7 @@ export const authSignupServiceFactory = ({
});
return;
}
+
if (!user) {
user = await userDAL.create({
authMethods: [AuthMethod.EMAIL],
@@ -118,24 +89,34 @@ export const authSignupServiceFactory = ({
const verifyEmailSignup = async (email: string, code: string) => {
const sanitizedEmail = email.trim().toLowerCase();
- const usersByUsername = await userDAL.findUserByUsername(sanitizedEmail);
- const user =
- usersByUsername?.length > 1 ? usersByUsername.find((el) => el.username === sanitizedEmail) : usersByUsername?.[0];
- if (!user || (user && user.isAccepted)) {
- // TODO(akhilmhdh): copy as old one. this needs to be changed due to security issues
- throw new Error("Failed to send verification code for complete account");
+ const user = await userDAL.findOne({ username: sanitizedEmail });
+
+ // Always call validateTokenForUser so the response time includes
+ // the bcrypt cost regardless of whether the user exists.
+ // Use a dummy userId when there's no valid user.
+ const DUMMY_USER_ID = "00000000-0000-0000-0000-000000000000";
+ const shouldReject = !user || user.isAccepted;
+
+ try {
+ await tokenService.validateTokenForUser({
+ type: TokenType.TOKEN_EMAIL_CONFIRMATION,
+ userId: shouldReject ? DUMMY_USER_ID : user.id,
+ code
+ });
+ } catch {
+ // If we were going to reject anyway, throw the generic message.
+ // If the user was valid but the token failed, same generic message.
+ throw new Error("Invalid or expired verification request");
}
- const appCfg = getConfig();
- await tokenService.validateTokenForUser({
- type: TokenType.TOKEN_EMAIL_CONFIRMATION,
- userId: user.id,
- code
- });
+ // Reject *after* the constant-time token validation work.
+ if (shouldReject) {
+ throw new Error("Invalid or expired verification request");
+ }
await userDAL.updateById(user.id, { isEmailVerified: true });
- // generate jwt token this is a temporary token
+ const appCfg = getConfig();
const jwtToken = crypto.jwt().sign(
{
authTokenType: AuthTokenType.SIGNUP_TOKEN,
@@ -148,69 +129,50 @@ export const authSignupServiceFactory = ({
return { user, token: jwtToken };
};
- const completeEmailAccountSignup = async ({
+ const completeAccountSignup = async ({
email,
password,
firstName,
lastName,
- providerAuthToken,
organizationName,
- // attributionSource,
ip,
userAgent,
- authorization,
- useDefaultOrg
+ authorization
}: TCompleteAccountSignupDTO) => {
const sanitizedEmail = email.trim().toLowerCase();
const appCfg = getConfig();
- const serverCfg = await getServerCfg();
- const usersByUsername = await userDAL.findUserByUsername(sanitizedEmail);
- const user =
- usersByUsername?.length > 1 ? usersByUsername.find((el) => el.username === sanitizedEmail) : usersByUsername?.[0];
- if (!user || (user && user.isAccepted)) {
+ const user = await userDAL.findOne({ username: sanitizedEmail });
+
+ // Always validate the authorization token to prevent timing attacks
+ // that could reveal whether an email is registered.
+ // Use a dummy userId when user is missing so the JWT work is still performed.
+ const dummyUserId = "00000000-0000-0000-0000-000000000000";
+ validateSignUpAuthorization(authorization, user?.id ?? dummyUserId);
+
+ if (!user || (user && (user.isAccepted || !user.isEmailVerified))) {
throw new BadRequestError({ message: "Failed to complete account for complete user" });
}
- let organizationId: string | null = null;
- let authMethod: AuthMethod | null = null;
- if (providerAuthToken) {
- const { orgId, authMethod: userAuthMethod } = validateProviderAuthToken(providerAuthToken, user.username);
- authMethod = userAuthMethod;
- organizationId = orgId;
- } else {
- // disallow signup if disabled. we are not doing this for providerAuthToken because we allow signups via saml or sso
+ // Check if user has existing org memberships (i.e., they were invited)
+ const existingMemberships = await orgDAL.findMembership({
+ actorUserId: user.id,
+ scope: AccessScope.Organization
+ });
+ const isInvitedUser = existingMemberships.length > 0;
+
+ // Self-signup requires allowSignUp to be enabled
+ if (!isInvitedUser) {
+ const serverCfg = await getServerCfg();
if (!serverCfg.allowSignUp) {
throw new ForbiddenRequestError({
message: "Signup's are disabled"
});
}
- validateSignUpAuthorization(authorization, user.id);
}
const hashedPassword = await crypto.hashing().createHash(password, appCfg.SALT_ROUNDS);
- const updateduser = await authDAL.transaction(async (tx) => {
- const duplicateUsers = await userDAL.find(
- {
- email: user.email || sanitizedEmail,
- isAccepted: false
- },
- { tx }
- );
- const nonAcceptedDuplicateUserIds = duplicateUsers
- .filter((duplicateUser) => duplicateUser.id !== user.id)
- .map((duplicateUser) => duplicateUser.id);
- if (nonAcceptedDuplicateUserIds.length > 0) {
- await userDAL.delete(
- {
- $in: {
- id: nonAcceptedDuplicateUserIds
- }
- },
- tx
- );
- }
-
+ const updatedUser = await authDAL.transaction(async (tx) => {
const us = await userDAL.updateById(user.id, { firstName, lastName, isAccepted: true }, tx);
if (!us) throw new Error("User not found");
@@ -223,102 +185,36 @@ export const authSignupServiceFactory = ({
tx
);
- // If it's SAML Auth and the organization ID is present, we should check if the user has a pending invite for this org, and accept it
- if (
- (isAuthMethodSaml(authMethod) || [AuthMethod.LDAP, AuthMethod.OIDC].includes(authMethod as AuthMethod)) &&
- organizationId
- ) {
- const [pendingOrgMembership] = await orgDAL.findMembership({
- [`${TableName.Membership}.actorUserId` as "actorUserId"]: user.id,
- status: OrgMembershipStatus.Invited,
- [`${TableName.Membership}.scopeOrgId` as "scopeOrgId"]: organizationId,
- [`${TableName.Membership}.scope` as "scope"]: AccessScope.Organization
- });
-
- if (pendingOrgMembership) {
- await orgDAL.updateMembershipById(
- pendingOrgMembership.id,
- {
- status: OrgMembershipStatus.Accepted
- },
- tx
- );
- }
- }
-
return { info: us, key: userEncKey };
});
- if (!organizationId) {
- let orgId = "";
- if (useDefaultOrg && serverCfg.defaultAuthOrgId && !appCfg.isCloud) {
- const defaultOrg = await orgDAL.findOrgById(serverCfg.defaultAuthOrgId);
- if (!defaultOrg) throw new BadRequestError({ message: "Failed to find default organization" });
- orgId = defaultOrg.id;
- } else {
- if (!organizationName) throw new BadRequestError({ message: "Organization name is required" });
- const newOrganization = await orgService.createOrganization({
- userId: user.id,
- userEmail: user.email ?? user.username,
- orgName: organizationName
- });
-
- if (!newOrganization) throw new Error("Failed to create organization");
- orgId = newOrganization.id;
- }
-
- organizationId = orgId;
- }
-
- const updatedMembersips = await orgDAL.updateMembership(
- { inviteEmail: sanitizedEmail, status: OrgMembershipStatus.Invited, scope: AccessScope.Organization },
- { actorUserId: user.id, status: OrgMembershipStatus.Accepted }
- );
- const uniqueOrgId = [...new Set(updatedMembersips.map(({ scopeOrgId }) => scopeOrgId))];
- await Promise.allSettled(uniqueOrgId.map((orgId) => licenseService.updateSubscriptionOrgMemberCount(orgId)));
-
- await convertPendingGroupAdditionsToGroupMemberships({
- userIds: [user.id],
- userDAL,
- userGroupMembershipDAL,
- projectKeyDAL,
- membershipGroupDAL,
- projectDAL,
- projectBotDAL
- });
-
- let tokenSessionExpiresIn: string | number = appCfg.JWT_AUTH_LIFETIME;
- let refreshTokenExpiresIn: string | number = appCfg.JWT_REFRESH_LIFETIME;
-
- if (organizationId) {
- const org = await orgService.findOrganizationById({
+ // If self-signup, create a default organization
+ if (!isInvitedUser && organizationName) {
+ await orgService.createOrganization({
userId: user.id,
- orgId: organizationId,
- actorAuthMethod: authMethod,
- actorOrgId: organizationId,
- rootOrgId: organizationId
+ userEmail: user.email ?? user.username,
+ orgName: organizationName
});
- if (org && org.userTokenExpiration) {
- tokenSessionExpiresIn = getMinExpiresIn(appCfg.JWT_AUTH_LIFETIME, org.userTokenExpiration);
- refreshTokenExpiresIn = org.userTokenExpiration;
- }
}
+ // TODO(auth-revamp): check for license count
+ const tokenSessionExpiresIn = appCfg.JWT_AUTH_LIFETIME;
+ const refreshTokenExpiresIn = appCfg.JWT_REFRESH_LIFETIME;
+
const tokenSession = await tokenService.getUserTokenSession({
userAgent,
ip,
- userId: updateduser.info.id
+ userId: updatedUser.info.id
});
if (!tokenSession) throw new Error("Failed to create token");
const accessToken = crypto.jwt().sign(
{
- authMethod: authMethod || AuthMethod.EMAIL,
+ authMethod: AuthMethod.EMAIL,
authTokenType: AuthTokenType.ACCESS_TOKEN,
- userId: updateduser.info.id,
+ userId: updatedUser.info.id,
tokenVersionId: tokenSession.id,
- accessVersion: tokenSession.accessVersion,
- organizationId
+ accessVersion: tokenSession.accessVersion
},
appCfg.AUTH_SECRET,
{ expiresIn: tokenSessionExpiresIn }
@@ -326,153 +222,26 @@ export const authSignupServiceFactory = ({
const refreshToken = crypto.jwt().sign(
{
- authMethod: authMethod || AuthMethod.EMAIL,
authTokenType: AuthTokenType.REFRESH_TOKEN,
- userId: updateduser.info.id,
+ userId: updatedUser.info.id,
tokenVersionId: tokenSession.id,
- refreshVersion: tokenSession.refreshVersion,
- organizationId
+ refreshVersion: tokenSession.refreshVersion
},
appCfg.AUTH_SECRET,
{ expiresIn: refreshTokenExpiresIn }
);
return {
- user: updateduser.info,
+ user: updatedUser.info,
accessToken,
refreshToken,
- organizationId,
- authMethod: authMethod || AuthMethod.EMAIL
+ authMethod: AuthMethod.EMAIL
};
};
- /*
- * User signup flow when they are invited to join the org
- * */
- const completeAccountInvite = async ({
- email,
- ip,
- password,
- firstName,
- userAgent,
- lastName,
- authorization
- }: TCompleteAccountInviteDTO) => {
- const sanitizedEmail = email.trim().toLowerCase();
- const usersByUsername = await userDAL.findUserByUsername(sanitizedEmail);
- const user =
- usersByUsername?.length > 1 ? usersByUsername.find((el) => el.username === sanitizedEmail) : usersByUsername?.[0];
- if (!user || (user && user.isAccepted)) {
- throw new Error("Failed to complete account for complete user");
- }
-
- validateSignUpAuthorization(authorization, user.id);
-
- const [orgMembership] = await orgDAL.findMembership({
- inviteEmail: sanitizedEmail,
- status: OrgMembershipStatus.Invited
- });
- if (!orgMembership)
- throw new NotFoundError({
- message: "Failed to find invitation for email",
- name: "complete account invite"
- });
-
- const appCfg = getConfig();
- const hashedPassword = await crypto.hashing().createHash(password, appCfg.SALT_ROUNDS);
- const updateduser = await authDAL.transaction(async (tx) => {
- const duplicateUsers = await userDAL.find(
- {
- email: user.email || sanitizedEmail,
- isAccepted: false
- },
- { tx }
- );
- const nonAcceptedDuplicateUserIds = duplicateUsers
- .filter((duplicateUser) => duplicateUser.id !== user.id)
- .map((duplicateUser) => duplicateUser.id);
- if (nonAcceptedDuplicateUserIds.length > 0) {
- await userDAL.delete(
- {
- $in: {
- id: nonAcceptedDuplicateUserIds
- }
- },
- tx
- );
- }
-
- const us = await userDAL.updateById(user.id, { firstName, lastName, isAccepted: true }, tx);
- if (!us) throw new Error("User not found");
- const userEncKey = await userDAL.upsertUserEncryptionKey(
- us.id,
- {
- encryptionVersion: 2,
- hashedPassword
- },
- tx
- );
-
- const updatedMembersips = await orgDAL.updateMembership(
- { inviteEmail: sanitizedEmail, status: OrgMembershipStatus.Invited, scope: AccessScope.Organization },
- { actorUserId: us.id, status: OrgMembershipStatus.Accepted },
- tx
- );
- const uniqueOrgId = [...new Set(updatedMembersips.map(({ scopeOrgId }) => scopeOrgId))];
- await Promise.allSettled(uniqueOrgId.map((orgId) => licenseService.updateSubscriptionOrgMemberCount(orgId, tx)));
-
- await convertPendingGroupAdditionsToGroupMemberships({
- userIds: [user.id],
- userDAL,
- userGroupMembershipDAL,
- projectKeyDAL,
- projectDAL,
- projectBotDAL,
- membershipGroupDAL,
- tx
- });
-
- return { info: us, key: userEncKey };
- });
-
- const tokenSession = await tokenService.getUserTokenSession({
- userAgent,
- ip,
- userId: updateduser.info.id
- });
- if (!tokenSession) throw new Error("Failed to create token");
-
- const accessToken = crypto.jwt().sign(
- {
- authMethod: AuthMethod.EMAIL,
- authTokenType: AuthTokenType.ACCESS_TOKEN,
- userId: updateduser.info.id,
- tokenVersionId: tokenSession.id,
- accessVersion: tokenSession.accessVersion
- },
- appCfg.AUTH_SECRET,
- { expiresIn: appCfg.JWT_SIGNUP_LIFETIME }
- );
-
- const refreshToken = crypto.jwt().sign(
- {
- authMethod: AuthMethod.EMAIL,
- authTokenType: AuthTokenType.REFRESH_TOKEN,
- userId: updateduser.info.id,
- tokenVersionId: tokenSession.id,
- refreshVersion: tokenSession.refreshVersion
- },
- appCfg.AUTH_SECRET,
- { expiresIn: appCfg.JWT_SIGNUP_LIFETIME }
- );
-
- return { user: updateduser.info, accessToken, refreshToken, organizationId: orgMembership.scopeOrgId };
- };
-
return {
beginEmailSignupProcess,
verifyEmailSignup,
- completeEmailAccountSignup,
- completeAccountInvite
+ completeAccountSignup
};
};
diff --git a/backend/src/services/auth/auth-signup-type.ts b/backend/src/services/auth/auth-signup-type.ts
index 5c4fdc3c95..a9b5d57802 100644
--- a/backend/src/services/auth/auth-signup-type.ts
+++ b/backend/src/services/auth/auth-signup-type.ts
@@ -9,16 +9,4 @@ export type TCompleteAccountSignupDTO = {
ip: string;
userAgent: string;
authorization: string;
- useDefaultOrg?: boolean;
-};
-
-export type TCompleteAccountInviteDTO = {
- email: string;
- password: string;
- firstName: string;
- lastName?: string;
- ip: string;
- userAgent: string;
- authorization: string;
- tokenMetadata?: string;
};