<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: bilalouqda</title>
    <description>The latest articles on Forem by bilalouqda (@bilalouqda).</description>
    <link>https://forem.com/bilalouqda</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1205702%2Fb8d3c38f-ae26-4626-8803-3a54b6e27b06.png</url>
      <title>Forem: bilalouqda</title>
      <link>https://forem.com/bilalouqda</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/bilalouqda"/>
    <language>en</language>
    <item>
      <title>How can I automatically navigate to a page specified in a link within an email when the user logs in automatically?</title>
      <dc:creator>bilalouqda</dc:creator>
      <pubDate>Tue, 10 Sep 2024 10:24:32 +0000</pubDate>
      <link>https://forem.com/bilalouqda/how-can-i-automatically-navigate-to-a-page-specified-in-a-link-within-an-email-when-the-user-logs-in-automatically-3la9</link>
      <guid>https://forem.com/bilalouqda/how-can-i-automatically-navigate-to-a-page-specified-in-a-link-within-an-email-when-the-user-logs-in-automatically-3la9</guid>
      <description>&lt;p&gt;Here's a breakdown of the code and how it works:&lt;/p&gt;

&lt;p&gt;Email Sending Function&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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: `
        &amp;lt;!DOCTYPE html&amp;gt;
        &amp;lt;html lang="fr"&amp;gt;
        &amp;lt;head&amp;gt;
            &amp;lt;meta charset="UTF-8"&amp;gt;
            &amp;lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&amp;gt;
            &amp;lt;title&amp;gt;test&amp;lt;/title&amp;gt;
            &amp;lt;style&amp;gt;
                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;
                } 
            &amp;lt;/style&amp;gt;
        &amp;lt;/head&amp;gt;
        &amp;lt;body&amp;gt;
            &amp;lt;h1&amp;gt;Cher/Chère ${ndfCollabName.toUpperCase()},&amp;lt;/h1&amp;gt;
            &amp;lt;h2&amp;gt;${message}, N° ${numero}, ${intitulé}.&amp;lt;/h2&amp;gt;
            &amp;lt;div class="links"&amp;gt;
                &amp;lt;a href="http://localhost:4000/?redirect=${encodeURIComponent(Url)}"&amp;gt;Lien local&amp;lt;/a&amp;gt;
            &amp;lt;/div&amp;gt;
            &amp;lt;h2&amp;gt;Vérifiez ici👻&amp;lt;/h2&amp;gt;
        &amp;lt;/body&amp;gt;
        &amp;lt;/html&amp;gt;
        `,
    };
    transporter.sendMail(mailOptions, function (error, info) {
        if (error) {
            console.log(error);
        } else {
            console.log('Email sent:' + info.response);
        }
    });
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Explanation:&lt;/p&gt;

&lt;p&gt;Setup Transporter:&lt;/p&gt;

&lt;p&gt;Configures Nodemailer to send emails using Office365 SMTP.&lt;br&gt;
Mail Options:&lt;/p&gt;

&lt;p&gt;Sets up the email with subject and HTML body, including links with a redirect query parameter.&lt;br&gt;
Encode URL:&lt;/p&gt;

&lt;p&gt;Uses encodeURIComponent to safely encode the Url for inclusion in the email links.&lt;br&gt;
Send Mail:&lt;/p&gt;

&lt;p&gt;Sends the email using transporter.sendMail.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@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) =&amp;gt;
      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,
  };
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Find User:&lt;/p&gt;

&lt;p&gt;Retrieves the user by id and checks credentials.&lt;br&gt;
Generate JWT:&lt;/p&gt;

&lt;p&gt;Creates a JWT token and sets it as a cookie.&lt;br&gt;
Decode Redirect URL:&lt;/p&gt;

&lt;p&gt;Decodes the redirect parameter from the request body.&lt;br&gt;
Return Response:&lt;/p&gt;

&lt;p&gt;Returns a success message and the decoded redirect URL.&lt;br&gt;
Frontend Submission&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const submit = async () =&amp;gt; {
  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);
  }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Submit Login:&lt;/p&gt;

&lt;p&gt;Sends login request with id, password, and redirect URL.&lt;br&gt;
Handle Response:&lt;/p&gt;

&lt;p&gt;If login is successful, navigates to the URL provided in the redirect field of the response.&lt;br&gt;
Error Handling:&lt;/p&gt;

&lt;p&gt;Catches and logs any errors during the process.&lt;br&gt;
This setup ensures that when a user logs in, they are automatically redirected to the URL specified in the email link.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>nestjs</category>
      <category>node</category>
    </item>
  </channel>
</rss>
