mirror of
https://github.com/awatertrevi/infisical.git
synced 2026-09-22 13:39:35 +00:00
Improve verification and resend code logic, added oidc and ldap
This commit is contained in:
@@ -26,6 +26,12 @@ export async function up(knex: Knex): Promise<void> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!(await knex.schema.hasColumn(TableName.AuthTokens, "aliasId"))) {
|
||||
await knex.schema.alterTable(TableName.AuthTokens, (t) => {
|
||||
t.string("aliasId").nullable();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function down(knex: Knex): Promise<void> {
|
||||
@@ -34,4 +40,10 @@ export async function down(knex: Knex): Promise<void> {
|
||||
t.dropColumn("isEmailVerified");
|
||||
});
|
||||
}
|
||||
|
||||
if (await knex.schema.hasColumn(TableName.AuthTokens, "aliasId")) {
|
||||
await knex.schema.alterTable(TableName.AuthTokens, (t) => {
|
||||
t.dropColumn("aliasId");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,8 @@ export const AuthTokensSchema = z.object({
|
||||
createdAt: z.date(),
|
||||
updatedAt: z.date(),
|
||||
userId: z.string().uuid().nullable().optional(),
|
||||
orgId: z.string().uuid().nullable().optional()
|
||||
orgId: z.string().uuid().nullable().optional(),
|
||||
aliasId: z.string().nullable().optional()
|
||||
});
|
||||
|
||||
export type TAuthTokens = z.infer<typeof AuthTokensSchema>;
|
||||
|
||||
@@ -400,15 +400,13 @@ export const ldapConfigServiceFactory = ({
|
||||
|
||||
userAlias = await userDAL.transaction(async (tx) => {
|
||||
let newUser: TUsers | undefined;
|
||||
if (serverCfg.trustLdapEmails) {
|
||||
newUser = await userDAL.findOne(
|
||||
{
|
||||
email: email.toLowerCase(),
|
||||
isEmailVerified: true
|
||||
},
|
||||
tx
|
||||
);
|
||||
}
|
||||
newUser = await userDAL.findOne(
|
||||
{
|
||||
email: email.toLowerCase(),
|
||||
isEmailVerified: true
|
||||
},
|
||||
tx
|
||||
);
|
||||
|
||||
if (!newUser) {
|
||||
const uniqueUsername = await normalizeUsername(username, userDAL);
|
||||
@@ -433,7 +431,8 @@ export const ldapConfigServiceFactory = ({
|
||||
aliasType: UserAliasType.LDAP,
|
||||
externalId,
|
||||
emails: [email],
|
||||
orgId
|
||||
orgId,
|
||||
isEmailVerified: serverCfg.trustLdapEmails
|
||||
},
|
||||
tx
|
||||
);
|
||||
@@ -556,15 +555,14 @@ export const ldapConfigServiceFactory = ({
|
||||
return newUser;
|
||||
});
|
||||
|
||||
const isUserCompleted = Boolean(user.isAccepted);
|
||||
|
||||
const isUserCompleted = Boolean(user.isAccepted) && userAlias.isEmailVerified;
|
||||
const providerAuthToken = crypto.jwt().sign(
|
||||
{
|
||||
authTokenType: AuthTokenType.PROVIDER_TOKEN,
|
||||
userId: user.id,
|
||||
username: user.username,
|
||||
hasExchangedPrivateKey: true,
|
||||
...(user.email && { email: user.email, isEmailVerified: user.isEmailVerified }),
|
||||
...(user.email && { email: user.email, isEmailVerified: userAlias.isEmailVerified }),
|
||||
firstName,
|
||||
lastName,
|
||||
organizationName: organization.name,
|
||||
@@ -572,6 +570,7 @@ export const ldapConfigServiceFactory = ({
|
||||
organizationSlug: organization.slug,
|
||||
authMethod: AuthMethod.LDAP,
|
||||
authType: UserAliasType.LDAP,
|
||||
aliasId: userAlias.id,
|
||||
isUserCompleted,
|
||||
...(relayState
|
||||
? {
|
||||
@@ -585,10 +584,11 @@ export const ldapConfigServiceFactory = ({
|
||||
}
|
||||
);
|
||||
|
||||
if (user.email && !user.isEmailVerified) {
|
||||
if (user.email && !userAlias.isEmailVerified) {
|
||||
const token = await tokenService.createTokenForUser({
|
||||
type: TokenType.TOKEN_EMAIL_VERIFICATION,
|
||||
userId: user.id
|
||||
userId: user.id,
|
||||
aliasId: userAlias.id
|
||||
});
|
||||
|
||||
await smtpService.sendMail({
|
||||
|
||||
@@ -180,7 +180,7 @@ export const oidcConfigServiceFactory = ({
|
||||
}
|
||||
|
||||
const appCfg = getConfig();
|
||||
const userAlias = await userAliasDAL.findOne({
|
||||
let userAlias = await userAliasDAL.findOne({
|
||||
externalId,
|
||||
orgId,
|
||||
aliasType: UserAliasType.OIDC
|
||||
@@ -231,32 +231,29 @@ export const oidcConfigServiceFactory = ({
|
||||
} else {
|
||||
user = await userDAL.transaction(async (tx) => {
|
||||
let newUser: TUsers | undefined;
|
||||
// we prioritize getting the most complete user to create the new alias under
|
||||
newUser = await userDAL.findOne(
|
||||
{
|
||||
email,
|
||||
isEmailVerified: true
|
||||
},
|
||||
tx
|
||||
);
|
||||
|
||||
if (serverCfg.trustOidcEmails) {
|
||||
// we prioritize getting the most complete user to create the new alias under
|
||||
if (!newUser) {
|
||||
// this fetches user entries created via invites
|
||||
newUser = await userDAL.findOne(
|
||||
{
|
||||
email,
|
||||
isEmailVerified: true
|
||||
username: email
|
||||
},
|
||||
tx
|
||||
);
|
||||
|
||||
if (!newUser) {
|
||||
// this fetches user entries created via invites
|
||||
newUser = await userDAL.findOne(
|
||||
{
|
||||
username: email
|
||||
},
|
||||
tx
|
||||
);
|
||||
|
||||
if (newUser && !newUser.isEmailVerified) {
|
||||
// we automatically mark it as email-verified because we've configured trust for OIDC emails
|
||||
newUser = await userDAL.updateById(newUser.id, {
|
||||
isEmailVerified: true
|
||||
});
|
||||
}
|
||||
if (newUser && !newUser.isEmailVerified) {
|
||||
// we automatically mark it as email-verified because we've configured trust for OIDC emails
|
||||
newUser = await userDAL.updateById(newUser.id, {
|
||||
isEmailVerified: serverCfg.trustOidcEmails
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -276,13 +273,14 @@ export const oidcConfigServiceFactory = ({
|
||||
);
|
||||
}
|
||||
|
||||
await userAliasDAL.create(
|
||||
userAlias = await userAliasDAL.create(
|
||||
{
|
||||
userId: newUser.id,
|
||||
aliasType: UserAliasType.OIDC,
|
||||
externalId,
|
||||
emails: email ? [email] : [],
|
||||
orgId
|
||||
orgId,
|
||||
isEmailVerified: serverCfg.trustOidcEmails
|
||||
},
|
||||
tx
|
||||
);
|
||||
@@ -404,19 +402,20 @@ export const oidcConfigServiceFactory = ({
|
||||
|
||||
await licenseService.updateSubscriptionOrgMemberCount(organization.id);
|
||||
|
||||
const isUserCompleted = Boolean(user.isAccepted);
|
||||
const isUserCompleted = Boolean(user.isAccepted) && userAlias.isEmailVerified;
|
||||
const providerAuthToken = crypto.jwt().sign(
|
||||
{
|
||||
authTokenType: AuthTokenType.PROVIDER_TOKEN,
|
||||
userId: user.id,
|
||||
username: user.username,
|
||||
...(user.email && { email: user.email, isEmailVerified: user.isEmailVerified }),
|
||||
...(user.email && { email: user.email, isEmailVerified: userAlias.isEmailVerified }),
|
||||
firstName,
|
||||
lastName,
|
||||
organizationName: organization.name,
|
||||
organizationId: organization.id,
|
||||
organizationSlug: organization.slug,
|
||||
hasExchangedPrivateKey: true,
|
||||
aliasId: userAlias.id,
|
||||
authMethod: AuthMethod.OIDC,
|
||||
authType: UserAliasType.OIDC,
|
||||
isUserCompleted,
|
||||
@@ -430,10 +429,11 @@ export const oidcConfigServiceFactory = ({
|
||||
|
||||
await oidcConfigDAL.update({ orgId }, { lastUsed: new Date() });
|
||||
|
||||
if (user.email && !user.isEmailVerified) {
|
||||
if (user.email && !userAlias.isEmailVerified) {
|
||||
const token = await tokenService.createTokenForUser({
|
||||
type: TokenType.TOKEN_EMAIL_VERIFICATION,
|
||||
userId: user.id
|
||||
userId: user.id,
|
||||
aliasId: userAlias.id
|
||||
});
|
||||
|
||||
await smtpService
|
||||
|
||||
@@ -443,7 +443,8 @@ export const samlConfigServiceFactory = ({
|
||||
if (user.email && !userAlias.isEmailVerified) {
|
||||
const token = await tokenService.createTokenForUser({
|
||||
type: TokenType.TOKEN_EMAIL_VERIFICATION,
|
||||
userId: user.id
|
||||
userId: user.id,
|
||||
aliasId: userAlias.id
|
||||
});
|
||||
|
||||
await smtpService.sendMail({
|
||||
|
||||
@@ -17,15 +17,15 @@ export const registerUserRouter = async (server: FastifyZodProvider) => {
|
||||
})
|
||||
},
|
||||
schema: {
|
||||
headers: z.object({
|
||||
referer: z.string().trim()
|
||||
body: z.object({
|
||||
token: z.string().trim()
|
||||
}),
|
||||
response: {
|
||||
200: z.object({})
|
||||
}
|
||||
},
|
||||
handler: async (req) => {
|
||||
await server.services.user.sendEmailVerificationCode(req.headers.referer);
|
||||
await server.services.user.sendEmailVerificationCode(req.body.token);
|
||||
return {};
|
||||
}
|
||||
});
|
||||
|
||||
@@ -75,7 +75,7 @@ export const getTokenConfig = (tokenType: TokenType) => {
|
||||
};
|
||||
|
||||
export const tokenServiceFactory = ({ tokenDAL, userDAL, orgMembershipDAL }: TAuthTokenServiceFactoryDep) => {
|
||||
const createTokenForUser = async ({ type, userId, orgId }: TCreateTokenForUserDTO) => {
|
||||
const createTokenForUser = async ({ type, userId, orgId, aliasId }: TCreateTokenForUserDTO) => {
|
||||
const { token, ...tkCfg } = getTokenConfig(type);
|
||||
const appCfg = getConfig();
|
||||
const tokenHash = await crypto.hashing().createHash(token, appCfg.SALT_ROUNDS);
|
||||
@@ -88,7 +88,8 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL, orgMembershipDAL }: TAu
|
||||
type,
|
||||
userId,
|
||||
orgId,
|
||||
triesLeft: tkCfg?.triesLeft
|
||||
triesLeft: tkCfg?.triesLeft,
|
||||
aliasId
|
||||
},
|
||||
tx
|
||||
);
|
||||
|
||||
@@ -14,6 +14,7 @@ export type TCreateTokenForUserDTO = {
|
||||
type: TokenType;
|
||||
userId: string;
|
||||
orgId?: string;
|
||||
aliasId?: string;
|
||||
};
|
||||
|
||||
export type TCreateOrgInviteTokenDTO = {
|
||||
|
||||
@@ -10,7 +10,7 @@ import { TokenType } from "@app/services/auth-token/auth-token-types";
|
||||
import { TOrgMembershipDALFactory } from "@app/services/org-membership/org-membership-dal";
|
||||
import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";
|
||||
|
||||
import { AuthMethod } from "../auth/auth-type";
|
||||
import { AuthMethod, AuthTokenType } from "../auth/auth-type";
|
||||
import { TGroupProjectDALFactory } from "../group-project/group-project-dal";
|
||||
import { TProjectMembershipDALFactory } from "../project-membership/project-membership-dal";
|
||||
import { TUserAliasDALFactory } from "../user-alias/user-alias-dal";
|
||||
@@ -39,7 +39,7 @@ type TUserServiceFactoryDep = {
|
||||
projectMembershipDAL: Pick<TProjectMembershipDALFactory, "find">;
|
||||
smtpService: Pick<TSmtpService, "sendMail">;
|
||||
permissionService: TPermissionServiceFactory;
|
||||
userAliasDAL: Pick<TUserAliasDALFactory, "findOne" | "find" | "update">;
|
||||
userAliasDAL: Pick<TUserAliasDALFactory, "findOne" | "find" | "updateById">;
|
||||
};
|
||||
|
||||
export type TUserServiceFactory = ReturnType<typeof userServiceFactory>;
|
||||
@@ -54,23 +54,23 @@ export const userServiceFactory = ({
|
||||
permissionService,
|
||||
userAliasDAL
|
||||
}: TUserServiceFactoryDep) => {
|
||||
const sendEmailVerificationCode = async (referer: string) => {
|
||||
const url = new URL(referer);
|
||||
const refererToken = url.searchParams.get("token");
|
||||
if (!refererToken)
|
||||
throw new BadRequestError({ name: "Failed to send email verification code due to no token on referer" });
|
||||
const { authType, aliasId, username } = crypto.jwt().decode(refererToken) as {
|
||||
const sendEmailVerificationCode = async (token: string) => {
|
||||
const { authType, aliasId, username, authTokenType } = crypto.jwt().decode(token) as {
|
||||
authType: string;
|
||||
aliasId: string;
|
||||
aliasId?: string;
|
||||
username: string;
|
||||
authTokenType: AuthTokenType;
|
||||
};
|
||||
if (authTokenType !== AuthTokenType.PROVIDER_TOKEN) throw new BadRequestError({ name: "Invalid auth token type" });
|
||||
|
||||
// akhilmhdh: case sensitive email resolution
|
||||
const users = await userDAL.findUserByUsername(username);
|
||||
const user = users?.length > 1 ? users.find((el) => el.username === username) : users?.[0];
|
||||
if (!user) throw new NotFoundError({ name: `User with username '${username}' not found` });
|
||||
let { isEmailVerified } = user;
|
||||
const userAlias = await userAliasDAL.findOne({ userId: user.id, aliasType: authType, id: aliasId });
|
||||
if (userAlias) {
|
||||
if (aliasId) {
|
||||
const userAlias = await userAliasDAL.findOne({ userId: user.id, aliasType: authType, id: aliasId });
|
||||
if (!userAlias) throw new NotFoundError({ name: `User alias with ID '${aliasId}' not found` });
|
||||
isEmailVerified = userAlias.isEmailVerified;
|
||||
}
|
||||
|
||||
@@ -79,9 +79,10 @@ export const userServiceFactory = ({
|
||||
if (isEmailVerified)
|
||||
throw new BadRequestError({ name: "Failed to send email verification code due to email already verified" });
|
||||
|
||||
const token = await tokenService.createTokenForUser({
|
||||
const userToken = await tokenService.createTokenForUser({
|
||||
type: TokenType.TOKEN_EMAIL_VERIFICATION,
|
||||
userId: user.id
|
||||
userId: user.id,
|
||||
aliasId
|
||||
});
|
||||
|
||||
await smtpService.sendMail({
|
||||
@@ -89,7 +90,7 @@ export const userServiceFactory = ({
|
||||
subjectLine: "Infisical confirmation code",
|
||||
recipients: [user.email],
|
||||
substitutions: {
|
||||
code: token
|
||||
code: userToken
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -114,19 +115,20 @@ export const userServiceFactory = ({
|
||||
if (!user.email)
|
||||
throw new BadRequestError({ name: "Failed to verify email verification code due to no email on user" });
|
||||
|
||||
const userAliases = await userAliasDAL.find({ userId: user.id });
|
||||
if (user.isEmailVerified && userAliases?.every((alias) => alias.isEmailVerified))
|
||||
throw new BadRequestError({ name: "Failed to verify email verification code due to email already verified" });
|
||||
|
||||
await tokenService.validateTokenForUser({
|
||||
const token = await tokenService.validateTokenForUser({
|
||||
type: TokenType.TOKEN_EMAIL_VERIFICATION,
|
||||
userId: user.id,
|
||||
code
|
||||
});
|
||||
|
||||
const userEmails = user?.email ? await userDAL.find({ email: user.email }) : [];
|
||||
if (token?.aliasId) {
|
||||
const userAlias = await userAliasDAL.findOne({ userId: user.id, id: token.aliasId });
|
||||
if (userAlias?.isEmailVerified)
|
||||
throw new BadRequestError({ name: "Failed to verify email verification code due to email already verified" });
|
||||
|
||||
await userAliasDAL.update({ userId: user.id }, { isEmailVerified: true });
|
||||
await userAliasDAL.updateById(token.aliasId, { isEmailVerified: true });
|
||||
}
|
||||
const userEmails = user?.email ? await userDAL.find({ email: user.email }) : [];
|
||||
|
||||
await userDAL.updateById(user.id, {
|
||||
isEmailVerified: true,
|
||||
|
||||
@@ -26,16 +26,16 @@ export const useAddUserToWsNonE2EE = () => {
|
||||
});
|
||||
};
|
||||
|
||||
export const sendEmailVerificationCode = async (username: string) => {
|
||||
export const sendEmailVerificationCode = async (token: string) => {
|
||||
return apiRequest.post("/api/v2/users/me/emails/code", {
|
||||
username
|
||||
token
|
||||
});
|
||||
};
|
||||
|
||||
export const useSendEmailVerificationCode = () => {
|
||||
return useMutation({
|
||||
mutationFn: async (username: string) => {
|
||||
await sendEmailVerificationCode(username);
|
||||
mutationFn: async (token: string) => {
|
||||
await sendEmailVerificationCode(token);
|
||||
return {};
|
||||
}
|
||||
});
|
||||
|
||||
@@ -114,7 +114,16 @@ export const EmailConfirmationStep = ({
|
||||
|
||||
const resendCode = async () => {
|
||||
try {
|
||||
await sendEmailVerificationCode(username);
|
||||
const queryParams = new URLSearchParams(window.location.search);
|
||||
const token = queryParams.get("token");
|
||||
if (!token) {
|
||||
createNotification({
|
||||
text: "Failed to resend code, no token found",
|
||||
type: "error"
|
||||
});
|
||||
return;
|
||||
}
|
||||
await sendEmailVerificationCode(token);
|
||||
createNotification({
|
||||
text: "Successfully resent code",
|
||||
type: "success"
|
||||
|
||||
Reference in New Issue
Block a user