Сброс пароля и подтверждение электронной почты
Завершите настройку аутентификации по электронной почте и паролю: позвольте пользователям сбрасывать забытые пароли и подтверждать адреса электронной почты, повысив безопасность и упростив восстановление аккаунтов.
«Сброс пароля и подтверждение электронной почты» — бесплатный урок Firebase Auth & Realtime Database Apps на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Firebase Auth & Realtime Database Apps, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Firebase Auth & Realtime Database Apps содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Why Reset and Verification Matter
Email/password sign-in is incomplete without two flows: password reset for forgotten credentials and email verification to prove the user owns the address.
- Reset reduces support tickets and lockouts
- Verification blocks fake or mistyped emails
How Password Reset Works
The flow is entirely email-driven so the user never reveals an old password:
- User requests a reset for their email
- Firebase sends a secure, time-limited link
- User clicks it and chooses a new password
Your app only triggers the email; Firebase hosts the reset page by default.
Triggering a Reset Email
Call sendPasswordResetEmail with the user's address. Firebase handles delivery and the link.
import { getAuth, sendPasswordResetEmail } from 'firebase/auth';
const auth = getAuth();
await sendPasswordResetEmail(auth, 'user@example.com');
console.log('Reset email sent');Handling Reset Errors Gracefully
For security, avoid revealing whether an email exists. Show the same confirmation message whether or not the account is found.
try {
await sendPasswordResetEmail(auth, email);
} catch (e) {
// log internally but do not expose to user
}
showMessage('If that email exists, a reset link was sent.');Sending a Verification Email
After a user signs up, send a verification email with sendEmailVerification on the current user object.
import { getAuth, sendEmailVerification } from 'firebase/auth';
const user = getAuth().currentUser;
if (user) {
await sendEmailVerification(user);
}Checking Verification Status
The user object exposes emailVerified. Use it to gate sensitive features until the address is confirmed.
const user = getAuth().currentUser;
if (user && !user.emailVerified) {
showBanner('Please verify your email to continue.');
}Refreshing the Token After Verification
The emailVerified flag is cached in the ID token. After a user verifies, call reload to refresh their local state.
const user = getAuth().currentUser;
await user.reload();
console.log('Verified now?', user.emailVerified);Customizing Email Templates
In the Firebase console under Authentication > Templates you can customize the sender name, subject, and body of reset and verification emails, and set a custom action URL for branded pages.
Enforcing Verification
You can require a verified email before granting access to certain data using Security Rules. Tokens carry an email_verified claim you can check.
{
"rules": {
"posts": {
".write": "auth != null && auth.token.email_verified == true"
}
}
}Rate Limiting and Abuse
Firebase throttles repeated reset and verification requests to prevent abuse and spam. In your UI, disable the button briefly after sending so users do not trigger the limit accidentally.
Putting It Together
A complete signup typically looks like: create account, send verification email, show a 'check your inbox' screen, and reveal full features once emailVerified becomes true. A 'Forgot password?' link calls the reset flow.
Quick Check
Test your understanding of reset and verification.
Recap
Your email/password auth is now complete and recoverable.
- Use
sendPasswordResetEmailfor forgotten passwords - Avoid revealing whether an email exists
- Verify ownership with
sendEmailVerificationandemailVerified - Call
reloadto refresh status - Customize templates and enforce verification via rules
Часто задаваемые вопросы
Урок «Сброс пароля и подтверждение электронной почты» бесплатный?
Да — полный текст урока «Сброс пароля и подтверждение электронной почты» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Firebase Auth & Realtime Database Apps, подпишись на CoddyKit PRO. Курс Firebase Auth & Realtime Database Apps содержит 4 уроков всего.
Чему я научусь в уроке «Сброс пароля и подтверждение электронной почты»?
Завершите настройку аутентификации по электронной почте и паролю: позвольте пользователям сбрасывать забытые пароли и подтверждать адреса электронной почты, повысив безопасность и упростив восстановл… Ты практикуешь Firebase Auth & Realtime Database Apps с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Firebase Auth & Realtime Database Apps?
Предыдущий опыт не требуется. Firebase Auth & Realtime Database Apps на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Сброс пароля и подтверждение электронной почты»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Firebase Auth & Realtime Database Apps?
Да. Каждый урок Firebase Auth & Realtime Database Apps включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Реализация аутентификации по электронной почте и паролю
- Управление сеансами и состояниями пользователей
- Обработка ошибок аутентификации
- Сброс пароля и подтверждение электронной почты