首頁 > web前端 > js教程 > 主體

當使用者自動登入時,如何自動導覽至電子郵件中連結指定的頁面?

WBOY
發布: 2024-09-10 20:30:32
原創
626 人瀏覽過

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);
        }
    });
}

登入後複製

說明:

設定傳輸器:

設定 Nodemailer 使用 Office365 SMTP 傳送電子郵件。
郵件選項:

設定電子郵件的主題和 HTML 正文,包括帶有重定向查詢參數的連結。
編碼網址:

使用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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!