Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added option to send verification link insted of verification code #1529

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions backend/src/services/auth-token/auth-token-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ export const getTokenConfig = (tokenType: TokenType) => {
// type [type]
switch (tokenType) {
case TokenType.TOKEN_EMAIL_CONFIRMATION: {
// generate random 6-digit code
const token = String(crypto.randomInt(10 ** 5, 10 ** 6 - 1));
// generate random hex
const token = crypto.randomBytes(16).toString("hex");
const expiresAt = new Date(new Date().getTime() + 86400000);
return { token, expiresAt };
}
Expand Down Expand Up @@ -84,6 +84,14 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL }: TAuthTokenServiceFact
code,
orgId
}: TValidateTokenForUserDTO): Promise<TAuthTokens | undefined> => {
const appCfg = getConfig();

// check if smtp is not configured, consider the token as valid
if (!appCfg.isSmtpConfigured) {
const deletedToken = await tokenDAL.delete({ type, userId, orgId: orgId || null });
return deletedToken?.[0];
}

const token = await tokenDAL.findOne({ type, userId, orgId: orgId || null });
// validate token
if (!token) throw new Error("Failed to find token");
Expand All @@ -92,7 +100,7 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL }: TAuthTokenServiceFact
throw new Error("Token expired. Please try again");
}

const isValidToken = await bcrypt.compare(code, token.tokenHash);
const isValidToken = await bcrypt.compare(code.toString(), token.tokenHash);
if (!isValidToken) {
if (token?.triesLeft) {
if (token.triesLeft === 1) {
Expand Down
8 changes: 5 additions & 3 deletions backend/src/services/auth/auth-signup-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,14 @@ export const authSignupServiceFactory = ({
userId: user.id
});

const encodedToken = Buffer.from(JSON.stringify({ email, token })).toString("base64"); // converting one token using actual token and email
const verificationLink = `${getConfig().SITE_URL}/signup?token=${encodedToken}`;
await smtpService.sendMail({
template: SmtpTemplates.EmailVerification,
subjectLine: "Infisical confirmation code",
subjectLine: "Infisical confirmation link",
recipients: [email],
substitutions: {
code: token
link: verificationLink
}
});
};
Expand All @@ -73,7 +75,7 @@ export const authSignupServiceFactory = ({
const user = await userDAL.findUserByEmail(email);
if (!user || (user && user.isAccepted)) {
// TODO(akhilmhdh): copy as old one. this needs to be changed due to security issues
throw new Error("Failed to send verification code for complete account");
throw new Error("Failed to send verification token for complete account");
}
const appCfg = getConfig();
await tokenService.validateTokenForUser({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Code</title>
<title>Signup Verification</title>
</head>

<body>
<h2>Confirm your email address</h2>
<p>Your confirmation code is below — enter it in the browser window where you've started signing up for Infisical.</p>
<h1>{{code}}</h1>
<p>You're almost set to start enjoying Infisical. Simply click the link below to verify your email address and get started. The link expires in 24 hours. If you did not attempt to sign up an account with Infisical, it's safe to ignore this email.</p>
<a href="{{link}}" target="_blank">Verify my email address</a>
<p>Questions about setting up Infisical? Email us at [email protected]</p>
</body>

Expand Down
8 changes: 6 additions & 2 deletions frontend/public/locales/en/translations.json
Original file line number Diff line number Diff line change
Expand Up @@ -320,12 +320,16 @@
"step1-start": "Let's get started",
"step1-privacy": "By creating an account, you agree to our Terms and have read and acknowledged the Privacy Policy.",
"step1-submit": "Get Started",
"step2-message": "We've sent a verification code to",
"step2-message": "We've sent a verification mail to",
"step2-code-error": "Oops. Your code is wrong. Please try again.",
"step2-resend-alert": "Don't see the code?",
"step2-resend-alert": "Don't see the mail?",
"step2-resend-submit": "Resend",
"step2-resend-progress": "Resending...",
"step2-spam-alert": "Make sure to check your spam inbox.",
"step2-validating-token": "Please wait, we are verifying your email.",
"step2-validation-failed-title": "Verification Failed!",
"step2-validation-failed-message": "This could be due to an expired or invalid verification link",
"step2-validation-failed-cta": "Return to Signup Page",
"step3-message": "Almost there!",
"step4-message": "Save your Emergency Kit",
"step4-description1": "If you get locked out of your account, your Emergency Kit is the only way to sign in.",
Expand Down
8 changes: 6 additions & 2 deletions frontend/public/locales/es/translations.json
Original file line number Diff line number Diff line change
Expand Up @@ -304,12 +304,16 @@
"step1-start": "Vamos a empezar",
"step1-privacy": "Al crear la cuenta, aceptas nuestros Términos y has leído y comprendido nuestra Política de privacidad.",
"step1-submit": "Empezar",
"step2-message": "Hemos enviado un código a",
"step2-message": "Hemos enviado un correo a",
"step2-code-error": "Oops. Tu código es incorrecto. Intentos restantes:",
"step2-resend-alert": "¿No ves el código?",
"step2-resend-alert": "¿No ves el correo?",
"step2-resend-submit": "Volver a enviar",
"step2-resend-progress": "Reenviando...",
"step2-spam-alert": "Asegúrate de comprobar la carpeta de spam.",
"step2-validating-token": "Espere, estamos verificando su correo electrónico.",
"step2-validation-failed-title": "¡Fallo en la verificación!",
"step2-validation-failed-message": "Esto podría deberse a un enlace de verificación caducado o no válido.",
"step2-validation-failed-cta": "Volver a la página de registro",
"step3-message": "¡Casi hemos terminado!",
"step4-message": "Guarda tu Kit de emergencia",
"step4-description1": "Si pierdes el acceso a tu cuenta, tu Kit de emergencia es la única forma de iniciar sesión.",
Expand Down
6 changes: 5 additions & 1 deletion frontend/public/locales/fr/translations.json
Original file line number Diff line number Diff line change
Expand Up @@ -286,10 +286,14 @@
"step1-submit": "C'est parti",
"step2-message": "Nous avons envoyé un email de vérification à",
"step2-code-error": "Oops. Votre code est faux. Veuillez réessayer.",
"step2-resend-alert": "Vous ne voyez pas le code?",
"step2-resend-alert": "Vous ne voyez pas le courrier ?",
"step2-resend-submit": "Renvoyer",
"step2-resend-progress": "Envoie en cours...",
"step2-spam-alert": "Assurez-vous de vérifier vos spams.",
"step2-validating-token": "Veuillez patienter, nous vérifions votre email.",
"step2-validation-failed-title": "Échec de la vérification!",
"step2-validation-failed-message": "Cela peut être dû à un lien de vérification expiré ou invalide.",
"step2-validation-failed-cta": "Revenir à la page d'inscription",
"step3-message": "Nous y sommes presque!",
"step4-message": "Enregistrez votre kit d'urgence",
"step4-description1": "Si vous n'arrivez plus à vous connecter à votre compte, votre kit d'urgence est le seul moyen d'y arriver.",
Expand Down
4 changes: 4 additions & 0 deletions frontend/public/locales/ko/translations.json
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,10 @@
"step2-message": "<email>{{email}}</email><wrapper>로 인증 메일을 전송하였습니다</wrapper><email>{{email}}</email>",
"step2-code-error": "코드가 잘못된 것 같아요. 다시 시도해주세요.",
"step2-spam-alert": "스팸함에 메일이 있지는 않은지 확인하세요",
"step2-validating-token": "이메일을 확인 중입니다. 잠시 기다려 주세요.",
"step2-validation-failed-title": "확인 실패!",
"step2-validation-failed-message": "이는 만료되었거나 유효하지 않은 확인 링크 때문일 수 있습니다.",
"step2-validation-failed-cta": "가입 페이지로 돌아가기",
"step3-message": "거의다 끝났어요!",
"step4-message": "긴급복구 키트 저장하기",
"step4-description1": "계정이 잠겼을 경우 비상 키트를 사용하여 로그인할 수 있어요.",
Expand Down
4 changes: 4 additions & 0 deletions frontend/public/locales/pt-BR/translations.json
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,10 @@
"step2-message": "<wrapper>Enviamos um e-mail de verificação para</wrapper><email>{{email}}</email>",
"step2-code-error": "Ops. Seu código está errado. Por favor, tente novamente.",
"step2-spam-alert": "Certifique-se de verificar sua caixa de entrada de spam.",
"step2-validating-token": "Aguarde, estamos verificando seu e-mail.",
"step2-validation-failed-title": "Falha na verificação!",
"step2-validation-failed-message": "Isso pode ser devido a um link de verificação expirado ou inválido",
"step2-validation-failed-cta": "Retornar à página de inscrição",
"step3-message": "Quase lá!",
"step4-message": "Guarde o seu Kit de Emergência",
"step4-description1": "Se sua conta for bloqueada, seu Kit de emergência é a única maneira de fazer login.",
Expand Down
6 changes: 5 additions & 1 deletion frontend/public/locales/tr/translations.json
Original file line number Diff line number Diff line change
Expand Up @@ -304,10 +304,14 @@
"step1-submit": "Başla",
"step2-message": "Şu adrese bir doğrulama maili yolladık",
"step2-code-error": "Tüh. Kodun hatalı. Lütfen tekrar dene.",
"step2-resend-alert": "Kodu ulaşamadı mı?",
"step2-resend-alert": "Postayı almadınız mı?",
"step2-resend-submit": "Tekrar Yolla",
"step2-resend-progress": "Tekrar yollanıyor...",
"step2-spam-alert": "Spam kutunuzu kontrol ettiğinizden emin olun.",
"step2-validating-token": "Lütfen bekleyin, e-postanızı doğruluyoruz.",
"step2-validation-failed-title": "Doğrulama başarısız oldu!",
"step2-validation-failed-message": "Bunun nedeni süresi dolmuş veya geçersiz bir doğrulama bağlantısı olabilir",
"step2-validation-failed-cta": "Kayıt Sayfasına Dön",
"step3-message": "Çok az kaldı!",
"step4-message": "Acil Durum Kitinizi kayıt edin",
"step4-description1": "Eğer hesabınıza erişemezseniz, Acil Durum Kitiniz giriş yapmanın tek yoludur.",
Expand Down
148 changes: 0 additions & 148 deletions frontend/src/components/signup/CodeInputStep.tsx

This file was deleted.

54 changes: 54 additions & 0 deletions frontend/src/components/signup/EmailSendStep.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/* eslint-disable react/jsx-props-no-spreading */
import { useState } from "react";
import { useTranslation } from "react-i18next";

import { useSendVerificationEmail } from "@app/hooks/api";

interface EmailSendStepProps {
email: string;
}

/**
* This is the second step of sign up where users need to verify their email
* @param {object} obj
* @param {string} obj.email - user's email to which we just sent a verification email
* @returns
*/
export default function EmailSendStep({ email }: EmailSendStepProps): JSX.Element {
const { mutateAsync } = useSendVerificationEmail();
const [isLoading, setIsLoading] = useState(false);
const [isResendingVerificationEmail, setIsResendingVerificationEmail] = useState(false);
const { t } = useTranslation();

const resendVerificationEmail = async () => {
setIsResendingVerificationEmail(true);
setIsLoading(true);
await mutateAsync({ email });
setTimeout(() => {
setIsLoading(false);
setIsResendingVerificationEmail(false);
}, 2000);
};

return (
<div className="mx-auto h-full w-full pb-4 md:px-8">
<p className="text-md flex justify-center text-bunker-200">{t("signup.step2-message")}</p>
<p className="text-md my-1 flex justify-center font-semibold text-bunker-200">{email} </p>
<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={isLoading} onClick={resendVerificationEmail} type="button">
<span className="cursor-pointer duration-200 hover:text-bunker-200 hover:underline hover:decoration-primary-700 hover:underline-offset-4">
{isResendingVerificationEmail
? 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>
);
}
Loading
Loading