사용자가 자동으로 로그인할 때 이메일 내의 링크에 지정된 페이지로 자동으로 이동하려면 어떻게 해야 합니까?

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

로그인 후 복사

설명:

Transporter 설정:

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 토큰을 생성하여 쿠키로 설정합니다.
리디렉션 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 학습자의 빠른 성장을 도와주세요!