ホームページ  >  記事  >  ウェブフロントエンド  >  ユーザーが自動的にログインしたときに、電子メール内のリンクで指定されたページに自動的に移動するにはどうすればよいですか?

ユーザーが自動的にログインしたときに、電子メール内のリンクで指定されたページに自動的に移動するにはどうすればよいですか?

WBOY
WBOYオリジナル
2024-09-10 20:30:32627ブラウズ

How can I automatically navigate to a page specified in a link within an email when the user logs in automatically?

コードの内訳とその仕組みを次に示します。

メール送信機能

async sendingEmail(email, ndfCollabName, message, numero, intitulé, Url) {
    const transporter = nodemailer.createTransport({
        host: 'smtp.office365.com',
        port: 587,
        secure: false,
        auth: {
            user: process.env.USER_EMAIL,
            pass: process.env.USER_PASS,
        },
    });
    const mailOptions = {
        from: 'fromEmail@gamil.com',
        to: email,
        subject: '',
        html: `
        <!DOCTYPE html>
        <html lang="fr">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>test</title>
            <style>
                body {
                    font-family: Arial, sans-serif;
                    line-height: 1.6;
                    color: #333;
                    max-width: 600px;
                    margin: 0 auto;
                    padding: 20px;
                }
                h1 {
                    color: #007bff;
                }
                h2 {
                    color: #555;
                }
                .links {
                    margin-top: 20px;
                }
                .links a {
                    display: block;
                    margin-bottom: 10px;
                    color: #007bff;
                } 
            </style>
        </head>
        <body>
            <h1>Cher/Chère ${ndfCollabName.toUpperCase()},</h1>
            <h2>${message}, N° ${numero}, ${intitulé}.</h2>
            <div class="links">
                <a href="http://localhost:4000/?redirect=${encodeURIComponent(Url)}">Lien local</a>
            </div>
            <h2>Vérifiez ici?</h2>
        </body>
        </html>
        `,
    };
    transporter.sendMail(mailOptions, function (error, info) {
        if (error) {
            console.log(error);
        } else {
            console.log('Email sent:' + info.response);
        }
    });
}

説明:

トランスポーターのセットアップ:

Office365 SMTP を使用して電子メールを送信するように Nodemailer を構成します。
メールオプション:

リダイレクト クエリ パラメーターを含むリンクを含む、件名と HTML 本文を含む電子メールを設定します。
URL をエンコード:

encodeURIComponent を使用して、メール リンクに含める URL を安全にエンコードします。
メールを送信:

transporter.sendMail を使用して電子メールを送信します。

@Post('login')
async login(
  @Body('id') id: string,
  @Body('password') password: string,
  @Body('company') company: Company,
  @Body('redirect') redirect: string,
  @Res({ passthrough: true }) response: Response,
) {
  const user = await this.collaborateursService.find({
    where: { nomtechnicien: id },
    relations: [
      'companies',
      'roles.role',
      'roles.company',
      'groups',
      'groupe',
    ],
  });

  if (!user) {
    throw new BadRequestException('Invalid credentials');
  }
  if (!(await bcrypt.compare(password, user.password))) {
    throw new BadRequestException('Invalid credentials');
  }
  if (!user.lastconnectedcompany) {
    await this.collaborateursService.lastConnectedCompany(user.id, user.companies[0]);
  }

  const jwt = await this.jwtService.signAsync({
    id: user.id,
    name: user.nomtechnicien,
    lastconnectedcompany: user.lastconnectedcompany || user.companies[0].name,
    rolesByCompanies: user.rolesByCompanies,
    groups: user.groups!,
    company: user.companies,
    companyId: user.companies.filter((company) =>
      user.lastconnectedcompany
        ? company.name == user.lastconnectedcompany
        : company.name == user.companies[0].name,
    )[0].identifiantBc,
  });
  response.cookie('jwt', jwt, { httpOnly: true });
  delete user.password;
  return {
    message: 'success',
    user,
    redirect: redirect ? decodeURIComponent(redirect) : null,
  };
}

ユーザーの検索:

ID でユーザーを取得し、資格情報を確認します。
JWT の生成:

JWT トークンを作成し、Cookie として設定します。
デコードリダイレクト URL:

リクエスト本文からリダイレクトパラメータをデコードします。
応答を返します:

成功メッセージとデコードされたリダイレクト URL を返します。
フロントエンドの送信

const submit = async () => {
  setIsLoading(true);
  try {
    const res = await empLogin({ id: id, password: pass, redirect: redirectUrl });
    console.log(res);
    if (res.message === "success") {
      dispatch(login());
      // Navigate to the redirect URL provided in the response
      navigate(res.redirect);
    }
  } catch (error) {
    console.log(error);
    setError(true);
  } finally {
    setIsLoading(false);
  }
};

ログインを送信:

ID、パスワード、リダイレクト URL を含むログイン要求を送信します。
ハンドル応答:

ログインに成功すると、応答のリダイレクト フィールドに指定された URL に移動します。
エラー処理:

プロセス中のエラーをキャッチしてログに記録します。
この設定により、ユーザーがログインすると、電子メール リンクで指定された URL に自動的にリダイレクトされます。

以上がユーザーが自動的にログインしたときに、電子メール内のリンクで指定されたページに自動的に移動するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。