feat(identity): confirm the email address with a six-digit code from the message
This commit is contained in:
1 parent
c94434cd09
commit
d365a05c96
87 files changed
+4764
-224
No files matched your search
@@ -4,6 +4,7 @@ import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
@@ -36,6 +37,12 @@ type VerificationData struct {
|
||||
// TokenLifetime is the policy value stated in the copy, from 1 hour to
|
||||
// 7 days.
|
||||
TokenLifetime domain.Hours
|
||||
// Code is the six-digit code the message shows. VerificationCode redacts
|
||||
// itself in fmt and slog output.
|
||||
Code domain.VerificationCode
|
||||
// CodeLifetime is the validity of the code stated in the copy: whole
|
||||
// minutes, from 1 to 60.
|
||||
CodeLifetime time.Duration
|
||||
}
|
||||
|
||||
// PasswordResetData is the input of the password reset message.
|
||||
@@ -77,6 +84,15 @@ type tokenLinkView struct {
|
||||
LifetimeHours int
|
||||
}
|
||||
|
||||
// verificationCodeView is what the verification templates receive: the link
|
||||
// view plus the code and its validity in whole minutes.
|
||||
type verificationCodeView struct {
|
||||
tokenLinkView
|
||||
|
||||
Code string
|
||||
CodeLifetimeMinutes int
|
||||
}
|
||||
|
||||
// notificationView is what the notification templates receive. TextBody is
|
||||
// the sanitized body for the plain-text part; Paragraphs holds the same lines
|
||||
// for the HTML part, where html/template escapes each line.
|
||||
@@ -97,6 +113,26 @@ func (renderer *Renderer) tokenLinkView(linkPath string, token domain.SecretToke
|
||||
return tokenLinkView{Link: renderer.tokenLink(linkPath, token), LifetimeHours: int(lifetime)}, nil
|
||||
}
|
||||
|
||||
// maxCodeLifetimeMinutes bounds the code copy; the code lifetime is a fixed
|
||||
// product value of 30 minutes, so a longer value in the copy would be a bug.
|
||||
const maxCodeLifetimeMinutes = 60
|
||||
|
||||
func (renderer *Renderer) verificationCodeView(data VerificationData) (verificationCodeView, error) {
|
||||
const location = "Renderer.verificationCodeView"
|
||||
link, err := renderer.tokenLinkView(verifyEmailPath, data.Token, data.TokenLifetime)
|
||||
if err != nil {
|
||||
return verificationCodeView{}, err
|
||||
}
|
||||
if data.Code.IsZero() {
|
||||
return verificationCodeView{}, invalidData(location, "verification code must be set")
|
||||
}
|
||||
minutes := data.CodeLifetime / time.Minute
|
||||
if data.CodeLifetime%time.Minute != 0 || minutes < 1 || minutes > maxCodeLifetimeMinutes {
|
||||
return verificationCodeView{}, invalidData(location, fmt.Sprintf("code lifetime must be whole minutes from 1 to %d", maxCodeLifetimeMinutes))
|
||||
}
|
||||
return verificationCodeView{tokenLinkView: link, Code: data.Code.Reveal(), CodeLifetimeMinutes: int(minutes)}, nil
|
||||
}
|
||||
|
||||
func (renderer *Renderer) notificationView(data NotificationData) (notificationView, error) {
|
||||
if !utf8.ValidString(data.Subject) || !utf8.ValidString(data.Body) {
|
||||
return notificationView{}, invalidData("Renderer.notificationView", "subject and body must be valid UTF-8")
|
||||
|
||||
@@ -42,7 +42,7 @@ type TemplateVersion string
|
||||
// The versions that new renderings use. Changing copy means adding new
|
||||
// template files with the next version and pointing the constant at them.
|
||||
const (
|
||||
currentVerificationVersion TemplateVersion = "verification.v1"
|
||||
currentVerificationVersion TemplateVersion = "verification.v2"
|
||||
currentPasswordResetVersion TemplateVersion = "password_reset.v1"
|
||||
currentNotificationVersion TemplateVersion = "notification.v1"
|
||||
)
|
||||
@@ -110,10 +110,10 @@ func NewRenderer(publicOrigin string) (*Renderer, error) {
|
||||
return &Renderer{origin: origin, templates: templates}, nil
|
||||
}
|
||||
|
||||
// RenderVerification renders the email confirmation message. The link is
|
||||
// <origin>/verify-email#token=<token>.
|
||||
// RenderVerification renders the email confirmation message with its six-digit
|
||||
// code and the link. The link is <origin>/verify-email#token=<token>.
|
||||
func (renderer *Renderer) RenderVerification(data VerificationData) (RenderedMail, error) {
|
||||
view, err := renderer.tokenLinkView(verifyEmailPath, data.Token, data.TokenLifetime)
|
||||
view, err := renderer.verificationCodeView(data)
|
||||
if err != nil {
|
||||
return RenderedMail{}, fmt.Errorf("Renderer.RenderVerification - validate data: %w", err)
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
@@ -50,6 +51,21 @@ func testToken(t *testing.T) domain.SecretToken {
|
||||
return token
|
||||
}
|
||||
|
||||
// testCode is a fixed synthetic code. It is not a credential.
|
||||
const (
|
||||
syntheticCode = "482915"
|
||||
testCodeLifetime = 30 * time.Minute
|
||||
)
|
||||
|
||||
func testCode(t *testing.T) domain.VerificationCode {
|
||||
t.Helper()
|
||||
code, err := domain.ParseVerificationCode(syntheticCode)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseVerificationCode() error = %v", err)
|
||||
}
|
||||
return code
|
||||
}
|
||||
|
||||
func hostileNotification() NotificationData {
|
||||
return NotificationData{Subject: hostileSubject, Body: hostileBody, LinkPath: "/candidate/invitations"}
|
||||
}
|
||||
@@ -58,7 +74,7 @@ func hostileNotification() NotificationData {
|
||||
func renderAll(t *testing.T, renderer *Renderer) map[Kind]RenderedMail {
|
||||
t.Helper()
|
||||
token := testToken(t)
|
||||
verification, err := renderer.RenderVerification(VerificationData{Token: token, TokenLifetime: 24})
|
||||
verification, err := renderer.RenderVerification(VerificationData{Token: token, TokenLifetime: 24, Code: testCode(t), CodeLifetime: testCodeLifetime})
|
||||
if err != nil {
|
||||
t.Fatalf("RenderVerification() error = %v", err)
|
||||
}
|
||||
@@ -102,7 +118,7 @@ func assertGolden(t *testing.T, path, got string) {
|
||||
|
||||
func TestRenderingCarriesKindAndVersion(t *testing.T) {
|
||||
want := map[Kind]TemplateVersion{
|
||||
KindVerification: "verification.v1",
|
||||
KindVerification: "verification.v2",
|
||||
KindPasswordReset: "password_reset.v1",
|
||||
KindNotification: "notification.v1",
|
||||
}
|
||||
@@ -146,7 +162,7 @@ func TestLoopbackOriginKeepsPort(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("NewRenderer() error = %v", err)
|
||||
}
|
||||
mail, err := renderer.RenderVerification(VerificationData{Token: testToken(t), TokenLifetime: 24})
|
||||
mail, err := renderer.RenderVerification(VerificationData{Token: testToken(t), TokenLifetime: 24, Code: testCode(t), CodeLifetime: testCodeLifetime})
|
||||
if err != nil {
|
||||
t.Fatalf("RenderVerification() error = %v", err)
|
||||
}
|
||||
@@ -251,18 +267,29 @@ func TestNotificationRejectsLinksOutsideTheApp(t *testing.T) {
|
||||
func TestRejectsInvalidData(t *testing.T) {
|
||||
renderer := newTestRenderer(t)
|
||||
token := testToken(t)
|
||||
code := testCode(t)
|
||||
tokenCases := map[string]VerificationData{
|
||||
"missing token": {TokenLifetime: 24},
|
||||
"zero lifetime": {Token: token},
|
||||
"negative": {Token: token, TokenLifetime: -1},
|
||||
"lifetime too big": {Token: token, TokenLifetime: maxTokenLifetime + 1},
|
||||
"missing token": {TokenLifetime: 24, Code: code, CodeLifetime: testCodeLifetime},
|
||||
"zero lifetime": {Token: token, Code: code, CodeLifetime: testCodeLifetime},
|
||||
"negative": {Token: token, TokenLifetime: -1, Code: code, CodeLifetime: testCodeLifetime},
|
||||
"lifetime too big": {Token: token, TokenLifetime: maxTokenLifetime + 1, Code: code, CodeLifetime: testCodeLifetime},
|
||||
"missing code": {Token: token, TokenLifetime: 24, CodeLifetime: testCodeLifetime},
|
||||
"zero code lifetime": {Token: token, TokenLifetime: 24, Code: code},
|
||||
"code lifetime seconds": {Token: token, TokenLifetime: 24, Code: code, CodeLifetime: testCodeLifetime + time.Second},
|
||||
"code lifetime too long": {Token: token, TokenLifetime: 24, Code: code, CodeLifetime: 61 * time.Minute},
|
||||
}
|
||||
for name, data := range tokenCases {
|
||||
if _, err := renderer.RenderVerification(data); !errors.Is(err, ErrInvalidTemplateData) {
|
||||
t.Fatalf("RenderVerification(%s) error = %v", name, err)
|
||||
}
|
||||
reset := PasswordResetData(data)
|
||||
if _, err := renderer.RenderPasswordReset(reset); !errors.Is(err, ErrInvalidTemplateData) {
|
||||
}
|
||||
resetCases := map[string]PasswordResetData{
|
||||
"missing token": {TokenLifetime: 24},
|
||||
"zero lifetime": {Token: token},
|
||||
"negative": {Token: token, TokenLifetime: -1},
|
||||
}
|
||||
for name, data := range resetCases {
|
||||
if _, err := renderer.RenderPasswordReset(data); !errors.Is(err, ErrInvalidTemplateData) {
|
||||
t.Fatalf("RenderPasswordReset(%s) error = %v", name, err)
|
||||
}
|
||||
}
|
||||
@@ -287,7 +314,7 @@ func TestRejectsInvalidData(t *testing.T) {
|
||||
func TestLifetimeCopyUsesRussianPlural(t *testing.T) {
|
||||
renderer := newTestRenderer(t)
|
||||
for hours, want := range map[domain.Hours]string{1: "1 час.", 3: "3 часа.", 11: "11 часов.", 21: "21 час.", 24: "24 часа.", 48: "48 часов.", 168: "168 часов."} {
|
||||
mail, err := renderer.RenderVerification(VerificationData{Token: testToken(t), TokenLifetime: hours})
|
||||
mail, err := renderer.RenderVerification(VerificationData{Token: testToken(t), TokenLifetime: hours, Code: testCode(t), CodeLifetime: testCodeLifetime})
|
||||
if err != nil {
|
||||
t.Fatalf("RenderVerification(%d) error = %v", hours, err)
|
||||
}
|
||||
@@ -336,10 +363,10 @@ func TestContentHashPinsTheBody(t *testing.T) {
|
||||
base Kind
|
||||
}{
|
||||
{"token", func() (RenderedMail, error) {
|
||||
return renderer.RenderVerification(VerificationData{Token: otherToken, TokenLifetime: 24})
|
||||
return renderer.RenderVerification(VerificationData{Token: otherToken, TokenLifetime: 24, Code: testCode(t), CodeLifetime: testCodeLifetime})
|
||||
}, KindVerification},
|
||||
{"lifetime", func() (RenderedMail, error) {
|
||||
return renderer.RenderVerification(VerificationData{Token: testToken(t), TokenLifetime: 25})
|
||||
return renderer.RenderVerification(VerificationData{Token: testToken(t), TokenLifetime: 25, Code: testCode(t), CodeLifetime: testCodeLifetime})
|
||||
}, KindVerification},
|
||||
{"body", func() (RenderedMail, error) {
|
||||
data := hostileNotification()
|
||||
@@ -376,7 +403,7 @@ func TestRenderingNeverReachesLogs(t *testing.T) {
|
||||
slog.New(slog.NewTextHandler(&output, nil)),
|
||||
slog.New(slog.NewJSONHandler(&output, nil)),
|
||||
}
|
||||
verification := VerificationData{Token: token, TokenLifetime: 24}
|
||||
verification := VerificationData{Token: token, TokenLifetime: 24, Code: testCode(t), CodeLifetime: testCodeLifetime}
|
||||
notification := hostileNotification()
|
||||
// RenderedMail hides its content even in an unexported field.
|
||||
// NotificationData redacts itself only where fmt can call its methods.
|
||||
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="light">
|
||||
<title>{{.Subject}}</title>
|
||||
</head>
|
||||
<body style="margin:0;padding:0;background-color:#ededed;color:#1b1c21;font-family:Arial,Helvetica,sans-serif;font-size:16px;line-height:1.5;">
|
||||
<div style="max-width:560px;margin:0 auto;padding:24px 12px;">
|
||||
<div style="background-color:#ffffff;border-top:4px solid #402fff;border-radius:8px;padding:28px 24px;">
|
||||
<p style="margin:0 0 24px;font-size:18px;font-weight:bold;letter-spacing:0.02em;color:#1b1c21;">Lincodex</p>
|
||||
<h1 style="margin:0 0 16px;font-size:22px;line-height:1.3;color:#1b1c21;">Подтвердите адрес почты</h1>
|
||||
<p style="margin:0 0 16px;">Чтобы завершить регистрацию в Lincodex, введите код на странице подтверждения вместе с паролем, который вы выбрали при регистрации.</p>
|
||||
<p style="margin:0 0 8px;font-size:14px;">Код подтверждения:</p>
|
||||
<p style="margin:0 0 8px;padding:16px;border-radius:6px;background-color:#f3f2ff;color:#1b1c21;font-family:'Courier New',Courier,monospace;font-size:32px;font-weight:bold;letter-spacing:0.3em;text-align:center;">{{.View.Code}}</p>
|
||||
<p style="margin:0 0 24px;font-size:14px;">Код действует {{.View.CodeLifetimeMinutes}} {{plural .View.CodeLifetimeMinutes "минуту" "минуты" "минут"}}.</p>
|
||||
<p style="margin:0 0 8px;font-size:14px;">Или откройте ссылку и подтвердите адрес на открывшейся странице:</p>
|
||||
<p style="margin:0 0 24px;"><a href="{{.View.Link}}" style="display:inline-block;padding:12px 24px;border-radius:6px;background-color:#402fff;color:#ffffff;font-weight:bold;text-decoration:none;">Подтвердить почту</a></p>
|
||||
<p style="margin:0 0 8px;font-size:14px;">Если кнопка не работает, скопируйте ссылку в адресную строку браузера:</p>
|
||||
<p style="margin:0 0 24px;font-size:14px;word-break:break-all;"><a href="{{.View.Link}}" style="color:#402fff;">{{.View.Link}}</a></p>
|
||||
<p style="margin:0 0 16px;">Ссылка действует {{.View.LifetimeHours}} {{plural .View.LifetimeHours "час" "часа" "часов"}}.</p>
|
||||
<p style="margin:0;">Если вы не регистрировались в Lincodex, ничего не делайте: без подтверждения аккаунт не будет активирован.</p>
|
||||
</div>
|
||||
<p style="margin:16px 12px 0;font-size:13px;color:#2d2e37;">Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.</p>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
+1
@@ -0,0 +1 @@
|
||||
Подтвердите почту в Lincodex
|
||||
@@ -0,0 +1,18 @@
|
||||
Подтвердите адрес почты
|
||||
|
||||
Чтобы завершить регистрацию в Lincodex, введите код на странице подтверждения вместе с паролем, который вы выбрали при регистрации:
|
||||
|
||||
Код подтверждения: {{.View.Code}}
|
||||
|
||||
Код действует {{.View.CodeLifetimeMinutes}} {{plural .View.CodeLifetimeMinutes "минуту" "минуты" "минут"}}.
|
||||
|
||||
Или откройте ссылку и подтвердите адрес на открывшейся странице:
|
||||
|
||||
{{.View.Link}}
|
||||
|
||||
Ссылка действует {{.View.LifetimeHours}} {{plural .View.LifetimeHours "час" "часа" "часов"}}.
|
||||
|
||||
Если вы не регистрировались в Lincodex, ничего не делайте: без подтверждения аккаунт не будет активирован.
|
||||
|
||||
--
|
||||
Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
Subject: Подтвердите почту в Lincodex
|
||||
|
||||
Подтвердите адрес почты
|
||||
|
||||
Чтобы завершить регистрацию в Lincodex, откройте ссылку и подтвердите адрес на открывшейся странице:
|
||||
|
||||
https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv
|
||||
|
||||
Ссылка действует 24 часа.
|
||||
|
||||
Если вы не регистрировались в Lincodex, просто не открывайте ссылку: без подтверждения аккаунт не будет активирован.
|
||||
|
||||
--
|
||||
Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.
|
||||
+6
-2
@@ -11,12 +11,16 @@
|
||||
<div style="background-color:#ffffff;border-top:4px solid #402fff;border-radius:8px;padding:28px 24px;">
|
||||
<p style="margin:0 0 24px;font-size:18px;font-weight:bold;letter-spacing:0.02em;color:#1b1c21;">Lincodex</p>
|
||||
<h1 style="margin:0 0 16px;font-size:22px;line-height:1.3;color:#1b1c21;">Подтвердите адрес почты</h1>
|
||||
<p style="margin:0 0 24px;">Чтобы завершить регистрацию в Lincodex, откройте ссылку и подтвердите адрес на открывшейся странице.</p>
|
||||
<p style="margin:0 0 16px;">Чтобы завершить регистрацию в Lincodex, введите код на странице подтверждения вместе с паролем, который вы выбрали при регистрации.</p>
|
||||
<p style="margin:0 0 8px;font-size:14px;">Код подтверждения:</p>
|
||||
<p style="margin:0 0 8px;padding:16px;border-radius:6px;background-color:#f3f2ff;color:#1b1c21;font-family:'Courier New',Courier,monospace;font-size:32px;font-weight:bold;letter-spacing:0.3em;text-align:center;">482915</p>
|
||||
<p style="margin:0 0 24px;font-size:14px;">Код действует 30 минут.</p>
|
||||
<p style="margin:0 0 8px;font-size:14px;">Или откройте ссылку и подтвердите адрес на открывшейся странице:</p>
|
||||
<p style="margin:0 0 24px;"><a href="https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv" style="display:inline-block;padding:12px 24px;border-radius:6px;background-color:#402fff;color:#ffffff;font-weight:bold;text-decoration:none;">Подтвердить почту</a></p>
|
||||
<p style="margin:0 0 8px;font-size:14px;">Если кнопка не работает, скопируйте ссылку в адресную строку браузера:</p>
|
||||
<p style="margin:0 0 24px;font-size:14px;word-break:break-all;"><a href="https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv" style="color:#402fff;">https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv</a></p>
|
||||
<p style="margin:0 0 16px;">Ссылка действует 24 часа.</p>
|
||||
<p style="margin:0;">Если вы не регистрировались в Lincodex, просто не открывайте ссылку: без подтверждения аккаунт не будет активирован.</p>
|
||||
<p style="margin:0;">Если вы не регистрировались в Lincodex, ничего не делайте: без подтверждения аккаунт не будет активирован.</p>
|
||||
</div>
|
||||
<p style="margin:16px 12px 0;font-size:13px;color:#2d2e37;">Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.</p>
|
||||
</div>
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
Subject: Подтвердите почту в Lincodex
|
||||
|
||||
Подтвердите адрес почты
|
||||
|
||||
Чтобы завершить регистрацию в Lincodex, введите код на странице подтверждения вместе с паролем, который вы выбрали при регистрации:
|
||||
|
||||
Код подтверждения: 482915
|
||||
|
||||
Код действует 30 минут.
|
||||
|
||||
Или откройте ссылку и подтвердите адрес на открывшейся странице:
|
||||
|
||||
https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv
|
||||
|
||||
Ссылка действует 24 часа.
|
||||
|
||||
Если вы не регистрировались в Lincodex, ничего не делайте: без подтверждения аккаунт не будет активирован.
|
||||
|
||||
--
|
||||
Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.
|
||||
Reference in new issue
Block a user