# Email Verification

- [Introduction](#introduction)
- [Setting up verification](#setting-up-verification)
- [Sending verification links](#sending-verification-links)
- [Verifying the email](#verifying-the-email)
- [Requiring a verified email](#requiring-a-verified-email)
- [Changing a user's email](#changing-the-email)
- [Customizing the verification email](#customizing-the-verification-email)
- [Testing](#testing)

<a name="introduction"></a>

## Introduction


많은 웹 애플리케이션은 사용자가 민감한 기능을 사용하거나 거래 관련 메일을 받기 전에 이메일 주소를 확인하도록 요구합니다. 예를 들어 상점에서는 새 사용자가 바로 상품을 둘러보게 하되, 주소를 인증한 뒤에만 결제하도록 할 수 있습니다. Laravel은 사용자에게 서명된 인증 링크를 이메일로 보내고, 사용자가 열면 링크를 확인하며, 선택한 라우트에 미인증 사용자가 접근하지 못하게 할 수 있습니다. 라우트와 페이지는 애플리케이션에서 계속 관리합니다.


시작하기 전에 사용자가 로그인할 수 있도록 [authentication](/go/docs/authentication)을 설정하세요.

<a name="setting-up-verification"></a>

## Setting up verification


Laravel은 `User` 모델의 `Email` 필드에서 사용자 주소를, `EmailVerifiedAt` 필드에서 인증 시간을 읽습니다. 사용자가 인증하면 `email_verified_at` 컬럼을 설정합니다. 새 애플리케이션의 `models/user.go`에 있는 `User`에는 이미 두 필드가 있으며, `users` 마이그레이션은 null을 허용하는 `email_verified_at` 컬럼을 만듭니다.

```go
package models

import "time"

type User struct {
	ID              int64      `json:"id"`
	Email           string     `json:"email"`
	EmailVerifiedAt *time.Time `json:"email_verified_at"`
	// ...
}
```


Laravel은 [mail](/go/docs/mail) 시스템을 사용하여 `User` 모델의 `MailAddress` 메서드가 반환하는 주소로 인증 링크를 보냅니다. 메일 가이드의 [recipients](/go/docs/mail#recipients) 절에서 설명하는 대로 `models/user.go`의 `User` 모델에 이 메서드를 추가하세요.

```go
func (u User) MailAddress() mail.Address {
	return mail.Address{Name: u.Name, Email: u.Email}
}
```


이메일 인증에는 `routes/web.go`에서 `Authenticate`로 보호하는 라우트 세 개가 필요합니다. 받은편지함을 확인하도록 안내하는 페이지, 새 인증 이메일을 보내는 라우트, 사용자가 클릭한 링크를 처리하는 라우트입니다. 사용자가 받은편지함에 과도하게 메일을 보내거나 누군가 링크를 추측하지 못하도록 재전송과 인증 라우트의 요청 횟수를 제한하세요. 새 링크를 여섯 번 요청한 사용자도 최신 링크를 열 수 있도록 각 제한에 별도의 [bucket](/go/docs/rate-limiting#throttling-routes)을 지정하세요.

```go
import (
	"go.laravel.com/auth"
	"go.laravel.com/middleware"
	"go.laravel.com/routing"

	"app/handlers/verification"
)

route.Middleware(auth.Authenticate{}).Group(func(route *routing.Router) {
	route.Get("/email/verify", verification.Notice).Name("verification.notice")

	route.Post("/email/verification-notification", verification.Resend).
		Middleware(middleware.ThrottlePerMinute(6).WithBucket("verification-resend"))

	route.Get("/email/verify/{id}/{hash}", verification.Verify).Name("verification.verify").
		Middleware(middleware.ThrottlePerMinute(6).WithBucket("verification-verify"))
})
```


Laravel은 [names](/go/docs/authentication#naming-pages)로 안내 페이지와 인증 라우트를 찾으므로 이름을 `verification.notice`와 `verification.verify`로 지정하세요. 각 인증 링크에는 `{id}`와 `{hash}` 파라미터로 사용자 ID와 이메일 주소의 해시가 포함되므로 `verification.verify` 라우트에는 둘 다 필요합니다. 하나라도 없으면 애플리케이션이 시작을 거부하고 누락된 파라미터를 보고합니다.

<a name="sending-verification-links"></a>

## Sending verification links


사용자가 가입하면 새 사용자를 `auth.SendVerificationLink`에 전달하여 첫 링크를 즉시 보내세요. 다음 가입 핸들러는 사용자를 생성하고 로그인시킨 다음 링크를 보냅니다.

```go
package registrations

import (
	"go.laravel.com/auth"
	"go.laravel.com/hash"
	"go.laravel.com/model"
	"go.laravel.com/validation"
	"go.laravel.com/validation/rule"
	"go.laravel.com/web"

	"app/models"
)

type SignUp struct {
	Name     string `json:"name"`
	Email    string `json:"email" transform:"lowercase"`
	Password string `json:"password"`
}

func (f *SignUp) Rules() validation.Rules {
	return validation.For(f,
		rule.Field(&f.Name, rule.Required, rule.Max(255)),
		rule.Field(&f.Email, rule.Required, rule.Email, model.Unique[models.User]()),
		rule.Field(&f.Password, rule.Required, rule.Min(8), hash.Password, rule.Confirmed),
	)
}

func Store(r *web.Request) *web.Response {
	form, err := r.Validate[SignUp]()
	if err != nil {
		return web.Fail(err)
	}

	hashed, err := hash.Make(r, form.Password)
	if err != nil {
		return web.Fail(err)
	}

	user := models.User{Name: form.Name, Email: form.Email, Password: hashed}
	if err := model.Create(r, &user); err != nil {
		return web.Fail(err)
	}

	if err := auth.Login(r, &user, false); err != nil {
		return web.Fail(err)
	}

	if err := auth.SendVerificationLink(r, &user); err != nil {
		return web.Fail(err)
	}

	return web.RedirectRoute("dashboard")
}
```


`SendVerificationLink`는 60분 동안 유효한 서명된 링크를 담은 `auth.VerificationEmail`을 [queues](/go/docs/mail#queueing-mail)에 등록합니다. 따라서 요청은 메일 프로바이더를 기다리지 않으며 워커가 이메일을 보냅니다. 사용자의 이메일이 이미 인증되었다면 아무 작업도 하지 않습니다.


이메일은 유실될 수 있고 링크는 만료되므로 안내 페이지에 새 링크를 요청하는 폼을 두고 `Resend` 핸들러에 POST합니다. 두 핸들러 모두 다른 탭 등에서 이미 이메일을 인증한 사용자를 원래 가려던 페이지로 보냅니다.

```go
package verification

import (
	"go.laravel.com/auth"
	"go.laravel.com/inertia"
	"go.laravel.com/web"

	"app/models"
)

func Notice(r *web.Request) *web.Response {
	user := r.User[models.User]()
	if user.EmailVerifiedAt != nil {
		return auth.RedirectIntended("/dashboard")
	}

	return inertia.Render("auth/VerifyEmail", inertia.Props{"email": user.Email})
}

func Resend(r *web.Request) *web.Response {
	user := r.User[models.User]()
	if user.EmailVerifiedAt != nil {
		return auth.RedirectIntended("/dashboard")
	}

	if err := auth.SendVerificationLink(r, user); err != nil {
		return web.Fail(err)
	}

	inertia.Flash(r, "status", "We've sent you a new verification link.")

	return web.Back()
}
```


Inertia 페이지는 `flash` 필드로 플래시 메시지를 받으므로 `Resend`는 리다이렉트 전에 [`inertia.Flash`](/go/docs/inertia#flash-data)로 상태를 플래시합니다.

<a name="verifying-the-email"></a>

## Verifying the email


사용자가 링크를 열면 `verification.verify` 라우트의 핸들러가 실행됩니다. 여기서 `auth.VerifyEmail`을 호출하세요.

```go
func Verify(r *web.Request) *web.Response {
	if _, err := auth.VerifyEmail[models.User](r); err != nil {
		return web.Fail(err)
	}

	inertia.Flash(r, "status", "Your email is verified.")

	return auth.RedirectIntended("/dashboard")
}
```


`VerifyEmail`은 링크가 변경되거나 만료되지 않았고 Laravel이 로그인한 사용자의 현재 주소로 보낸 링크인지 확인합니다. 그런 다음 사용자의 `email_verified_at`을 현재 시각으로 설정하고 사용자를 반환합니다. 같은 링크를 두 번 열어도 같은 결과를 얻습니다.


`VerifyEmail`은 다음 세 가지 경우에 유효하지 않은 요청을 거부합니다.


- 게스트는 먼저 로그인 페이지로 이동하며, 로그인하면 [`RedirectIntended`](/go/docs/authentication#attempting-a-login)가 링크로 돌려보냅니다.
- 만료되었거나 누군가 변경한 링크에는 [`urls.ErrExpired` or `urls.ErrInvalidSignature`](/go/docs/urls#responding-to-invalid-signed-routes)를 감싼 `403`이 반환됩니다.
- Laravel이 다른 사용자 또는 사용자가 더 이상 사용하지 않는 주소로 보낸 링크에는 "This verification link is invalid."라는 메시지를 담은 `403`인 `auth.ErrInvalidVerificationLink`가 반환됩니다.


만료되거나 유효하지 않은 링크에 `403` 오류 페이지를 표시하는 대신 핸들러 안에서 `errors.Is`로 오류를 확인하고 상태 메시지와 함께 안내 페이지로 사용자를 돌려보낼 수 있습니다.

```go
import (
	"errors"

	"go.laravel.com/auth"
	"go.laravel.com/inertia"
	"go.laravel.com/urls"
	"go.laravel.com/web"

	"app/models"
)

func Verify(r *web.Request) *web.Response {
	_, err := auth.VerifyEmail[models.User](r)
	switch {
	case errors.Is(err, urls.ErrExpired), errors.Is(err, urls.ErrInvalidSignature),
		errors.Is(err, auth.ErrInvalidVerificationLink):
		inertia.Flash(
			r,
			"status",
			"That verification link has expired or is invalid. Please request a new one.",
		)

		return web.RedirectRoute("verification.notice")
	case err != nil:
		return web.Fail(err)
	}

	inertia.Flash(r, "status", "Your email is verified.")

	return auth.RedirectIntended("/dashboard")
}
```


[rendering errors yourself](/go/docs/errors#rendering-errors)를 통해 오류를 직접 렌더링하면 모든 라우트에서 이러한 오류를 처리할 수도 있습니다.

<a name="requiring-a-verified-email"></a>

## Requiring a verified email


결제 같은 일부 페이지는 사용자가 이메일을 인증한 뒤에 접근하도록 해야 합니다. `auth.RequireVerifiedEmail` 미들웨어는 인증을 마친 사용자만 통과시킵니다. 로그인한 사용자가 필요하므로 `Authenticate` 뒤에 배치하세요.

```go
route.Middleware(auth.Authenticate{}, auth.RequireVerifiedEmail{}).Group(func(route *routing.Router) {
	route.Get("/billing", billing.Show)
})
```


`RequireVerifiedEmail`은 미인증 사용자를 `verification.notice` 페이지로 리다이렉트합니다. 사용자가 링크를 열면 `Verify` 핸들러의 `RedirectIntended`가 처음 요청한 페이지로 돌려보냅니다. JSON을 기대하는 요청에는 대신 `403`이 반환됩니다.


코드에서 사용자가 이메일을 인증했는지 확인하려면 `EmailVerifiedAt` 필드를 확인하세요.

```go
if user.EmailVerifiedAt == nil {
	// ...
}
```

<a name="changing-the-email"></a>

## Changing a user's email


사용자가 이메일 주소를 변경할 때마다 같은 업데이트에서 `email_verified_at`을 비우고 새 주소로 새 인증 링크를 보내세요.

```go
package profile

import (
	"go.laravel.com/auth"
	"go.laravel.com/db"
	"go.laravel.com/model"
	"go.laravel.com/validation"
	"go.laravel.com/validation/rule"
	"go.laravel.com/web"

	"app/models"
)

type UpdateEmail struct {
	Email string `json:"email" transform:"lowercase"`
}

func (f *UpdateEmail) Rules(r *web.Request) (validation.Rules, error) {
	return validation.For(f,
		rule.Field(&f.Email,
			rule.Required,
			rule.Email,
			model.Unique[models.User]().Ignore(r.User[models.User]()),
		),
	), nil
}

func UpdateEmailAddress(r *web.Request) *web.Response {
	form, err := r.Validate[UpdateEmail]()
	if err != nil {
		return web.Fail(err)
	}

	user := r.User[models.User]()
	if err := model.Update(r, user, db.Values{
		"email":             form.Email,
		"email_verified_at": nil,
	}); err != nil {
		return web.Fail(err)
	}

	if err := auth.SendVerificationLink(r, user); err != nil {
		return web.Fail(err)
	}

	return web.Back()
}
```


`model.Update`는 사용자의 `Email`과 `EmailVerifiedAt` 필드도 설정하므로 `SendVerificationLink`는 미인증 사용자로 판단하고 새 주소로 링크를 보냅니다. 각 링크의 해시는 사용자의 현재 이메일 주소를 기준으로 하므로 이전 주소로 보낸 모든 링크는 즉시 작동하지 않게 됩니다.

<a name="customizing-the-verification-email"></a>

## Customizing the verification email


Laravel은 기본적으로 `auth.VerificationEmail` 메일러블로 인증 링크를 보냅니다. 제목은 "Verify your email address"이며 Laravel의 [mail components](/go/docs/mail#mail-components)로 렌더링합니다.


별도의 메일러블을 작성하지 않고 인증 후 사용할 수 있는 기능을 안내하는 문장처럼 이메일 문구를 변경하려면 `vendor:publish`로 Laravel의 `auth::verify-email` 뷰를 애플리케이션에 복사하세요.

```shell
laravel vendor:publish auth verify-email
```


명령어는 `resources/views/vendor/auth/verify-email.html`을 작성합니다. 브랜드에 맞게 이 파일을 수정하면 Laravel은 인증 이메일을 보낼 때마다 수정한 복사본을 렌더링합니다. 뷰는 서명된 링크를 `.URL`로, 링크의 유효 시간을 분 단위로 `.Minutes`로 받습니다.

```html
{{template "mail::layout" .}}

{{define "content"}}
<h1>Welcome to {{config.App.Name}}!</h1>
<p>Confirm your email address to start your free trial.</p>
{{template "mail::button" (dict "Label" "Confirm my email" "URL" .URL)}}
<p>This link expires in {{.Minutes}} minutes.</p>
{{end}}
```


제목이 다른 메일 등 직접 만든 [mailable](/go/docs/mail#writing-mailables)을 보내려면 `SendVerificationLink`를 호출하던 곳에서 `auth.SendVerificationLinkWith`를 호출하세요. 사용자와 서명된 링크를 받는 함수를 인수로 받습니다. 다음 `VerifyYourEmail` 메일러블은 사용자 이름으로 인사하고 `resources/views/mails/verify-your-email.html`을 렌더링합니다.

```go
import (
	"context"

	"go.laravel.com/auth"
	"go.laravel.com/inertia"
	"go.laravel.com/mail"
	"go.laravel.com/web"

	"app/models"
)

type VerifyYourEmail struct {
	Name string
	URL  string
}

func (m VerifyYourEmail) Build() mail.Message {
	return mail.Message{
		Subject: "Confirm your email address",
		View:    "mails.verify-your-email",
		Data:    m,
	}
}

func Resend(r *web.Request) *web.Response {
	user := r.User[models.User]()
	if user.EmailVerifiedAt != nil {
		return auth.RedirectIntended("/dashboard")
	}

	err := auth.SendVerificationLinkWith(
		r,
		user,
		func(ctx context.Context, user *models.User, link string) error {
			return mail.To(user).Queue(ctx, VerifyYourEmail{Name: user.Name, URL: link})
		},
	)
	if err != nil {
		return web.Fail(err)
	}

	inertia.Flash(r, "status", "We've sent you a new verification link.")

	return web.Back()
}
```


`SendVerificationLink`와 마찬가지로 `SendVerificationLinkWith`는 아직 이메일을 인증하지 않은 사용자에 대해서만 함수를 호출합니다. 인증 여부와 관계없이 환영 이메일 같은 다른 메일에 링크를 넣으려면 링크를 반환하는 `auth.VerificationLink(r, user)`를 호출하세요.

<a name="testing"></a>

## Testing


이메일 인증을 테스트하려면 애플리케이션에 [mail fake](/go/docs/mail#testing)를 설정하고 큐에 등록된 `auth.VerificationEmail`에서 서명된 `URL`을 읽은 뒤 해당 사용자로 접속하세요.

```go
package feature_test

import (
	"net/url"
	"testing"

	"go.laravel.com/auth"
	"go.laravel.com/mailtest"

	"app/database/factories"
	"app/tests"
)

func TestUsersCanVerifyTheirEmail(t *testing.T) {
	client := tests.New(t)
	emails := mailtest.New(client)
	user := client.Create(factories.User.State(factories.Unverified))

	client.ActingAs(&user).Post("/email/verification-notification", nil)

	sent := emails.Queued[auth.VerificationEmail]()
	if len(sent) != 1 {
		t.Fatalf("queued %d verification emails, want one", len(sent))
	}
	link, _ := url.Parse(sent[0].Mailable.URL)

	client.ActingAs(&user).Get(link.RequestURI()).AssertRedirect("/dashboard")
}
```


새 애플리케이션의 `User` [factory](/go/docs/factories)는 이메일을 인증한 사용자를 생성합니다. 따라서 인증된 사용자는 `client.Create(factories.User)`로 만들고, 미인증 계정을 테스트할 때는 `factories.Unverified` 상태를 사용하세요.