mirror of
https://github.com/awatertrevi/infisical.git
synced 2026-10-07 17:27:40 +00:00
Merge pull request #2597 from Infisical/feat/moved-mfa-to-org-level
feat: moved mfa to org level
This commit is contained in:
@@ -39,8 +39,6 @@ describe("Login V1 Router", async () => {
|
|||||||
});
|
});
|
||||||
expect(res.statusCode).toBe(200);
|
expect(res.statusCode).toBe(200);
|
||||||
const payload = JSON.parse(res.payload);
|
const payload = JSON.parse(res.payload);
|
||||||
expect(payload).toHaveProperty("mfaEnabled");
|
|
||||||
expect(payload).toHaveProperty("token");
|
expect(payload).toHaveProperty("token");
|
||||||
expect(payload.mfaEnabled).toBeFalsy();
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { Knex } from "knex";
|
||||||
|
|
||||||
|
import { TableName } from "../schemas";
|
||||||
|
|
||||||
|
export async function up(knex: Knex): Promise<void> {
|
||||||
|
if (!(await knex.schema.hasColumn(TableName.Organization, "enforceMfa"))) {
|
||||||
|
await knex.schema.alterTable(TableName.Organization, (tb) => {
|
||||||
|
tb.boolean("enforceMfa").defaultTo(false).notNullable();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function down(knex: Knex): Promise<void> {
|
||||||
|
if (await knex.schema.hasColumn(TableName.Organization, "enforceMfa")) {
|
||||||
|
await knex.schema.alterTable(TableName.Organization, (t) => {
|
||||||
|
t.dropColumn("enforceMfa");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -20,7 +20,8 @@ export const OrganizationsSchema = z.object({
|
|||||||
scimEnabled: z.boolean().default(false).nullable().optional(),
|
scimEnabled: z.boolean().default(false).nullable().optional(),
|
||||||
kmsDefaultKeyId: z.string().uuid().nullable().optional(),
|
kmsDefaultKeyId: z.string().uuid().nullable().optional(),
|
||||||
kmsEncryptedDataKey: zodBuffer.nullable().optional(),
|
kmsEncryptedDataKey: zodBuffer.nullable().optional(),
|
||||||
defaultMembershipRole: z.string().default("member")
|
defaultMembershipRole: z.string().default("member"),
|
||||||
|
enforceMfa: z.boolean().default(false)
|
||||||
});
|
});
|
||||||
|
|
||||||
export type TOrganizations = z.infer<typeof OrganizationsSchema>;
|
export type TOrganizations = z.infer<typeof OrganizationsSchema>;
|
||||||
|
|||||||
@@ -46,7 +46,8 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({
|
|||||||
writeLimit: 200,
|
writeLimit: 200,
|
||||||
secretsLimit: 40
|
secretsLimit: 40
|
||||||
},
|
},
|
||||||
pkiEst: false
|
pkiEst: false,
|
||||||
|
enforceMfa: false
|
||||||
});
|
});
|
||||||
|
|
||||||
export const setupLicenseRequestWithStore = (baseURL: string, refreshUrl: string, licenseKey: string) => {
|
export const setupLicenseRequestWithStore = (baseURL: string, refreshUrl: string, licenseKey: string) => {
|
||||||
|
|||||||
@@ -64,6 +64,7 @@ export type TFeatureSet = {
|
|||||||
secretsLimit: number;
|
secretsLimit: number;
|
||||||
};
|
};
|
||||||
pkiEst: boolean;
|
pkiEst: boolean;
|
||||||
|
enforceMfa: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type TOrgPlansTableDTO = {
|
export type TOrgPlansTableDTO = {
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ export type TAuthMode =
|
|||||||
user: TUsers;
|
user: TUsers;
|
||||||
orgId: string;
|
orgId: string;
|
||||||
authMethod: AuthMethod;
|
authMethod: AuthMethod;
|
||||||
|
isMfaVerified?: boolean;
|
||||||
}
|
}
|
||||||
| {
|
| {
|
||||||
authMode: AuthMode.API_KEY;
|
authMode: AuthMode.API_KEY;
|
||||||
@@ -121,7 +122,8 @@ export const injectIdentity = fp(async (server: FastifyZodProvider) => {
|
|||||||
tokenVersionId,
|
tokenVersionId,
|
||||||
actor,
|
actor,
|
||||||
orgId: orgId as string,
|
orgId: orgId as string,
|
||||||
authMethod: token.authMethod
|
authMethod: token.authMethod,
|
||||||
|
isMfaVerified: token.isMfaVerified
|
||||||
};
|
};
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -107,7 +107,8 @@ export const registerAuthRoutes = async (server: FastifyZodProvider) => {
|
|||||||
userId: decodedToken.userId,
|
userId: decodedToken.userId,
|
||||||
tokenVersionId: tokenVersion.id,
|
tokenVersionId: tokenVersion.id,
|
||||||
accessVersion: tokenVersion.accessVersion,
|
accessVersion: tokenVersion.accessVersion,
|
||||||
organizationId: decodedToken.organizationId
|
organizationId: decodedToken.organizationId,
|
||||||
|
isMfaVerified: decodedToken.isMfaVerified
|
||||||
},
|
},
|
||||||
appCfg.AUTH_SECRET,
|
appCfg.AUTH_SECRET,
|
||||||
{ expiresIn: appCfg.JWT_AUTH_LIFETIME }
|
{ expiresIn: appCfg.JWT_AUTH_LIFETIME }
|
||||||
|
|||||||
@@ -258,7 +258,8 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {
|
|||||||
.refine((v) => slugify(v) === v, {
|
.refine((v) => slugify(v) === v, {
|
||||||
message: "Membership role must be a valid slug"
|
message: "Membership role must be a valid slug"
|
||||||
})
|
})
|
||||||
.optional()
|
.optional(),
|
||||||
|
enforceMfa: z.boolean().optional()
|
||||||
}),
|
}),
|
||||||
response: {
|
response: {
|
||||||
200: z.object({
|
200: z.object({
|
||||||
|
|||||||
@@ -280,10 +280,6 @@ export const registerSsoRouter = async (server: FastifyZodProvider) => {
|
|||||||
providerAuthToken: req.body.providerAuthToken
|
providerAuthToken: req.body.providerAuthToken
|
||||||
});
|
});
|
||||||
|
|
||||||
if (data.isMfaEnabled) {
|
|
||||||
return { mfaEnabled: true, token: data.token } as const; // for discriminated union
|
|
||||||
}
|
|
||||||
|
|
||||||
void res.setCookie("jid", data.token.refresh, {
|
void res.setCookie("jid", data.token.refresh, {
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
path: "/",
|
path: "/",
|
||||||
@@ -292,7 +288,6 @@ export const registerSsoRouter = async (server: FastifyZodProvider) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
mfaEnabled: false,
|
|
||||||
encryptionVersion: data.user.encryptionVersion,
|
encryptionVersion: data.user.encryptionVersion,
|
||||||
token: data.token.access,
|
token: data.token.access,
|
||||||
publicKey: data.user.publicKey,
|
publicKey: data.user.publicKey,
|
||||||
|
|||||||
@@ -47,7 +47,8 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
|
|||||||
}),
|
}),
|
||||||
response: {
|
response: {
|
||||||
200: z.object({
|
200: z.object({
|
||||||
token: z.string()
|
token: z.string(),
|
||||||
|
isMfaEnabled: z.boolean()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -60,6 +61,13 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
|
|||||||
ipAddress: req.realIp
|
ipAddress: req.realIp
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (tokens.isMfaEnabled) {
|
||||||
|
return {
|
||||||
|
token: tokens.mfa as string,
|
||||||
|
isMfaEnabled: true
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
void res.setCookie("jid", tokens.refresh, {
|
void res.setCookie("jid", tokens.refresh, {
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
path: "/",
|
path: "/",
|
||||||
@@ -67,7 +75,7 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
|
|||||||
secure: cfg.HTTPS_ENABLED
|
secure: cfg.HTTPS_ENABLED
|
||||||
});
|
});
|
||||||
|
|
||||||
return { token: tokens.access };
|
return { token: tokens.access, isMfaEnabled: false };
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -86,10 +94,7 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
|
|||||||
password: z.string().optional()
|
password: z.string().optional()
|
||||||
}),
|
}),
|
||||||
response: {
|
response: {
|
||||||
200: z.discriminatedUnion("mfaEnabled", [
|
200: z.object({
|
||||||
z.object({ mfaEnabled: z.literal(true), token: z.string() }),
|
|
||||||
z.object({
|
|
||||||
mfaEnabled: z.literal(false),
|
|
||||||
encryptionVersion: z.number().default(1).nullable().optional(),
|
encryptionVersion: z.number().default(1).nullable().optional(),
|
||||||
protectedKey: z.string().nullable(),
|
protectedKey: z.string().nullable(),
|
||||||
protectedKeyIV: z.string().nullable(),
|
protectedKeyIV: z.string().nullable(),
|
||||||
@@ -100,7 +105,6 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
|
|||||||
tag: z.string(),
|
tag: z.string(),
|
||||||
token: z.string()
|
token: z.string()
|
||||||
})
|
})
|
||||||
])
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
handler: async (req, res) => {
|
handler: async (req, res) => {
|
||||||
@@ -118,10 +122,6 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
|
|||||||
password: req.body.password
|
password: req.body.password
|
||||||
});
|
});
|
||||||
|
|
||||||
if (data.isMfaEnabled) {
|
|
||||||
return { mfaEnabled: true, token: data.token } as const; // for discriminated union
|
|
||||||
}
|
|
||||||
|
|
||||||
void res.setCookie("jid", data.token.refresh, {
|
void res.setCookie("jid", data.token.refresh, {
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
path: "/",
|
path: "/",
|
||||||
@@ -130,7 +130,6 @@ export const registerLoginRouter = async (server: FastifyZodProvider) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
mfaEnabled: false,
|
|
||||||
encryptionVersion: data.user.encryptionVersion,
|
encryptionVersion: data.user.encryptionVersion,
|
||||||
token: data.token.access,
|
token: data.token.access,
|
||||||
publicKey: data.user.publicKey,
|
publicKey: data.user.publicKey,
|
||||||
|
|||||||
@@ -99,13 +99,15 @@ export const authLoginServiceFactory = ({
|
|||||||
ip,
|
ip,
|
||||||
userAgent,
|
userAgent,
|
||||||
organizationId,
|
organizationId,
|
||||||
authMethod
|
authMethod,
|
||||||
|
isMfaVerified
|
||||||
}: {
|
}: {
|
||||||
user: TUsers;
|
user: TUsers;
|
||||||
ip: string;
|
ip: string;
|
||||||
userAgent: string;
|
userAgent: string;
|
||||||
organizationId?: string;
|
organizationId?: string;
|
||||||
authMethod: AuthMethod;
|
authMethod: AuthMethod;
|
||||||
|
isMfaVerified?: boolean;
|
||||||
}) => {
|
}) => {
|
||||||
const cfg = getConfig();
|
const cfg = getConfig();
|
||||||
await updateUserDeviceSession(user, ip, userAgent);
|
await updateUserDeviceSession(user, ip, userAgent);
|
||||||
@@ -123,7 +125,8 @@ export const authLoginServiceFactory = ({
|
|||||||
userId: user.id,
|
userId: user.id,
|
||||||
tokenVersionId: tokenSession.id,
|
tokenVersionId: tokenSession.id,
|
||||||
accessVersion: tokenSession.accessVersion,
|
accessVersion: tokenSession.accessVersion,
|
||||||
organizationId
|
organizationId,
|
||||||
|
isMfaVerified
|
||||||
},
|
},
|
||||||
cfg.AUTH_SECRET,
|
cfg.AUTH_SECRET,
|
||||||
{ expiresIn: cfg.JWT_AUTH_LIFETIME }
|
{ expiresIn: cfg.JWT_AUTH_LIFETIME }
|
||||||
@@ -136,7 +139,8 @@ export const authLoginServiceFactory = ({
|
|||||||
userId: user.id,
|
userId: user.id,
|
||||||
tokenVersionId: tokenSession.id,
|
tokenVersionId: tokenSession.id,
|
||||||
refreshVersion: tokenSession.refreshVersion,
|
refreshVersion: tokenSession.refreshVersion,
|
||||||
organizationId
|
organizationId,
|
||||||
|
isMfaVerified
|
||||||
},
|
},
|
||||||
cfg.AUTH_SECRET,
|
cfg.AUTH_SECRET,
|
||||||
{ expiresIn: cfg.JWT_REFRESH_LIFETIME }
|
{ expiresIn: cfg.JWT_REFRESH_LIFETIME }
|
||||||
@@ -298,30 +302,6 @@ export const authLoginServiceFactory = ({
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// send multi factor auth token if they it enabled
|
|
||||||
if (userEnc.isMfaEnabled && userEnc.email) {
|
|
||||||
enforceUserLockStatus(Boolean(user.isLocked), user.temporaryLockDateEnd);
|
|
||||||
|
|
||||||
const mfaToken = jwt.sign(
|
|
||||||
{
|
|
||||||
authMethod,
|
|
||||||
authTokenType: AuthTokenType.MFA_TOKEN,
|
|
||||||
userId: userEnc.userId
|
|
||||||
},
|
|
||||||
cfg.AUTH_SECRET,
|
|
||||||
{
|
|
||||||
expiresIn: cfg.JWT_MFA_LIFETIME
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
await sendUserMfaCode({
|
|
||||||
userId: userEnc.userId,
|
|
||||||
email: userEnc.email
|
|
||||||
});
|
|
||||||
|
|
||||||
return { isMfaEnabled: true, token: mfaToken } as const;
|
|
||||||
}
|
|
||||||
|
|
||||||
const token = await generateUserTokens({
|
const token = await generateUserTokens({
|
||||||
user: {
|
user: {
|
||||||
...userEnc,
|
...userEnc,
|
||||||
@@ -333,7 +313,7 @@ export const authLoginServiceFactory = ({
|
|||||||
organizationId
|
organizationId
|
||||||
});
|
});
|
||||||
|
|
||||||
return { token, isMfaEnabled: false, user: userEnc } as const;
|
return { token, user: userEnc } as const;
|
||||||
};
|
};
|
||||||
|
|
||||||
const selectOrganization = async ({
|
const selectOrganization = async ({
|
||||||
@@ -373,15 +353,43 @@ export const authLoginServiceFactory = ({
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// send multi factor auth token if they it enabled
|
||||||
|
if ((selectedOrg.enforceMfa || user.isMfaEnabled) && user.email && !decodedToken.isMfaVerified) {
|
||||||
|
enforceUserLockStatus(Boolean(user.isLocked), user.temporaryLockDateEnd);
|
||||||
|
|
||||||
|
const mfaToken = jwt.sign(
|
||||||
|
{
|
||||||
|
authMethod: decodedToken.authMethod,
|
||||||
|
authTokenType: AuthTokenType.MFA_TOKEN,
|
||||||
|
userId: user.id
|
||||||
|
},
|
||||||
|
cfg.AUTH_SECRET,
|
||||||
|
{
|
||||||
|
expiresIn: cfg.JWT_MFA_LIFETIME
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
await sendUserMfaCode({
|
||||||
|
userId: user.id,
|
||||||
|
email: user.email
|
||||||
|
});
|
||||||
|
|
||||||
|
return { isMfaEnabled: true, mfa: mfaToken } as const;
|
||||||
|
}
|
||||||
|
|
||||||
const tokens = await generateUserTokens({
|
const tokens = await generateUserTokens({
|
||||||
authMethod: decodedToken.authMethod,
|
authMethod: decodedToken.authMethod,
|
||||||
user,
|
user,
|
||||||
userAgent,
|
userAgent,
|
||||||
ip: ipAddress,
|
ip: ipAddress,
|
||||||
organizationId
|
organizationId,
|
||||||
|
isMfaVerified: decodedToken.isMfaVerified
|
||||||
});
|
});
|
||||||
|
|
||||||
return tokens;
|
return {
|
||||||
|
...tokens,
|
||||||
|
isMfaEnabled: false
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -504,7 +512,8 @@ export const authLoginServiceFactory = ({
|
|||||||
ip,
|
ip,
|
||||||
userAgent,
|
userAgent,
|
||||||
organizationId: orgId,
|
organizationId: orgId,
|
||||||
authMethod: decodedToken.authMethod
|
authMethod: decodedToken.authMethod,
|
||||||
|
isMfaVerified: true
|
||||||
});
|
});
|
||||||
|
|
||||||
return { token, user: userEnc };
|
return { token, user: userEnc };
|
||||||
@@ -629,7 +638,6 @@ export const authLoginServiceFactory = ({
|
|||||||
const oauth2TokenExchange = async ({ userAgent, ip, providerAuthToken, email }: TOauthTokenExchangeDTO) => {
|
const oauth2TokenExchange = async ({ userAgent, ip, providerAuthToken, email }: TOauthTokenExchangeDTO) => {
|
||||||
const decodedProviderToken = validateProviderAuthToken(providerAuthToken, email);
|
const decodedProviderToken = validateProviderAuthToken(providerAuthToken, email);
|
||||||
|
|
||||||
const appCfg = getConfig();
|
|
||||||
const { authMethod, userName } = decodedProviderToken;
|
const { authMethod, userName } = decodedProviderToken;
|
||||||
if (!userName) throw new BadRequestError({ message: "Missing user name" });
|
if (!userName) throw new BadRequestError({ message: "Missing user name" });
|
||||||
const organizationId =
|
const organizationId =
|
||||||
@@ -644,29 +652,6 @@ export const authLoginServiceFactory = ({
|
|||||||
if (!userEnc) throw new BadRequestError({ message: "Invalid token" });
|
if (!userEnc) throw new BadRequestError({ message: "Invalid token" });
|
||||||
if (!userEnc.serverEncryptedPrivateKey)
|
if (!userEnc.serverEncryptedPrivateKey)
|
||||||
throw new BadRequestError({ message: "Key handoff incomplete. Please try logging in again." });
|
throw new BadRequestError({ message: "Key handoff incomplete. Please try logging in again." });
|
||||||
// send multi factor auth token if they it enabled
|
|
||||||
if (userEnc.isMfaEnabled && userEnc.email) {
|
|
||||||
enforceUserLockStatus(Boolean(userEnc.isLocked), userEnc.temporaryLockDateEnd);
|
|
||||||
|
|
||||||
const mfaToken = jwt.sign(
|
|
||||||
{
|
|
||||||
authMethod,
|
|
||||||
authTokenType: AuthTokenType.MFA_TOKEN,
|
|
||||||
userId: userEnc.userId
|
|
||||||
},
|
|
||||||
appCfg.AUTH_SECRET,
|
|
||||||
{
|
|
||||||
expiresIn: appCfg.JWT_MFA_LIFETIME
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
await sendUserMfaCode({
|
|
||||||
userId: userEnc.userId,
|
|
||||||
email: userEnc.email
|
|
||||||
});
|
|
||||||
|
|
||||||
return { isMfaEnabled: true, token: mfaToken } as const;
|
|
||||||
}
|
|
||||||
|
|
||||||
const token = await generateUserTokens({
|
const token = await generateUserTokens({
|
||||||
user: { ...userEnc, id: userEnc.userId },
|
user: { ...userEnc, id: userEnc.userId },
|
||||||
|
|||||||
@@ -52,6 +52,7 @@ export type AuthModeJwtTokenPayload = {
|
|||||||
tokenVersionId: string;
|
tokenVersionId: string;
|
||||||
accessVersion: number;
|
accessVersion: number;
|
||||||
organizationId?: string;
|
organizationId?: string;
|
||||||
|
isMfaVerified?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type AuthModeMfaJwtTokenPayload = {
|
export type AuthModeMfaJwtTokenPayload = {
|
||||||
@@ -69,6 +70,7 @@ export type AuthModeRefreshJwtTokenPayload = {
|
|||||||
tokenVersionId: string;
|
tokenVersionId: string;
|
||||||
refreshVersion: number;
|
refreshVersion: number;
|
||||||
organizationId?: string;
|
organizationId?: string;
|
||||||
|
isMfaVerified?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type AuthModeProviderJwtTokenPayload = {
|
export type AuthModeProviderJwtTokenPayload = {
|
||||||
|
|||||||
@@ -268,13 +268,28 @@ export const orgServiceFactory = ({
|
|||||||
actorOrgId,
|
actorOrgId,
|
||||||
actorAuthMethod,
|
actorAuthMethod,
|
||||||
orgId,
|
orgId,
|
||||||
data: { name, slug, authEnforced, scimEnabled, defaultMembershipRoleSlug }
|
data: { name, slug, authEnforced, scimEnabled, defaultMembershipRoleSlug, enforceMfa }
|
||||||
}: TUpdateOrgDTO) => {
|
}: TUpdateOrgDTO) => {
|
||||||
|
const appCfg = getConfig();
|
||||||
const { permission } = await permissionService.getOrgPermission(actor, actorId, orgId, actorAuthMethod, actorOrgId);
|
const { permission } = await permissionService.getOrgPermission(actor, actorId, orgId, actorAuthMethod, actorOrgId);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Settings);
|
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Settings);
|
||||||
|
|
||||||
const plan = await licenseService.getPlan(orgId);
|
const plan = await licenseService.getPlan(orgId);
|
||||||
|
|
||||||
|
if (enforceMfa !== undefined) {
|
||||||
|
if (!plan.enforceMfa) {
|
||||||
|
throw new BadRequestError({
|
||||||
|
message: "Failed to enforce user MFA due to plan restriction. Upgrade plan to enforce/un-enforce MFA."
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!appCfg.isSmtpConfigured) {
|
||||||
|
throw new BadRequestError({
|
||||||
|
message: "Failed to enforce user MFA due to missing instance SMTP configuration."
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (authEnforced !== undefined) {
|
if (authEnforced !== undefined) {
|
||||||
if (!plan?.samlSSO || !plan.oidcSSO)
|
if (!plan?.samlSSO || !plan.oidcSSO)
|
||||||
throw new BadRequestError({
|
throw new BadRequestError({
|
||||||
@@ -317,7 +332,8 @@ export const orgServiceFactory = ({
|
|||||||
slug: slug ? slugify(slug) : undefined,
|
slug: slug ? slugify(slug) : undefined,
|
||||||
authEnforced,
|
authEnforced,
|
||||||
scimEnabled,
|
scimEnabled,
|
||||||
defaultMembershipRole
|
defaultMembershipRole,
|
||||||
|
enforceMfa
|
||||||
});
|
});
|
||||||
if (!org) throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });
|
if (!org) throw new NotFoundError({ message: `Organization with ID '${orgId}' not found` });
|
||||||
return org;
|
return org;
|
||||||
|
|||||||
@@ -64,6 +64,7 @@ export type TUpdateOrgDTO = {
|
|||||||
authEnforced: boolean;
|
authEnforced: boolean;
|
||||||
scimEnabled: boolean;
|
scimEnabled: boolean;
|
||||||
defaultMembershipRoleSlug: string;
|
defaultMembershipRoleSlug: string;
|
||||||
|
enforceMfa: boolean;
|
||||||
}>;
|
}>;
|
||||||
} & TOrgPermission;
|
} & TOrgPermission;
|
||||||
|
|
||||||
|
|||||||
@@ -137,6 +137,7 @@ type GetOrganizationsResponse struct {
|
|||||||
|
|
||||||
type SelectOrganizationResponse struct {
|
type SelectOrganizationResponse struct {
|
||||||
Token string `json:"token"`
|
Token string `json:"token"`
|
||||||
|
MfaEnabled bool `json:"isMfaEnabled"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type SelectOrganizationRequest struct {
|
type SelectOrganizationRequest struct {
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ package cmd
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
"github.com/Infisical/infisical-merge/packages/api"
|
"github.com/Infisical/infisical-merge/packages/api"
|
||||||
"github.com/Infisical/infisical-merge/packages/models"
|
"github.com/Infisical/infisical-merge/packages/models"
|
||||||
@@ -75,6 +76,42 @@ var initCmd = &cobra.Command{
|
|||||||
selectedOrganization := organizations[index]
|
selectedOrganization := organizations[index]
|
||||||
|
|
||||||
tokenResponse, err := api.CallSelectOrganization(httpClient, api.SelectOrganizationRequest{OrganizationId: selectedOrganization.ID})
|
tokenResponse, err := api.CallSelectOrganization(httpClient, api.SelectOrganizationRequest{OrganizationId: selectedOrganization.ID})
|
||||||
|
if tokenResponse.MfaEnabled {
|
||||||
|
i := 1
|
||||||
|
for i < 6 {
|
||||||
|
mfaVerifyCode := askForMFACode()
|
||||||
|
|
||||||
|
httpClient := resty.New()
|
||||||
|
httpClient.SetAuthToken(tokenResponse.Token)
|
||||||
|
verifyMFAresponse, mfaErrorResponse, requestError := api.CallVerifyMfaToken(httpClient, api.VerifyMfaTokenRequest{
|
||||||
|
Email: userCreds.UserCredentials.Email,
|
||||||
|
MFAToken: mfaVerifyCode,
|
||||||
|
})
|
||||||
|
if requestError != nil {
|
||||||
|
util.HandleError(err)
|
||||||
|
break
|
||||||
|
} else if mfaErrorResponse != nil {
|
||||||
|
if mfaErrorResponse.Context.Code == "mfa_invalid" {
|
||||||
|
msg := fmt.Sprintf("Incorrect, verification code. You have %v attempts left", 5-i)
|
||||||
|
fmt.Println(msg)
|
||||||
|
if i == 5 {
|
||||||
|
util.PrintErrorMessageAndExit("No tries left, please try again in a bit")
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if mfaErrorResponse.Context.Code == "mfa_expired" {
|
||||||
|
util.PrintErrorMessageAndExit("Your 2FA verification code has expired, please try logging in again")
|
||||||
|
break
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
} else {
|
||||||
|
httpClient.SetAuthToken(verifyMFAresponse.Token)
|
||||||
|
tokenResponse, err = api.CallSelectOrganization(httpClient, api.SelectOrganizationRequest{OrganizationId: selectedOrganization.ID})
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
util.HandleError(err, "Unable to select organization")
|
util.HandleError(err, "Unable to select organization")
|
||||||
|
|||||||
@@ -479,7 +479,7 @@ func cliDefaultLogin(userCredentialsToBeStored *models.UserCredentials) {
|
|||||||
util.PrintErrorMessageAndExit("We were unable to fetch required details to complete your login. Run with -d to see more info")
|
util.PrintErrorMessageAndExit("We were unable to fetch required details to complete your login. Run with -d to see more info")
|
||||||
}
|
}
|
||||||
// Login is successful so ask user to choose organization
|
// Login is successful so ask user to choose organization
|
||||||
newJwtToken := GetJwtTokenWithOrganizationId(loginTwoResponse.Token)
|
newJwtToken := GetJwtTokenWithOrganizationId(loginTwoResponse.Token, email)
|
||||||
|
|
||||||
//updating usercredentials
|
//updating usercredentials
|
||||||
userCredentialsToBeStored.Email = email
|
userCredentialsToBeStored.Email = email
|
||||||
@@ -718,7 +718,7 @@ func getFreshUserCredentials(email string, password string) (*api.GetLoginOneV2R
|
|||||||
return &loginOneResponseResult, &loginTwoResponseResult, nil
|
return &loginOneResponseResult, &loginTwoResponseResult, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetJwtTokenWithOrganizationId(oldJwtToken string) string {
|
func GetJwtTokenWithOrganizationId(oldJwtToken string, email string) string {
|
||||||
log.Debug().Msg(fmt.Sprint("GetJwtTokenWithOrganizationId: ", "oldJwtToken", oldJwtToken))
|
log.Debug().Msg(fmt.Sprint("GetJwtTokenWithOrganizationId: ", "oldJwtToken", oldJwtToken))
|
||||||
|
|
||||||
httpClient := resty.New()
|
httpClient := resty.New()
|
||||||
@@ -747,11 +747,51 @@ func GetJwtTokenWithOrganizationId(oldJwtToken string) string {
|
|||||||
selectedOrganization := organizations[index]
|
selectedOrganization := organizations[index]
|
||||||
|
|
||||||
selectedOrgRes, err := api.CallSelectOrganization(httpClient, api.SelectOrganizationRequest{OrganizationId: selectedOrganization.ID})
|
selectedOrgRes, err := api.CallSelectOrganization(httpClient, api.SelectOrganizationRequest{OrganizationId: selectedOrganization.ID})
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
util.HandleError(err)
|
util.HandleError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if selectedOrgRes.MfaEnabled {
|
||||||
|
i := 1
|
||||||
|
for i < 6 {
|
||||||
|
mfaVerifyCode := askForMFACode()
|
||||||
|
|
||||||
|
httpClient := resty.New()
|
||||||
|
httpClient.SetAuthToken(selectedOrgRes.Token)
|
||||||
|
verifyMFAresponse, mfaErrorResponse, requestError := api.CallVerifyMfaToken(httpClient, api.VerifyMfaTokenRequest{
|
||||||
|
Email: email,
|
||||||
|
MFAToken: mfaVerifyCode,
|
||||||
|
})
|
||||||
|
if requestError != nil {
|
||||||
|
util.HandleError(err)
|
||||||
|
break
|
||||||
|
} else if mfaErrorResponse != nil {
|
||||||
|
if mfaErrorResponse.Context.Code == "mfa_invalid" {
|
||||||
|
msg := fmt.Sprintf("Incorrect, verification code. You have %v attempts left", 5-i)
|
||||||
|
fmt.Println(msg)
|
||||||
|
if i == 5 {
|
||||||
|
util.PrintErrorMessageAndExit("No tries left, please try again in a bit")
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if mfaErrorResponse.Context.Code == "mfa_expired" {
|
||||||
|
util.PrintErrorMessageAndExit("Your 2FA verification code has expired, please try logging in again")
|
||||||
|
break
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
} else {
|
||||||
|
httpClient.SetAuthToken(verifyMFAresponse.Token)
|
||||||
|
selectedOrgRes, err = api.CallSelectOrganization(httpClient, api.SelectOrganizationRequest{OrganizationId: selectedOrganization.ID})
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
util.HandleError(err, "Unable to select organization")
|
||||||
|
}
|
||||||
|
|
||||||
return selectedOrgRes.Token
|
return selectedOrgRes.Token
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ export const selectOrganization = async (data: {
|
|||||||
organizationId: string;
|
organizationId: string;
|
||||||
userAgent?: UserAgentType;
|
userAgent?: UserAgentType;
|
||||||
}) => {
|
}) => {
|
||||||
const { data: res } = await apiRequest.post<{ token: string }>(
|
const { data: res } = await apiRequest.post<{ token: string; isMfaEnabled: boolean }>(
|
||||||
"/api/v3/auth/select-organization",
|
"/api/v3/auth/select-organization",
|
||||||
data
|
data
|
||||||
);
|
);
|
||||||
@@ -79,7 +79,7 @@ export const useSelectOrganization = () => {
|
|||||||
const data = await selectOrganization(details);
|
const data = await selectOrganization(details);
|
||||||
|
|
||||||
// If a custom user agent is set, then this session is meant for another consuming application, not the web application.
|
// If a custom user agent is set, then this session is meant for another consuming application, not the web application.
|
||||||
if (!details.userAgent) {
|
if (!details.userAgent && !data.isMfaEnabled) {
|
||||||
SecurityClient.setToken(data.token);
|
SecurityClient.setToken(data.token);
|
||||||
SecurityClient.setProviderAuthToken("");
|
SecurityClient.setProviderAuthToken("");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -84,13 +84,22 @@ export const useCreateOrg = (options: { invalidate: boolean } = { invalidate: tr
|
|||||||
export const useUpdateOrg = () => {
|
export const useUpdateOrg = () => {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
return useMutation<{}, {}, UpdateOrgDTO>({
|
return useMutation<{}, {}, UpdateOrgDTO>({
|
||||||
mutationFn: ({ name, authEnforced, scimEnabled, slug, orgId, defaultMembershipRoleSlug }) => {
|
mutationFn: ({
|
||||||
|
name,
|
||||||
|
authEnforced,
|
||||||
|
scimEnabled,
|
||||||
|
slug,
|
||||||
|
orgId,
|
||||||
|
defaultMembershipRoleSlug,
|
||||||
|
enforceMfa
|
||||||
|
}) => {
|
||||||
return apiRequest.patch(`/api/v1/organization/${orgId}`, {
|
return apiRequest.patch(`/api/v1/organization/${orgId}`, {
|
||||||
name,
|
name,
|
||||||
authEnforced,
|
authEnforced,
|
||||||
scimEnabled,
|
scimEnabled,
|
||||||
slug,
|
slug,
|
||||||
defaultMembershipRoleSlug
|
defaultMembershipRoleSlug,
|
||||||
|
enforceMfa
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ export type Organization = {
|
|||||||
scimEnabled: boolean;
|
scimEnabled: boolean;
|
||||||
slug: string;
|
slug: string;
|
||||||
defaultMembershipRole: string;
|
defaultMembershipRole: string;
|
||||||
|
enforceMfa: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type UpdateOrgDTO = {
|
export type UpdateOrgDTO = {
|
||||||
@@ -20,6 +21,7 @@ export type UpdateOrgDTO = {
|
|||||||
scimEnabled?: boolean;
|
scimEnabled?: boolean;
|
||||||
slug?: string;
|
slug?: string;
|
||||||
defaultMembershipRoleSlug?: string;
|
defaultMembershipRoleSlug?: string;
|
||||||
|
enforceMfa?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type BillingDetails = {
|
export type BillingDetails = {
|
||||||
|
|||||||
@@ -42,4 +42,5 @@ export type SubscriptionPlan = {
|
|||||||
instanceUserManagement: boolean;
|
instanceUserManagement: boolean;
|
||||||
externalKms: boolean;
|
externalKms: boolean;
|
||||||
pkiEst: boolean;
|
pkiEst: boolean;
|
||||||
|
enforceMfa: boolean;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
/* eslint-disable no-var */
|
/* eslint-disable no-var */
|
||||||
/* eslint-disable func-names */
|
/* eslint-disable func-names */
|
||||||
|
|
||||||
import { useEffect, useMemo } from "react";
|
import { useEffect, useMemo, useState } from "react";
|
||||||
import { Controller, useForm } from "react-hook-form";
|
import { Controller, useForm } from "react-hook-form";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
@@ -35,6 +35,7 @@ import * as yup from "yup";
|
|||||||
import { createNotification } from "@app/components/notifications";
|
import { createNotification } from "@app/components/notifications";
|
||||||
import { OrgPermissionCan } from "@app/components/permissions";
|
import { OrgPermissionCan } from "@app/components/permissions";
|
||||||
import { tempLocalStorage } from "@app/components/utilities/checks/tempLocalStorage";
|
import { tempLocalStorage } from "@app/components/utilities/checks/tempLocalStorage";
|
||||||
|
import SecurityClient from "@app/components/utilities/SecurityClient";
|
||||||
import {
|
import {
|
||||||
Accordion,
|
Accordion,
|
||||||
AccordionContent,
|
AccordionContent,
|
||||||
@@ -64,7 +65,7 @@ import {
|
|||||||
useUser,
|
useUser,
|
||||||
useWorkspace
|
useWorkspace
|
||||||
} from "@app/context";
|
} from "@app/context";
|
||||||
import { usePopUp } from "@app/hooks";
|
import { usePopUp, useToggle } from "@app/hooks";
|
||||||
import {
|
import {
|
||||||
fetchOrgUsers,
|
fetchOrgUsers,
|
||||||
useAddUserToWsNonE2EE,
|
useAddUserToWsNonE2EE,
|
||||||
@@ -82,6 +83,7 @@ import { useUpdateUserProjectFavorites } from "@app/hooks/api/users/mutation";
|
|||||||
import { useGetUserProjectFavorites } from "@app/hooks/api/users/queries";
|
import { useGetUserProjectFavorites } from "@app/hooks/api/users/queries";
|
||||||
import { AuthMethod } from "@app/hooks/api/users/types";
|
import { AuthMethod } from "@app/hooks/api/users/types";
|
||||||
import { navigateUserToOrg } from "@app/views/Login/Login.utils";
|
import { navigateUserToOrg } from "@app/views/Login/Login.utils";
|
||||||
|
import { Mfa } from "@app/views/Login/Mfa";
|
||||||
import { CreateOrgModal } from "@app/views/Org/components";
|
import { CreateOrgModal } from "@app/views/Org/components";
|
||||||
|
|
||||||
import { WishForm } from "./components/WishForm/WishForm";
|
import { WishForm } from "./components/WishForm/WishForm";
|
||||||
@@ -136,6 +138,8 @@ export const AppLayout = ({ children }: LayoutProps) => {
|
|||||||
|
|
||||||
const { data: projectFavorites } = useGetUserProjectFavorites(currentOrg?.id!);
|
const { data: projectFavorites } = useGetUserProjectFavorites(currentOrg?.id!);
|
||||||
const { mutateAsync: updateUserProjectFavorites } = useUpdateUserProjectFavorites();
|
const { mutateAsync: updateUserProjectFavorites } = useUpdateUserProjectFavorites();
|
||||||
|
const [shouldShowMfa, toggleShowMfa] = useToggle(false);
|
||||||
|
const [mfaSuccessCallback, setMfaSuccessCallback] = useState<() => void>(() => {});
|
||||||
|
|
||||||
const workspacesWithFaveProp = useMemo(
|
const workspacesWithFaveProp = useMemo(
|
||||||
() =>
|
() =>
|
||||||
@@ -206,10 +210,17 @@ export const AppLayout = ({ children }: LayoutProps) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const changeOrg = async (orgId: string) => {
|
const changeOrg = async (orgId: string) => {
|
||||||
await selectOrganization({
|
const { token, isMfaEnabled } = await selectOrganization({
|
||||||
organizationId: orgId
|
organizationId: orgId
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (isMfaEnabled) {
|
||||||
|
SecurityClient.setMfaToken(token);
|
||||||
|
toggleShowMfa.on();
|
||||||
|
setMfaSuccessCallback(() => () => changeOrg(orgId));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
await navigateUserToOrg(router, orgId);
|
await navigateUserToOrg(router, orgId);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -335,6 +346,18 @@ export const AppLayout = ({ children }: LayoutProps) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (shouldShowMfa) {
|
||||||
|
return (
|
||||||
|
<div className="flex max-h-screen min-h-screen flex-col items-center justify-center gap-2 overflow-y-auto bg-gradient-to-tr from-mineshaft-600 via-mineshaft-800 to-bunker-700">
|
||||||
|
<Mfa
|
||||||
|
email={user.email as string}
|
||||||
|
successCallback={mfaSuccessCallback}
|
||||||
|
closeMfa={() => toggleShowMfa.off()}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="dark hidden h-screen w-full flex-col overflow-x-hidden md:flex">
|
<div className="dark hidden h-screen w-full flex-col overflow-x-hidden md:flex">
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useCallback, useEffect } from "react";
|
import { useCallback, useEffect, useState } from "react";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import Head from "next/head";
|
import Head from "next/head";
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
@@ -12,15 +12,22 @@ import jwt_decode from "jwt-decode";
|
|||||||
|
|
||||||
import { createNotification } from "@app/components/notifications";
|
import { createNotification } from "@app/components/notifications";
|
||||||
import { IsCliLoginSuccessful } from "@app/components/utilities/attemptCliLogin";
|
import { IsCliLoginSuccessful } from "@app/components/utilities/attemptCliLogin";
|
||||||
|
import SecurityClient from "@app/components/utilities/SecurityClient";
|
||||||
import { Button, Spinner } from "@app/components/v2";
|
import { Button, Spinner } from "@app/components/v2";
|
||||||
import { SessionStorageKeys } from "@app/const";
|
import { SessionStorageKeys } from "@app/const";
|
||||||
import { useUser } from "@app/context";
|
import { useToggle } from "@app/hooks";
|
||||||
import { useGetOrganizations, useLogoutUser, useSelectOrganization } from "@app/hooks/api";
|
import {
|
||||||
|
useGetOrganizations,
|
||||||
|
useGetUser,
|
||||||
|
useLogoutUser,
|
||||||
|
useSelectOrganization
|
||||||
|
} from "@app/hooks/api";
|
||||||
import { UserAgentType } from "@app/hooks/api/auth/types";
|
import { UserAgentType } from "@app/hooks/api/auth/types";
|
||||||
import { Organization } from "@app/hooks/api/types";
|
import { Organization } from "@app/hooks/api/types";
|
||||||
import { AuthMethod } from "@app/hooks/api/users/types";
|
import { AuthMethod } from "@app/hooks/api/users/types";
|
||||||
import { getAuthToken, isLoggedIn } from "@app/reactQuery";
|
import { getAuthToken, isLoggedIn } from "@app/reactQuery";
|
||||||
import { navigateUserToOrg } from "@app/views/Login/Login.utils";
|
import { navigateUserToOrg } from "@app/views/Login/Login.utils";
|
||||||
|
import { Mfa } from "@app/views/Login/Mfa";
|
||||||
|
|
||||||
const LoadingScreen = () => {
|
const LoadingScreen = () => {
|
||||||
return (
|
return (
|
||||||
@@ -37,10 +44,16 @@ export default function LoginPage() {
|
|||||||
|
|
||||||
const organizations = useGetOrganizations();
|
const organizations = useGetOrganizations();
|
||||||
const selectOrg = useSelectOrganization();
|
const selectOrg = useSelectOrganization();
|
||||||
const { user, isLoading: userLoading } = useUser();
|
const { data: user, isLoading: userLoading } = useGetUser();
|
||||||
|
const [shouldShowMfa, toggleShowMfa] = useToggle(false);
|
||||||
|
const [isInitialOrgCheckLoading, setIsInitialOrgCheckLoading] = useState(true);
|
||||||
|
|
||||||
|
const [mfaSuccessCallback, setMfaSuccessCallback] = useState<() => void>(() => {});
|
||||||
|
|
||||||
const queryParams = new URLSearchParams(window.location.search);
|
const queryParams = new URLSearchParams(window.location.search);
|
||||||
|
const orgId = queryParams.get("org_id");
|
||||||
const callbackPort = queryParams.get("callback_port");
|
const callbackPort = queryParams.get("callback_port");
|
||||||
|
const defaultSelectedOrg = organizations.data?.find((org) => org.id === orgId);
|
||||||
|
|
||||||
const logout = useLogoutUser(true);
|
const logout = useLogoutUser(true);
|
||||||
const handleLogout = useCallback(async () => {
|
const handleLogout = useCallback(async () => {
|
||||||
@@ -77,18 +90,26 @@ export default function LoginPage() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const { token } = await selectOrg.mutateAsync({
|
const { token, isMfaEnabled } = await selectOrg.mutateAsync({
|
||||||
organizationId: organization.id,
|
organizationId: organization.id,
|
||||||
userAgent: callbackPort ? UserAgentType.CLI : undefined
|
userAgent: callbackPort ? UserAgentType.CLI : undefined
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (isMfaEnabled) {
|
||||||
|
SecurityClient.setMfaToken(token);
|
||||||
|
toggleShowMfa.on();
|
||||||
|
|
||||||
|
setMfaSuccessCallback(() => () => handleSelectOrganization(organization));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (callbackPort) {
|
if (callbackPort) {
|
||||||
const privateKey = localStorage.getItem("PRIVATE_KEY");
|
const privateKey = localStorage.getItem("PRIVATE_KEY");
|
||||||
|
|
||||||
let error: string | null = null;
|
let error: string | null = null;
|
||||||
|
|
||||||
if (!privateKey) error = "Private key not found";
|
if (!privateKey) error = "Private key not found";
|
||||||
if (!user.email) error = "User email not found";
|
if (!user?.email) error = "User email not found";
|
||||||
if (!token) error = "No token found";
|
if (!token) error = "No token found";
|
||||||
|
|
||||||
if (error) {
|
if (error) {
|
||||||
@@ -101,7 +122,7 @@ export default function LoginPage() {
|
|||||||
|
|
||||||
const payload = {
|
const payload = {
|
||||||
JTWToken: token,
|
JTWToken: token,
|
||||||
email: user.email,
|
email: user?.email,
|
||||||
privateKey
|
privateKey
|
||||||
} as IsCliLoginSuccessful["loginResponse"];
|
} as IsCliLoginSuccessful["loginResponse"];
|
||||||
|
|
||||||
@@ -149,23 +170,36 @@ export default function LoginPage() {
|
|||||||
}
|
}
|
||||||
}, [router]);
|
}, [router]);
|
||||||
|
|
||||||
// Case: User has no organizations.
|
|
||||||
// This can happen if the user was previously a member, but the organization was deleted or the user was removed.
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (organizations.isLoading || !organizations.data) return;
|
if (organizations.isLoading || !organizations.data) return;
|
||||||
|
|
||||||
|
// Case: User has no organizations.
|
||||||
|
// This can happen if the user was previously a member, but the organization was deleted or the user was removed.
|
||||||
if (organizations.data.length === 0) {
|
if (organizations.data.length === 0) {
|
||||||
router.push("/org/none");
|
router.push("/org/none");
|
||||||
} else if (organizations.data.length === 1) {
|
} else if (organizations.data.length === 1) {
|
||||||
if (callbackPort) {
|
if (callbackPort) {
|
||||||
handleCliRedirect();
|
handleCliRedirect();
|
||||||
|
setIsInitialOrgCheckLoading(false);
|
||||||
} else {
|
} else {
|
||||||
handleSelectOrganization(organizations.data[0]);
|
handleSelectOrganization(organizations.data[0]);
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
setIsInitialOrgCheckLoading(false);
|
||||||
}
|
}
|
||||||
}, [organizations.isLoading, organizations.data]);
|
}, [organizations.isLoading, organizations.data]);
|
||||||
|
|
||||||
if (userLoading || !user) {
|
useEffect(() => {
|
||||||
|
if (defaultSelectedOrg) {
|
||||||
|
handleSelectOrganization(defaultSelectedOrg);
|
||||||
|
}
|
||||||
|
}, [defaultSelectedOrg]);
|
||||||
|
|
||||||
|
if (
|
||||||
|
userLoading ||
|
||||||
|
!user ||
|
||||||
|
((isInitialOrgCheckLoading || defaultSelectedOrg) && !shouldShowMfa)
|
||||||
|
) {
|
||||||
return <LoadingScreen />;
|
return <LoadingScreen />;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -178,16 +212,16 @@ export default function LoginPage() {
|
|||||||
<meta property="og:title" content={t("login.og-title") ?? ""} />
|
<meta property="og:title" content={t("login.og-title") ?? ""} />
|
||||||
<meta name="og:description" content={t("login.og-description") ?? ""} />
|
<meta name="og:description" content={t("login.og-description") ?? ""} />
|
||||||
</Head>
|
</Head>
|
||||||
|
{shouldShowMfa ? (
|
||||||
|
<Mfa email={user.email as string} successCallback={mfaSuccessCallback} />
|
||||||
|
) : (
|
||||||
<div className="mx-auto mt-20 w-fit rounded-lg border-2 border-mineshaft-500 p-10 shadow-lg">
|
<div className="mx-auto mt-20 w-fit rounded-lg border-2 border-mineshaft-500 p-10 shadow-lg">
|
||||||
<Link href="/">
|
<Link href="/">
|
||||||
<div className="mb-4 flex justify-center">
|
<div className="mb-4 flex justify-center">
|
||||||
<Image src="/images/gradientLogo.svg" height={90} width={120} alt="Infisical logo" />
|
<Image src="/images/gradientLogo.svg" height={90} width={120} alt="Infisical logo" />
|
||||||
</div>
|
</div>
|
||||||
</Link>
|
</Link>
|
||||||
<form
|
<form className="mx-auto flex w-full flex-col items-center justify-center">
|
||||||
onSubmit={() => console.log("submit")}
|
|
||||||
className="mx-auto flex w-full flex-col items-center justify-center"
|
|
||||||
>
|
|
||||||
<div className="mb-8 space-y-2">
|
<div className="mb-8 space-y-2">
|
||||||
<h1 className="bg-gradient-to-b from-white to-bunker-200 bg-clip-text text-center text-2xl font-medium text-transparent">
|
<h1 className="bg-gradient-to-b from-white to-bunker-200 bg-clip-text text-center text-2xl font-medium text-transparent">
|
||||||
Choose your organization
|
Choose your organization
|
||||||
@@ -228,6 +262,7 @@ export default function LoginPage() {
|
|||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<div className="pb-28" />
|
<div className="pb-28" />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ import issueBackupKey from "@app/components/utilities/cryptography/issueBackupKe
|
|||||||
import { saveTokenToLocalStorage } from "@app/components/utilities/saveTokenToLocalStorage";
|
import { saveTokenToLocalStorage } from "@app/components/utilities/saveTokenToLocalStorage";
|
||||||
import SecurityClient from "@app/components/utilities/SecurityClient";
|
import SecurityClient from "@app/components/utilities/SecurityClient";
|
||||||
import { useServerConfig } from "@app/context";
|
import { useServerConfig } from "@app/context";
|
||||||
|
import { useToggle } from "@app/hooks";
|
||||||
import {
|
import {
|
||||||
completeAccountSignupInvite,
|
completeAccountSignupInvite,
|
||||||
useSelectOrganization,
|
useSelectOrganization,
|
||||||
@@ -57,6 +58,8 @@ export default function SignupInvite() {
|
|||||||
const [backupKeyIssued, setBackupKeyIssued] = useState(false);
|
const [backupKeyIssued, setBackupKeyIssued] = useState(false);
|
||||||
const [errors, setErrors] = useState<Errors>({});
|
const [errors, setErrors] = useState<Errors>({});
|
||||||
|
|
||||||
|
const [shouldShowMfa, toggleShowMfa] = useToggle(false);
|
||||||
|
const [mfaSuccessCallback, setMfaSuccessCallback] = useState<() => void>(() => {});
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const parsedUrl = queryString.parse(router.asPath.split("?")[1]);
|
const parsedUrl = queryString.parse(router.asPath.split("?")[1]);
|
||||||
const token = parsedUrl.token as string;
|
const token = parsedUrl.token as string;
|
||||||
@@ -180,11 +183,24 @@ export default function SignupInvite() {
|
|||||||
|
|
||||||
if (!orgId) throw new Error("You are not part of any organization");
|
if (!orgId) throw new Error("You are not part of any organization");
|
||||||
|
|
||||||
await selectOrganization({ organizationId: orgId });
|
const completeSignupFlow = async () => {
|
||||||
|
const { token: mfaToken, isMfaEnabled } = await selectOrganization({
|
||||||
|
organizationId: orgId
|
||||||
|
});
|
||||||
|
|
||||||
|
if (isMfaEnabled) {
|
||||||
|
SecurityClient.setMfaToken(mfaToken);
|
||||||
|
toggleShowMfa.on();
|
||||||
|
setMfaSuccessCallback(() => completeSignupFlow);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
localStorage.setItem("orgData.id", orgId);
|
localStorage.setItem("orgData.id", orgId);
|
||||||
|
|
||||||
setStep(3);
|
setStep(3);
|
||||||
|
};
|
||||||
|
|
||||||
|
await completeSignupFlow();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
console.error(error);
|
console.error(error);
|
||||||
@@ -222,11 +238,24 @@ export default function SignupInvite() {
|
|||||||
SecurityClient.setSignupToken(response.token);
|
SecurityClient.setSignupToken(response.token);
|
||||||
setStep(2);
|
setStep(2);
|
||||||
} else {
|
} else {
|
||||||
await selectOrganization({ organizationId });
|
const redirectExistingUser = async () => {
|
||||||
|
const { token: mfaToken, isMfaEnabled } = await selectOrganization({
|
||||||
|
organizationId
|
||||||
|
});
|
||||||
|
|
||||||
|
if (isMfaEnabled) {
|
||||||
|
SecurityClient.setMfaToken(mfaToken);
|
||||||
|
toggleShowMfa.on();
|
||||||
|
setMfaSuccessCallback(() => redirectExistingUser);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// user will be redirected to dashboard
|
// user will be redirected to dashboard
|
||||||
// if not logged in gets kicked out to login
|
// if not logged in gets kicked out to login
|
||||||
await navigateUserToOrg(router, organizationId);
|
await navigateUserToOrg(router, organizationId);
|
||||||
|
};
|
||||||
|
|
||||||
|
await redirectExistingUser();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { useEffect, useState } from "react";
|
|||||||
|
|
||||||
import { isLoggedIn } from "@app/reactQuery";
|
import { isLoggedIn } from "@app/reactQuery";
|
||||||
|
|
||||||
import { InitialStep, MFAStep, SSOStep } from "./components";
|
import { InitialStep, SSOStep } from "./components";
|
||||||
import { useNavigateToSelectOrganization } from "./Login.utils";
|
import { useNavigateToSelectOrganization } from "./Login.utils";
|
||||||
|
|
||||||
export const Login = () => {
|
export const Login = () => {
|
||||||
@@ -46,15 +46,6 @@ export const Login = () => {
|
|||||||
setPassword={setPassword}
|
setPassword={setPassword}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
case 1:
|
|
||||||
return (
|
|
||||||
<MFAStep
|
|
||||||
email={email}
|
|
||||||
password={password}
|
|
||||||
providerAuthToken={undefined}
|
|
||||||
callbackPort={queryParams.get("callback_port")}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
case 2:
|
case 2:
|
||||||
return <SSOStep setStep={setStep} type="SAML" />;
|
return <SSOStep setStep={setStep} type="SAML" />;
|
||||||
case 3:
|
case 3:
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { NextRouter, useRouter } from "next/router";
|
import { NextRouter, useRouter } from "next/router";
|
||||||
|
|
||||||
import { useServerConfig } from "@app/context";
|
import { useServerConfig } from "@app/context";
|
||||||
import { useSelectOrganization } from "@app/hooks/api";
|
|
||||||
import { fetchOrganizations } from "@app/hooks/api/organization/queries";
|
import { fetchOrganizations } from "@app/hooks/api/organization/queries";
|
||||||
import { userKeys } from "@app/hooks/api/users";
|
import { userKeys } from "@app/hooks/api/users";
|
||||||
import { queryClient } from "@app/reactQuery";
|
import { queryClient } from "@app/reactQuery";
|
||||||
@@ -31,23 +30,18 @@ export const navigateUserToOrg = async (router: NextRouter, organizationId?: str
|
|||||||
|
|
||||||
export const useNavigateToSelectOrganization = () => {
|
export const useNavigateToSelectOrganization = () => {
|
||||||
const { config } = useServerConfig();
|
const { config } = useServerConfig();
|
||||||
const selectOrganization = useSelectOrganization();
|
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
const navigate = async (cliCallbackPort?: string) => {
|
const navigate = async (cliCallbackPort?: string) => {
|
||||||
|
let redirectTo = "/login/select-organization?";
|
||||||
if (config.defaultAuthOrgId) {
|
if (config.defaultAuthOrgId) {
|
||||||
await selectOrganization.mutateAsync({
|
redirectTo += `org_id=${config.defaultAuthOrgId}&`;
|
||||||
organizationId: config.defaultAuthOrgId
|
} else {
|
||||||
});
|
queryClient.invalidateQueries(userKeys.getUser);
|
||||||
|
|
||||||
await navigateUserToOrg(router, config.defaultAuthOrgId);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
queryClient.invalidateQueries(userKeys.getUser);
|
|
||||||
let redirectTo = "/login/select-organization";
|
|
||||||
|
|
||||||
if (cliCallbackPort) {
|
if (cliCallbackPort) {
|
||||||
redirectTo += `?callback_port=${cliCallbackPort}`;
|
redirectTo += `callback_port=${cliCallbackPort}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
router.push(redirectTo, undefined, { shallow: true });
|
router.push(redirectTo, undefined, { shallow: true });
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import jwt_decode from "jwt-decode";
|
import jwt_decode from "jwt-decode";
|
||||||
|
|
||||||
import { MFAStep, PasswordStep } from "./components";
|
import { PasswordStep } from "./components";
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
providerAuthToken: string;
|
providerAuthToken: string;
|
||||||
@@ -30,13 +30,8 @@ export const LoginSSO = ({ providerAuthToken }: Props) => {
|
|||||||
email={username}
|
email={username}
|
||||||
password={password}
|
password={password}
|
||||||
setPassword={setPassword}
|
setPassword={setPassword}
|
||||||
setStep={setStep}
|
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
case 2:
|
|
||||||
return (
|
|
||||||
<MFAStep providerAuthToken={providerAuthToken} email={username} password={password} />
|
|
||||||
);
|
|
||||||
default:
|
default:
|
||||||
return <div />;
|
return <div />;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,152 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import ReactCodeInput from "react-code-input";
|
||||||
|
import Image from "next/image";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useRouter } from "next/router";
|
||||||
|
import { t } from "i18next";
|
||||||
|
|
||||||
|
import Error from "@app/components/basic/Error";
|
||||||
|
import SecurityClient from "@app/components/utilities/SecurityClient";
|
||||||
|
import { Button } from "@app/components/v2";
|
||||||
|
import { useSendMfaToken } from "@app/hooks/api";
|
||||||
|
import { verifyMfaToken } from "@app/hooks/api/auth/queries";
|
||||||
|
|
||||||
|
// The style for the verification code input
|
||||||
|
const codeInputProps = {
|
||||||
|
inputStyle: {
|
||||||
|
fontFamily: "monospace",
|
||||||
|
margin: "4px",
|
||||||
|
MozAppearance: "textfield",
|
||||||
|
width: "48px",
|
||||||
|
borderRadius: "5px",
|
||||||
|
fontSize: "24px",
|
||||||
|
height: "48px",
|
||||||
|
paddingLeft: "7",
|
||||||
|
backgroundColor: "#0d1117",
|
||||||
|
color: "white",
|
||||||
|
border: "1px solid #2d2f33",
|
||||||
|
textAlign: "center",
|
||||||
|
outlineColor: "#8ca542",
|
||||||
|
borderColor: "#2d2f33"
|
||||||
|
}
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
type Props = {
|
||||||
|
successCallback: () => void | Promise<void>;
|
||||||
|
closeMfa?: () => void;
|
||||||
|
hideLogo?: boolean;
|
||||||
|
email: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const Mfa = ({ successCallback, closeMfa, hideLogo, email }: Props) => {
|
||||||
|
const [mfaCode, setMfaCode] = useState("");
|
||||||
|
const router = useRouter();
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const [isLoadingResend, setIsLoadingResend] = useState(false);
|
||||||
|
const [triesLeft, setTriesLeft] = useState<number | undefined>(undefined);
|
||||||
|
|
||||||
|
const sendMfaToken = useSendMfaToken();
|
||||||
|
|
||||||
|
const verifyMfa = async () => {
|
||||||
|
setIsLoading(true);
|
||||||
|
try {
|
||||||
|
const { token } = await verifyMfaToken({
|
||||||
|
email,
|
||||||
|
mfaCode
|
||||||
|
});
|
||||||
|
|
||||||
|
SecurityClient.setMfaToken("");
|
||||||
|
SecurityClient.setToken(token);
|
||||||
|
|
||||||
|
await successCallback();
|
||||||
|
if (closeMfa) {
|
||||||
|
closeMfa();
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (triesLeft) {
|
||||||
|
setTriesLeft((left) => {
|
||||||
|
if (triesLeft === 1) {
|
||||||
|
router.push("/");
|
||||||
|
|
||||||
|
SecurityClient.setMfaToken("");
|
||||||
|
SecurityClient.setToken("");
|
||||||
|
}
|
||||||
|
return (left as number) - 1;
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
setTriesLeft(2);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleResendMfaCode = async () => {
|
||||||
|
try {
|
||||||
|
setIsLoadingResend(true);
|
||||||
|
await sendMfaToken.mutateAsync({ email });
|
||||||
|
setIsLoadingResend(false);
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
setIsLoadingResend(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mx-auto w-max pb-4 pt-4 md:mb-16 md:px-8">
|
||||||
|
{!hideLogo && (
|
||||||
|
<Link href="/">
|
||||||
|
<div className="mb-4 flex justify-center">
|
||||||
|
<Image src="/images/gradientLogo.svg" height={90} width={120} alt="Infisical logo" />
|
||||||
|
</div>
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
<p className="text-l flex justify-center text-bunker-300">{t("mfa.step2-message")}</p>
|
||||||
|
<p className="text-l my-1 flex justify-center font-semibold text-bunker-300">{email}</p>
|
||||||
|
<div className="mx-auto hidden w-max min-w-[20rem] md:block">
|
||||||
|
<ReactCodeInput
|
||||||
|
name=""
|
||||||
|
inputMode="tel"
|
||||||
|
type="text"
|
||||||
|
fields={6}
|
||||||
|
onChange={setMfaCode}
|
||||||
|
className="mt-6 mb-2"
|
||||||
|
{...codeInputProps}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{typeof triesLeft === "number" && (
|
||||||
|
<Error text={`Invalid code. You have ${triesLeft} attempt(s) remaining.`} />
|
||||||
|
)}
|
||||||
|
<div className="mx-auto mt-2 flex w-1/4 min-w-[20rem] max-w-xs flex-col items-center justify-center text-center text-sm md:max-w-md md:text-left lg:w-[19%]">
|
||||||
|
<div className="text-l w-full py-1 text-lg">
|
||||||
|
<Button
|
||||||
|
onClick={() => verifyMfa()}
|
||||||
|
size="sm"
|
||||||
|
isFullWidth
|
||||||
|
className="h-14"
|
||||||
|
colorSchema="primary"
|
||||||
|
variant="outline_bg"
|
||||||
|
isLoading={isLoading}
|
||||||
|
>
|
||||||
|
{String(t("mfa.verify"))}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="mx-auto flex max-h-24 w-full max-w-md flex-col items-center justify-center pt-2">
|
||||||
|
<div className="flex flex-row items-baseline gap-1 text-sm">
|
||||||
|
<span className="text-bunker-400">{t("signup.step2-resend-alert")}</span>
|
||||||
|
<div className="text-md mt-2 flex flex-row text-bunker-400">
|
||||||
|
<button disabled={isLoadingResend} onClick={handleResendMfaCode} type="button">
|
||||||
|
<span className="cursor-pointer duration-200 hover:text-bunker-200 hover:underline hover:decoration-primary-700 hover:underline-offset-4">
|
||||||
|
{isLoadingResend
|
||||||
|
? t("signup.step2-resend-progress")
|
||||||
|
: t("signup.step2-resend-submit")}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p className="pb-2 text-sm text-bunker-400">{t("signup.step2-spam-alert")}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -85,13 +85,6 @@ export const InitialStep = ({ setStep, email, setEmail, password, setPassword }:
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (isCliLoginSuccessful && isCliLoginSuccessful.success) {
|
if (isCliLoginSuccessful && isCliLoginSuccessful.success) {
|
||||||
if (isCliLoginSuccessful.mfaEnabled) {
|
|
||||||
// case: login requires MFA step
|
|
||||||
setStep(1);
|
|
||||||
setIsLoading(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
navigateToSelectOrganization(callbackPort!);
|
navigateToSelectOrganization(callbackPort!);
|
||||||
} else {
|
} else {
|
||||||
setLoginError(true);
|
setLoginError(true);
|
||||||
@@ -109,17 +102,7 @@ export const InitialStep = ({ setStep, email, setEmail, password, setPassword }:
|
|||||||
|
|
||||||
if (isLoginSuccessful && isLoginSuccessful.success) {
|
if (isLoginSuccessful && isLoginSuccessful.success) {
|
||||||
// case: login was successful
|
// case: login was successful
|
||||||
|
|
||||||
if (isLoginSuccessful.mfaEnabled) {
|
|
||||||
// case: login requires MFA step
|
|
||||||
setStep(1);
|
|
||||||
setIsLoading(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
navigateToSelectOrganization();
|
navigateToSelectOrganization();
|
||||||
|
|
||||||
// case: login does not require MFA step
|
|
||||||
createNotification({
|
createNotification({
|
||||||
text: "Successfully logged in",
|
text: "Successfully logged in",
|
||||||
type: "success"
|
type: "success"
|
||||||
|
|||||||
@@ -1,338 +0,0 @@
|
|||||||
import React, { useState } from "react";
|
|
||||||
import ReactCodeInput from "react-code-input";
|
|
||||||
import { useTranslation } from "react-i18next";
|
|
||||||
import { useRouter } from "next/router";
|
|
||||||
import axios from "axios";
|
|
||||||
import { addSeconds, formatISO } from "date-fns";
|
|
||||||
import jwt_decode from "jwt-decode";
|
|
||||||
|
|
||||||
import Error from "@app/components/basic/Error";
|
|
||||||
import { createNotification } from "@app/components/notifications";
|
|
||||||
import attemptCliLoginMfa from "@app/components/utilities/attemptCliLoginMfa";
|
|
||||||
import attemptLoginMfa from "@app/components/utilities/attemptLoginMfa";
|
|
||||||
import SecurityClient from "@app/components/utilities/SecurityClient";
|
|
||||||
import { Button } from "@app/components/v2";
|
|
||||||
import { SessionStorageKeys } from "@app/const";
|
|
||||||
import { useSendMfaToken } from "@app/hooks/api/auth";
|
|
||||||
import { useSelectOrganization, verifyMfaToken } from "@app/hooks/api/auth/queries";
|
|
||||||
import { fetchOrganizations } from "@app/hooks/api/organization/queries";
|
|
||||||
import { fetchMyPrivateKey } from "@app/hooks/api/users/queries";
|
|
||||||
|
|
||||||
import { navigateUserToOrg, useNavigateToSelectOrganization } from "../../Login.utils";
|
|
||||||
|
|
||||||
// The style for the verification code input
|
|
||||||
const props = {
|
|
||||||
inputStyle: {
|
|
||||||
fontFamily: "monospace",
|
|
||||||
margin: "4px",
|
|
||||||
MozAppearance: "textfield",
|
|
||||||
width: "48px",
|
|
||||||
borderRadius: "5px",
|
|
||||||
fontSize: "24px",
|
|
||||||
height: "48px",
|
|
||||||
paddingLeft: "7",
|
|
||||||
backgroundColor: "#0d1117",
|
|
||||||
color: "white",
|
|
||||||
border: "1px solid #2d2f33",
|
|
||||||
textAlign: "center",
|
|
||||||
outlineColor: "#8ca542",
|
|
||||||
borderColor: "#2d2f33"
|
|
||||||
}
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
type Props = {
|
|
||||||
email: string;
|
|
||||||
password: string;
|
|
||||||
providerAuthToken?: string;
|
|
||||||
callbackPort?: string | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const MFAStep = ({ email, password, providerAuthToken }: Props) => {
|
|
||||||
const router = useRouter();
|
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
|
||||||
const [isLoadingResend, setIsLoadingResend] = useState(false);
|
|
||||||
const [mfaCode, setMfaCode] = useState("");
|
|
||||||
const { navigateToSelectOrganization } = useNavigateToSelectOrganization();
|
|
||||||
const [triesLeft, setTriesLeft] = useState<number | undefined>(undefined);
|
|
||||||
|
|
||||||
const { t } = useTranslation();
|
|
||||||
|
|
||||||
const sendMfaToken = useSendMfaToken();
|
|
||||||
const { mutateAsync: selectOrganization } = useSelectOrganization();
|
|
||||||
|
|
||||||
// They don't have password
|
|
||||||
const handleLoginMfaOauth = async (callbackPort: string, organizationId?: string) => {
|
|
||||||
setIsLoading(true);
|
|
||||||
const { token } = await verifyMfaToken({
|
|
||||||
email,
|
|
||||||
mfaCode
|
|
||||||
});
|
|
||||||
//
|
|
||||||
// unset temporary (MFA) JWT token and set JWT token
|
|
||||||
SecurityClient.setMfaToken("");
|
|
||||||
SecurityClient.setToken(token);
|
|
||||||
SecurityClient.setProviderAuthToken("");
|
|
||||||
const privateKey = await fetchMyPrivateKey();
|
|
||||||
localStorage.setItem("PRIVATE_KEY", privateKey);
|
|
||||||
|
|
||||||
// case: organization ID is present from the provider auth token -- select the org and use the new jwt token in the CLI, then navigate to the org
|
|
||||||
if (organizationId) {
|
|
||||||
const { token: newJwtToken } = await selectOrganization({ organizationId });
|
|
||||||
if (callbackPort) {
|
|
||||||
const cliUrl = `http://127.0.0.1:${callbackPort}/`;
|
|
||||||
const instance = axios.create();
|
|
||||||
const payload = {
|
|
||||||
email,
|
|
||||||
privateKey,
|
|
||||||
JTWToken: newJwtToken
|
|
||||||
};
|
|
||||||
await instance.post(cliUrl, payload).catch(() => {
|
|
||||||
// if error happens to communicate we set the token with an expiry in sessino storage
|
|
||||||
// the cli-redirect page has logic to show this to user and ask them to paste it in terminal
|
|
||||||
sessionStorage.setItem(
|
|
||||||
SessionStorageKeys.CLI_TERMINAL_TOKEN,
|
|
||||||
JSON.stringify({
|
|
||||||
expiry: formatISO(addSeconds(new Date(), 30)),
|
|
||||||
data: window.btoa(JSON.stringify(payload))
|
|
||||||
})
|
|
||||||
);
|
|
||||||
});
|
|
||||||
router.push("/cli-redirect");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
await navigateUserToOrg(router, organizationId);
|
|
||||||
}
|
|
||||||
// case: no organization ID is present -- navigate to the select org page IF the user has any orgs
|
|
||||||
// if the user has no orgs, navigate to the create org page
|
|
||||||
else {
|
|
||||||
const userOrgs = await fetchOrganizations();
|
|
||||||
|
|
||||||
// case: user has orgs, so we navigate the user to select an org
|
|
||||||
if (userOrgs.length > 0) {
|
|
||||||
navigateToSelectOrganization(callbackPort);
|
|
||||||
}
|
|
||||||
// case: no orgs found, so we navigate the user to create an org
|
|
||||||
// cli login will fail in this case
|
|
||||||
else {
|
|
||||||
await navigateUserToOrg(router);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleLoginMfa = async () => {
|
|
||||||
try {
|
|
||||||
let callbackPort: undefined | string;
|
|
||||||
let organizationId: undefined | string;
|
|
||||||
let hasExchangedPrivateKey: undefined | boolean;
|
|
||||||
|
|
||||||
const queryParams = new URLSearchParams(window.location.search);
|
|
||||||
|
|
||||||
callbackPort = queryParams.get("callback_port") || undefined;
|
|
||||||
|
|
||||||
if (providerAuthToken) {
|
|
||||||
const decodedToken = jwt_decode(providerAuthToken) as any;
|
|
||||||
|
|
||||||
callbackPort = decodedToken.callbackPort;
|
|
||||||
organizationId = decodedToken?.organizationId;
|
|
||||||
hasExchangedPrivateKey = decodedToken?.hasExchangedPrivateKey;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mfaCode.length !== 6) {
|
|
||||||
createNotification({
|
|
||||||
text: "Please enter a 6-digit MFA code and try again",
|
|
||||||
type: "error"
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (hasExchangedPrivateKey) {
|
|
||||||
await handleLoginMfaOauth(callbackPort as string, organizationId);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setIsLoading(true);
|
|
||||||
if (callbackPort) {
|
|
||||||
// attemptCliLogin
|
|
||||||
const isCliLoginSuccessful = await attemptCliLoginMfa({
|
|
||||||
email,
|
|
||||||
password,
|
|
||||||
providerAuthToken,
|
|
||||||
mfaToken: mfaCode
|
|
||||||
});
|
|
||||||
|
|
||||||
if (isCliLoginSuccessful && isCliLoginSuccessful.success) {
|
|
||||||
const cliUrl = `http://127.0.0.1:${callbackPort}/`;
|
|
||||||
|
|
||||||
// case: organization ID is present from the provider auth token -- select the org and use the new jwt token in the CLI, then navigate to the org
|
|
||||||
if (organizationId) {
|
|
||||||
const { token: newJwtToken } = await selectOrganization({ organizationId });
|
|
||||||
|
|
||||||
const instance = axios.create();
|
|
||||||
const payload = {
|
|
||||||
...isCliLoginSuccessful.loginResponse,
|
|
||||||
JTWToken: newJwtToken
|
|
||||||
};
|
|
||||||
await instance.post(cliUrl, payload).catch(() => {
|
|
||||||
// if error happens to communicate we set the token with an expiry in sessino storage
|
|
||||||
// the cli-redirect page has logic to show this to user and ask them to paste it in terminal
|
|
||||||
sessionStorage.setItem(
|
|
||||||
SessionStorageKeys.CLI_TERMINAL_TOKEN,
|
|
||||||
JSON.stringify({
|
|
||||||
expiry: formatISO(addSeconds(new Date(), 30)),
|
|
||||||
data: window.btoa(JSON.stringify(payload))
|
|
||||||
})
|
|
||||||
);
|
|
||||||
});
|
|
||||||
router.push("/cli-redirect");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// case: no organization ID is present -- navigate to the select org page IF the user has any orgs
|
|
||||||
// if the user has no orgs, navigate to the create org page
|
|
||||||
|
|
||||||
const userOrgs = await fetchOrganizations();
|
|
||||||
|
|
||||||
// case: user has orgs, so we navigate the user to select an org
|
|
||||||
if (userOrgs.length > 0) {
|
|
||||||
navigateToSelectOrganization(callbackPort);
|
|
||||||
}
|
|
||||||
// case: no orgs found, so we navigate the user to create an org
|
|
||||||
// cli login will fail in this case
|
|
||||||
else {
|
|
||||||
await navigateUserToOrg(router);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
const isLoginSuccessful = await attemptLoginMfa({
|
|
||||||
email,
|
|
||||||
password,
|
|
||||||
providerAuthToken,
|
|
||||||
mfaToken: mfaCode
|
|
||||||
});
|
|
||||||
|
|
||||||
if (isLoginSuccessful) {
|
|
||||||
setIsLoading(false);
|
|
||||||
|
|
||||||
// case: login does not require MFA step
|
|
||||||
createNotification({
|
|
||||||
text: "Successfully logged in",
|
|
||||||
type: "success"
|
|
||||||
});
|
|
||||||
|
|
||||||
if (organizationId) {
|
|
||||||
await navigateUserToOrg(router, organizationId);
|
|
||||||
} else {
|
|
||||||
navigateToSelectOrganization();
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
createNotification({
|
|
||||||
text: "Failed to log in",
|
|
||||||
type: "error"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (err: any) {
|
|
||||||
if (err.response.data.error === "User Locked") {
|
|
||||||
createNotification({
|
|
||||||
title: err.response.data.error,
|
|
||||||
text: err.response.data.message,
|
|
||||||
type: "error"
|
|
||||||
});
|
|
||||||
setIsLoading(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
createNotification({
|
|
||||||
text: "Failed to log in",
|
|
||||||
type: "error"
|
|
||||||
});
|
|
||||||
|
|
||||||
if (triesLeft) {
|
|
||||||
setTriesLeft((left) => {
|
|
||||||
if (triesLeft === 1) {
|
|
||||||
router.push("/");
|
|
||||||
}
|
|
||||||
return (left as number) - 1;
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
setTriesLeft(2);
|
|
||||||
}
|
|
||||||
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleResendMfaCode = async () => {
|
|
||||||
try {
|
|
||||||
setIsLoadingResend(true);
|
|
||||||
await sendMfaToken.mutateAsync({ email });
|
|
||||||
setIsLoadingResend(false);
|
|
||||||
} catch (err) {
|
|
||||||
console.error(err);
|
|
||||||
setIsLoadingResend(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<form className="mx-auto w-max pb-4 pt-4 md:mb-16 md:px-8">
|
|
||||||
<p className="text-l flex justify-center text-bunker-300">{t("mfa.step2-message")}</p>
|
|
||||||
<p className="text-l my-1 flex justify-center font-semibold text-bunker-300">{email} </p>
|
|
||||||
<div className="mx-auto hidden w-max min-w-[20rem] md:block">
|
|
||||||
<ReactCodeInput
|
|
||||||
name=""
|
|
||||||
inputMode="tel"
|
|
||||||
type="text"
|
|
||||||
fields={6}
|
|
||||||
onChange={setMfaCode}
|
|
||||||
{...props}
|
|
||||||
className="mt-6 mb-2"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="mx-auto mt-4 block w-max md:hidden">
|
|
||||||
<ReactCodeInput
|
|
||||||
name=""
|
|
||||||
inputMode="tel"
|
|
||||||
type="text"
|
|
||||||
fields={6}
|
|
||||||
onChange={setMfaCode}
|
|
||||||
{...props}
|
|
||||||
className="mt-2 mb-2"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
{typeof triesLeft === "number" && (
|
|
||||||
<Error text={`Invalid code. You have ${triesLeft} attempt(s) remaining.`} />
|
|
||||||
)}
|
|
||||||
<div className="mx-auto mt-2 flex w-1/4 min-w-[20rem] max-w-xs flex-col items-center justify-center text-center text-sm md:max-w-md md:text-left lg:w-[19%]">
|
|
||||||
<div className="text-l w-full py-1 text-lg">
|
|
||||||
<Button
|
|
||||||
onClick={() => handleLoginMfa()}
|
|
||||||
size="sm"
|
|
||||||
isFullWidth
|
|
||||||
className="h-14"
|
|
||||||
colorSchema="primary"
|
|
||||||
variant="outline_bg"
|
|
||||||
isLoading={isLoading}
|
|
||||||
>
|
|
||||||
{" "}
|
|
||||||
{String(t("mfa.verify"))}{" "}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="mx-auto flex max-h-24 w-full max-w-md flex-col items-center justify-center pt-2">
|
|
||||||
<div className="flex flex-row items-baseline gap-1 text-sm">
|
|
||||||
<span className="text-bunker-400">{t("signup.step2-resend-alert")}</span>
|
|
||||||
<div className="text-md mt-2 flex flex-row text-bunker-400">
|
|
||||||
<button disabled={isLoadingResend} onClick={handleResendMfaCode} type="button">
|
|
||||||
<span className="cursor-pointer duration-200 hover:text-bunker-200 hover:underline hover:decoration-primary-700 hover:underline-offset-4">
|
|
||||||
{isLoadingResend
|
|
||||||
? t("signup.step2-resend-progress")
|
|
||||||
: t("signup.step2-resend-submit")}
|
|
||||||
</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<p className="pb-2 text-sm text-bunker-400">{t("signup.step2-spam-alert")}</p>
|
|
||||||
</div>
|
|
||||||
</form>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
export { MFAStep } from "./MFAStep";
|
|
||||||
@@ -14,32 +14,29 @@ import { CAPTCHA_SITE_KEY } from "@app/components/utilities/config";
|
|||||||
import SecurityClient from "@app/components/utilities/SecurityClient";
|
import SecurityClient from "@app/components/utilities/SecurityClient";
|
||||||
import { Button, Input, Spinner } from "@app/components/v2";
|
import { Button, Input, Spinner } from "@app/components/v2";
|
||||||
import { SessionStorageKeys } from "@app/const";
|
import { SessionStorageKeys } from "@app/const";
|
||||||
|
import { useToggle } from "@app/hooks";
|
||||||
import { useOauthTokenExchange, useSelectOrganization } from "@app/hooks/api";
|
import { useOauthTokenExchange, useSelectOrganization } from "@app/hooks/api";
|
||||||
import { fetchOrganizations } from "@app/hooks/api/organization/queries";
|
import { fetchOrganizations } from "@app/hooks/api/organization/queries";
|
||||||
import { fetchMyPrivateKey } from "@app/hooks/api/users/queries";
|
import { fetchMyPrivateKey } from "@app/hooks/api/users/queries";
|
||||||
|
|
||||||
import { navigateUserToOrg, useNavigateToSelectOrganization } from "../../Login.utils";
|
import { navigateUserToOrg, useNavigateToSelectOrganization } from "../../Login.utils";
|
||||||
|
import { Mfa } from "../../Mfa";
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
providerAuthToken: string;
|
providerAuthToken: string;
|
||||||
email: string;
|
email: string;
|
||||||
password: string;
|
password: string;
|
||||||
setPassword: (password: string) => void;
|
setPassword: (password: string) => void;
|
||||||
setStep: (step: number) => void;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const PasswordStep = ({
|
export const PasswordStep = ({ providerAuthToken, email, password, setPassword }: Props) => {
|
||||||
providerAuthToken,
|
|
||||||
email,
|
|
||||||
password,
|
|
||||||
setPassword,
|
|
||||||
setStep
|
|
||||||
}: Props) => {
|
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { mutateAsync: selectOrganization } = useSelectOrganization();
|
const { mutateAsync: selectOrganization } = useSelectOrganization();
|
||||||
const { mutateAsync: oauthTokenExchange } = useOauthTokenExchange();
|
const { mutateAsync: oauthTokenExchange } = useOauthTokenExchange();
|
||||||
|
const [shouldShowMfa, toggleShowMfa] = useToggle(false);
|
||||||
|
const [mfaSuccessCallback, setMfaSuccessCallback] = useState<() => void>(() => {});
|
||||||
|
|
||||||
const { navigateToSelectOrganization } = useNavigateToSelectOrganization();
|
const { navigateToSelectOrganization } = useNavigateToSelectOrganization();
|
||||||
|
|
||||||
@@ -56,17 +53,8 @@ export const PasswordStep = ({
|
|||||||
});
|
});
|
||||||
|
|
||||||
// attemptCliLogin
|
// attemptCliLogin
|
||||||
if (oauthLogin.mfaEnabled) {
|
|
||||||
SecurityClient.setMfaToken(oauthLogin.token);
|
|
||||||
// case: login requires MFA step
|
|
||||||
setStep(2);
|
|
||||||
setIsLoading(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const cliUrl = `http://127.0.0.1:${callbackPort}/`;
|
const cliUrl = `http://127.0.0.1:${callbackPort}/`;
|
||||||
|
|
||||||
// case: MFA is not enabled
|
|
||||||
|
|
||||||
// unset provider auth token in case it was used
|
// unset provider auth token in case it was used
|
||||||
SecurityClient.setProviderAuthToken("");
|
SecurityClient.setProviderAuthToken("");
|
||||||
// set JWT token
|
// set JWT token
|
||||||
@@ -77,14 +65,23 @@ export const PasswordStep = ({
|
|||||||
|
|
||||||
// case: organization ID is present from the provider auth token -- select the org and use the new jwt token in the CLI, then navigate to the org
|
// case: organization ID is present from the provider auth token -- select the org and use the new jwt token in the CLI, then navigate to the org
|
||||||
if (organizationId) {
|
if (organizationId) {
|
||||||
const { token: newJwtToken } = await selectOrganization({ organizationId });
|
const finishWithOrgWorkflow = async () => {
|
||||||
|
const { token, isMfaEnabled } = await selectOrganization({ organizationId });
|
||||||
|
|
||||||
|
if (isMfaEnabled) {
|
||||||
|
SecurityClient.setMfaToken(token);
|
||||||
|
toggleShowMfa.on();
|
||||||
|
setMfaSuccessCallback(() => finishWithOrgWorkflow);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (callbackPort) {
|
if (callbackPort) {
|
||||||
console.log("organization id was present. new JWT token to be used in CLI:", newJwtToken);
|
console.log("organization id was present. new JWT token to be used in CLI:", token);
|
||||||
const instance = axios.create();
|
const instance = axios.create();
|
||||||
const payload = {
|
const payload = {
|
||||||
privateKey,
|
privateKey,
|
||||||
email,
|
email,
|
||||||
JTWToken: newJwtToken
|
JTWToken: token
|
||||||
};
|
};
|
||||||
await instance.post(cliUrl, payload).catch(() => {
|
await instance.post(cliUrl, payload).catch(() => {
|
||||||
// if error happens to communicate we set the token with an expiry in sessino storage
|
// if error happens to communicate we set the token with an expiry in sessino storage
|
||||||
@@ -102,6 +99,9 @@ export const PasswordStep = ({
|
|||||||
}
|
}
|
||||||
|
|
||||||
await navigateUserToOrg(router, organizationId);
|
await navigateUserToOrg(router, organizationId);
|
||||||
|
};
|
||||||
|
|
||||||
|
await finishWithOrgWorkflow();
|
||||||
}
|
}
|
||||||
// case: no organization ID is present -- navigate to the select org page IF the user has any orgs
|
// case: no organization ID is present -- navigate to the select org page IF the user has any orgs
|
||||||
// if the user has no orgs, navigate to the create org page
|
// if the user has no orgs, navigate to the create org page
|
||||||
@@ -162,27 +162,26 @@ export const PasswordStep = ({
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (isCliLoginSuccessful && isCliLoginSuccessful.success) {
|
if (isCliLoginSuccessful && isCliLoginSuccessful.success) {
|
||||||
if (isCliLoginSuccessful.mfaEnabled) {
|
|
||||||
// case: login requires MFA step
|
|
||||||
setStep(2);
|
|
||||||
setIsLoading(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const cliUrl = `http://127.0.0.1:${callbackPort}/`;
|
const cliUrl = `http://127.0.0.1:${callbackPort}/`;
|
||||||
|
|
||||||
// case: organization ID is present from the provider auth token -- select the org and use the new jwt token in the CLI, then navigate to the org
|
// case: organization ID is present from the provider auth token -- select the org and use the new jwt token in the CLI, then navigate to the org
|
||||||
if (organizationId) {
|
if (organizationId) {
|
||||||
const { token: newJwtToken } = await selectOrganization({ organizationId });
|
const finishWithOrgWorkflow = async () => {
|
||||||
|
const { token, isMfaEnabled } = await selectOrganization({ organizationId });
|
||||||
|
|
||||||
console.log(
|
if (isMfaEnabled) {
|
||||||
"organization id was present. new JWT token to be used in CLI:",
|
SecurityClient.setMfaToken(token);
|
||||||
newJwtToken
|
toggleShowMfa.on();
|
||||||
);
|
setMfaSuccessCallback(() => finishWithOrgWorkflow);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("organization id was present. new JWT token to be used in CLI:", token);
|
||||||
|
|
||||||
const instance = axios.create();
|
const instance = axios.create();
|
||||||
const payload = {
|
const payload = {
|
||||||
...isCliLoginSuccessful.loginResponse,
|
...isCliLoginSuccessful.loginResponse,
|
||||||
JTWToken: newJwtToken
|
JTWToken: token
|
||||||
};
|
};
|
||||||
await instance.post(cliUrl, payload).catch(() => {
|
await instance.post(cliUrl, payload).catch(() => {
|
||||||
// if error happens to communicate we set the token with an expiry in sessino storage
|
// if error happens to communicate we set the token with an expiry in sessino storage
|
||||||
@@ -196,8 +195,12 @@ export const PasswordStep = ({
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
router.push("/cli-redirect");
|
router.push("/cli-redirect");
|
||||||
|
};
|
||||||
|
|
||||||
|
await finishWithOrgWorkflow();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// case: no organization ID is present -- navigate to the select org page IF the user has any orgs
|
// case: no organization ID is present -- navigate to the select org page IF the user has any orgs
|
||||||
// if the user has no orgs, navigate to the create org page
|
// if the user has no orgs, navigate to the create org page
|
||||||
const userOrgs = await fetchOrganizations();
|
const userOrgs = await fetchOrganizations();
|
||||||
@@ -221,16 +224,6 @@ export const PasswordStep = ({
|
|||||||
|
|
||||||
if (loginAttempt && loginAttempt.success) {
|
if (loginAttempt && loginAttempt.success) {
|
||||||
// case: login was successful
|
// case: login was successful
|
||||||
|
|
||||||
if (loginAttempt.mfaEnabled) {
|
|
||||||
// TODO: deal with MFA
|
|
||||||
// case: login requires MFA step
|
|
||||||
setIsLoading(false);
|
|
||||||
setStep(2);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// case: login does not require MFA step
|
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
createNotification({
|
createNotification({
|
||||||
text: "Successfully logged in",
|
text: "Successfully logged in",
|
||||||
@@ -284,6 +277,18 @@ export const PasswordStep = ({
|
|||||||
setCaptchaToken("");
|
setCaptchaToken("");
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (shouldShowMfa) {
|
||||||
|
return (
|
||||||
|
<div className="flex max-h-screen min-h-screen flex-col items-center justify-center gap-2 overflow-y-auto bg-gradient-to-tr from-mineshaft-600 via-mineshaft-800 to-bunker-700">
|
||||||
|
<Mfa
|
||||||
|
email={email}
|
||||||
|
successCallback={mfaSuccessCallback}
|
||||||
|
closeMfa={() => toggleShowMfa.off()}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if (hasExchangedPrivateKey) {
|
if (hasExchangedPrivateKey) {
|
||||||
return (
|
return (
|
||||||
<div className="flex max-h-screen min-h-screen flex-col items-center justify-center gap-2 overflow-y-auto bg-gradient-to-tr from-mineshaft-600 via-mineshaft-800 to-bunker-700">
|
<div className="flex max-h-screen min-h-screen flex-col items-center justify-center gap-2 overflow-y-auto bg-gradient-to-tr from-mineshaft-600 via-mineshaft-800 to-bunker-700">
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
export { InitialStep } from "./InitialStep";
|
export { InitialStep } from "./InitialStep";
|
||||||
export { MFAStep } from "./MFAStep";
|
|
||||||
export { SSOStep } from "./SSOStep";
|
export { SSOStep } from "./SSOStep";
|
||||||
|
|
||||||
// SSO-specific step
|
// SSO-specific step
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import { LoginMethod } from "@app/hooks/api/admin/types";
|
|||||||
import { LDAPModal } from "./LDAPModal";
|
import { LDAPModal } from "./LDAPModal";
|
||||||
import { OIDCModal } from "./OIDCModal";
|
import { OIDCModal } from "./OIDCModal";
|
||||||
import { OrgGeneralAuthSection } from "./OrgGeneralAuthSection";
|
import { OrgGeneralAuthSection } from "./OrgGeneralAuthSection";
|
||||||
|
import { OrgGenericAuthSection } from "./OrgGenericAuthSection";
|
||||||
import { OrgLDAPSection } from "./OrgLDAPSection";
|
import { OrgLDAPSection } from "./OrgLDAPSection";
|
||||||
import { OrgOIDCSection } from "./OrgOIDCSection";
|
import { OrgOIDCSection } from "./OrgOIDCSection";
|
||||||
import { OrgScimSection } from "./OrgSCIMSection";
|
import { OrgScimSection } from "./OrgSCIMSection";
|
||||||
@@ -161,6 +162,7 @@ export const OrgAuthTab = withPermission(
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
|
<OrgGenericAuthSection />
|
||||||
{shouldShowCreateIdentityProviderView ? (
|
{shouldShowCreateIdentityProviderView ? (
|
||||||
createIdentityProviderView
|
createIdentityProviderView
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
+73
@@ -0,0 +1,73 @@
|
|||||||
|
import { createNotification } from "@app/components/notifications";
|
||||||
|
import { OrgPermissionCan } from "@app/components/permissions";
|
||||||
|
import { Switch, UpgradePlanModal } from "@app/components/v2";
|
||||||
|
import {
|
||||||
|
OrgPermissionActions,
|
||||||
|
OrgPermissionSubjects,
|
||||||
|
useOrganization,
|
||||||
|
useSubscription
|
||||||
|
} from "@app/context";
|
||||||
|
import { useUpdateOrg } from "@app/hooks/api";
|
||||||
|
import { usePopUp } from "@app/hooks/usePopUp";
|
||||||
|
|
||||||
|
export const OrgGenericAuthSection = () => {
|
||||||
|
const { currentOrg } = useOrganization();
|
||||||
|
const { subscription } = useSubscription();
|
||||||
|
const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp(["upgradePlan"] as const);
|
||||||
|
|
||||||
|
const { mutateAsync } = useUpdateOrg();
|
||||||
|
|
||||||
|
const handleEnforceMfaToggle = async (value: boolean) => {
|
||||||
|
try {
|
||||||
|
if (!currentOrg?.id) return;
|
||||||
|
if (!subscription?.enforceMfa) {
|
||||||
|
handlePopUpOpen("upgradePlan");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await mutateAsync({
|
||||||
|
orgId: currentOrg?.id,
|
||||||
|
enforceMfa: value
|
||||||
|
});
|
||||||
|
|
||||||
|
createNotification({
|
||||||
|
text: `Successfully ${value ? "enforced" : "un-enforced"} MFA`,
|
||||||
|
type: "success"
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err);
|
||||||
|
createNotification({
|
||||||
|
text: (err as { response: { data: { message: string } } }).response.data.message,
|
||||||
|
type: "error"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mb-4 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-6">
|
||||||
|
<div className="py-4">
|
||||||
|
<div className="mb-2 flex justify-between">
|
||||||
|
<h3 className="text-md text-mineshaft-100">Enforce Multi-factor Authentication</h3>
|
||||||
|
<OrgPermissionCan I={OrgPermissionActions.Edit} a={OrgPermissionSubjects.Sso}>
|
||||||
|
{(isAllowed) => (
|
||||||
|
<Switch
|
||||||
|
id="enforce-org-mfa"
|
||||||
|
onCheckedChange={(value) => handleEnforceMfaToggle(value)}
|
||||||
|
isChecked={currentOrg?.enforceMfa ?? false}
|
||||||
|
isDisabled={!isAllowed}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</OrgPermissionCan>
|
||||||
|
</div>
|
||||||
|
<p className="text-sm text-mineshaft-300">
|
||||||
|
Enforce members to authenticate with MFA in order to access the organization
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<UpgradePlanModal
|
||||||
|
isOpen={popUp.upgradePlan.isOpen}
|
||||||
|
onOpenChange={(isOpen) => handlePopUpToggle("upgradePlan", isOpen)}
|
||||||
|
text="You can enforce user MFA if you switch to Infisical's Pro plan."
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -11,9 +11,11 @@ import { deriveArgonKey } from "@app/components/utilities/cryptography/crypto";
|
|||||||
import { saveTokenToLocalStorage } from "@app/components/utilities/saveTokenToLocalStorage";
|
import { saveTokenToLocalStorage } from "@app/components/utilities/saveTokenToLocalStorage";
|
||||||
import SecurityClient from "@app/components/utilities/SecurityClient";
|
import SecurityClient from "@app/components/utilities/SecurityClient";
|
||||||
import { Button, Input } from "@app/components/v2";
|
import { Button, Input } from "@app/components/v2";
|
||||||
|
import { useToggle } from "@app/hooks";
|
||||||
import { completeAccountSignup, useSelectOrganization } from "@app/hooks/api/auth/queries";
|
import { completeAccountSignup, useSelectOrganization } from "@app/hooks/api/auth/queries";
|
||||||
import { fetchOrganizations } from "@app/hooks/api/organization/queries";
|
import { fetchOrganizations } from "@app/hooks/api/organization/queries";
|
||||||
import ProjectService from "@app/services/ProjectService";
|
import ProjectService from "@app/services/ProjectService";
|
||||||
|
import { Mfa } from "@app/views/Login/Mfa";
|
||||||
|
|
||||||
// eslint-disable-next-line new-cap
|
// eslint-disable-next-line new-cap
|
||||||
const client = new jsrp.client();
|
const client = new jsrp.client();
|
||||||
@@ -54,9 +56,11 @@ export const UserInfoSSOStep = ({
|
|||||||
const [organizationName, setOrganizationName] = useState("");
|
const [organizationName, setOrganizationName] = useState("");
|
||||||
const [organizationNameError, setOrganizationNameError] = useState(false);
|
const [organizationNameError, setOrganizationNameError] = useState(false);
|
||||||
const [attributionSource, setAttributionSource] = useState("");
|
const [attributionSource, setAttributionSource] = useState("");
|
||||||
|
const [shouldShowMfa, toggleShowMfa] = useToggle(false);
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
const { mutateAsync: selectOrganization } = useSelectOrganization();
|
const { mutateAsync: selectOrganization } = useSelectOrganization();
|
||||||
|
const [mfaSuccessCallback, setMfaSuccessCallback] = useState<() => void>(() => {});
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const randomPassword = crypto.randomBytes(32).toString("hex");
|
const randomPassword = crypto.randomBytes(32).toString("hex");
|
||||||
@@ -172,10 +176,19 @@ export const UserInfoSSOStep = ({
|
|||||||
const userOrgs = await fetchOrganizations();
|
const userOrgs = await fetchOrganizations();
|
||||||
const orgId = userOrgs[0]?.id;
|
const orgId = userOrgs[0]?.id;
|
||||||
|
|
||||||
await selectOrganization({
|
const completeSignupFlow = async () => {
|
||||||
|
try {
|
||||||
|
const { isMfaEnabled, token } = await selectOrganization({
|
||||||
organizationId: orgId
|
organizationId: orgId
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (isMfaEnabled) {
|
||||||
|
SecurityClient.setMfaToken(token);
|
||||||
|
toggleShowMfa.on();
|
||||||
|
setMfaSuccessCallback(() => completeSignupFlow);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// only create example project if not joining existing org
|
// only create example project if not joining existing org
|
||||||
if (!providerOrganizationName) {
|
if (!providerOrganizationName) {
|
||||||
const project = await ProjectService.initProject({
|
const project = await ProjectService.initProject({
|
||||||
@@ -186,12 +199,18 @@ export const UserInfoSSOStep = ({
|
|||||||
}
|
}
|
||||||
|
|
||||||
localStorage.setItem("orgData.id", orgId);
|
localStorage.setItem("orgData.id", orgId);
|
||||||
|
|
||||||
setStep(2);
|
setStep(2);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
console.error(error);
|
console.error(error);
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
await completeSignupFlow();
|
||||||
|
} catch (error) {
|
||||||
|
setIsLoading(false);
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
@@ -206,6 +225,17 @@ export const UserInfoSSOStep = ({
|
|||||||
}
|
}
|
||||||
}, [providerOrganizationName, password]);
|
}, [providerOrganizationName, password]);
|
||||||
|
|
||||||
|
if (shouldShowMfa) {
|
||||||
|
return (
|
||||||
|
<Mfa
|
||||||
|
hideLogo
|
||||||
|
email={username}
|
||||||
|
successCallback={mfaSuccessCallback}
|
||||||
|
closeMfa={() => toggleShowMfa.off()}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mx-auto mb-36 h-full w-max rounded-xl md:mb-16 md:px-8">
|
<div className="mx-auto mb-36 h-full w-max rounded-xl md:mb-16 md:px-8">
|
||||||
<p className="text-medium mx-8 mb-6 flex justify-center bg-gradient-to-b from-white to-bunker-200 bg-clip-text text-xl font-bold text-transparent md:mx-16">
|
<p className="text-medium mx-8 mb-6 flex justify-center bg-gradient-to-b from-white to-bunker-200 bg-clip-text text-xl font-bold text-transparent md:mx-16">
|
||||||
|
|||||||
Reference in New Issue
Block a user