DEV Community

bilalouqda
bilalouqda

Posted on

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

Here's a breakdown of the code and how it works:

Email Sending Function

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

Enter fullscreen mode Exit fullscreen mode

Explanation:

Setup Transporter:

Configures Nodemailer to send emails using Office365 SMTP.
Mail Options:

Sets up the email with subject and HTML body, including links with a redirect query parameter.
Encode URL:

Uses encodeURIComponent to safely encode the Url for inclusion in the email links.
Send Mail:

Sends the email using 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,
  };
}

Enter fullscreen mode Exit fullscreen mode

Find User:

Retrieves the user by id and checks credentials.
Generate JWT:

Creates a JWT token and sets it as a cookie.
Decode Redirect URL:

Decodes the redirect parameter from the request body.
Return Response:

Returns a success message and the decoded redirect URL.
Frontend Submission

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

Enter fullscreen mode Exit fullscreen mode

Submit Login:

Sends login request with id, password, and redirect URL.
Handle Response:

If login is successful, navigates to the URL provided in the redirect field of the response.
Error Handling:

Catches and logs any errors during the process.
This setup ensures that when a user logs in, they are automatically redirected to the URL specified in the email link.

Top comments (0)