# Resetting Passwords

- [Introduction](#introduction)
- [Preparing your application](#preparing-your-application)
- [Routing](#routing)
- [Sending reset links](#sending-reset-links)
- [Resetting the password](#resetting-the-password)
    - [Logging the user in after a reset](#logging-the-user-in-after-a-reset)
    - [Checking a link before showing the form](#checking-a-link-before-showing-the-form)
- [Customizing the reset email](#customizing-the-reset-email)
- [Testing](#testing)

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

## Introduction


Laravel はリセットトークンの生成と検証、リンクのメール送信、ハッシュ済みパスワードの更新を提供し、ルートとフォームはアプリケーション側で管理できます。


始める前に、ユーザーがログインできるよう [authentication](/ja/go/docs/authentication) を設定してください。

<a name="preparing-your-application"></a>

## Preparing your application


Laravel は [mailer](/ja/go/docs/mail) を通じて、`User` モデルの `MailAddress` が返すアドレスへリセットメールを送ります。メールガイドの [recipients](/ja/go/docs/mail#recipients) に従い、`models/user.go` の `User` モデルへこのメソッドを追加します。

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


レスポンスがメールプロバイダを待たずに済むよう、リセットメールは [queued](/ja/go/docs/mail#queueing-mail) として処理されます。そのため、配送には [queue worker](/ja/go/docs/queues#running-the-worker) が動作している必要があります。


Laravel は既定の [cache](/ja/go/docs/cache) ストアにリセットトークンを保存します。複数のサーバーで運用する場合は、`memory` ではなく `database` や `redis` など、すべてのサーバーが共有するストアを使用してください。


リセットリンクはリクエストのホストで始まります。本番環境では、Laravel は `APP_URL` のホストとそのサブドメインへのリクエストにのみ応答するため、偽造した `Host` ヘッダーで別のサイトへのリンクを作ることはできません。ほかのドメインも提供する場合は、[trusted hosts](/ja/go/docs/middleware#trusting-hosts) に追加してください。

<a name="routing"></a>

## Routing


リセットには四つのルートが必要です。パスワードを忘れた場合のフォーム表示とリンク送信、リセットフォーム表示と新しいパスワードの保存です。独自の `passwords` パッケージのハンドラーを参照するよう `routes/web.go` に追加し、ログイン済みユーザーをホームへ送る `RedirectIfAuthenticated` を適用します。


メール内のリンクが [point to it](/ja/go/docs/authentication#naming-pages) の規則で参照するため、フォームのルート名を `password.reset` にします。リンクは `{token}` パラメータにリセットトークンを持つため、`password.reset` ルートにこれがないとアプリケーションは起動を拒否します。

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

	"app/handlers/passwords"
)

route.Middleware(auth.RedirectIfAuthenticated{}).Group(func(route *routing.Router) {
	route.Get("/forgot-password", passwords.ShowForgotPassword)
	route.Post("/forgot-password", passwords.SendResetLink)
	route.Get("/reset-password/{token}", passwords.ShowResetPassword).Name("password.reset")
	route.Post("/reset-password", passwords.ResetPassword)
})
```

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

## Sending reset links


パスワードを忘れた場合のページには `email` フィールドを持つフォームを表示します。送信されたメールアドレスを検証して `auth.SendResetLink` に渡すと、リセットページへのリンクをメールで送ります。

```go
package passwords

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

	"app/models"
)

type ForgotPassword struct {
	Email string `json:"email"`
}

func (f *ForgotPassword) Rules() validation.Rules {
	return validation.For(f, rule.Field(&f.Email, rule.Required, rule.Email))
}

func ShowForgotPassword(r *web.Request) *web.Response {
	return inertia.Render("auth/ForgotPassword")
}

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

	if err := auth.SendResetLink[models.User](r, form.Email); err != nil {
		return web.Fail(err)
	}

	inertia.Flash(r, "status", "If that email has an account, we've sent it a reset link.")

	return web.Back()
}
```


ハンドラーはリダイレクト前に `inertia.Flash` で状態を一時保存するため、ページは `flash` フィールドでメッセージを受け取ります。詳しくは Inertia ガイドの [flash data](/ja/go/docs/inertia#flash-data) を参照してください。


メールアドレスに一致するユーザーがなければ、`SendResetLink` は何も送らず `nil` を返すため、レスポンスからアカウントの有無は分かりません。どちらの場合も同じメッセージを返してください。60 秒以内の再要求では `SendResetLink` は送信を省略し、それ以降の新しいリンクは前のリンクを置き換えます。

<a name="resetting-the-password"></a>

## Resetting the password


メール内のリンクは `password.reset` ルートを開きます。`https://acme.test/reset-password/4Fq…?email=taylor%40laravel.com` のように、トークンは `{token}` ルートパラメータ、メールアドレスはクエリ文字列で渡されます。


リセットページには、メールアドレス、新しいパスワードと確認欄、非表示フィールドのトークンを持つフォームを表示します。送信時に値を `auth.ResetPassword` へ渡します。

```go
package passwords

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

	"app/models"
)

type NewPassword struct {
	Token    string `json:"token"`
	Email    string `json:"email"`
	Password string `json:"password"`
}

func (f *NewPassword) Rules() validation.Rules {
	return validation.For(f,
		rule.Field(&f.Token, rule.Required),
		rule.Field(&f.Email, rule.Required, rule.Email),
		rule.Field(&f.Password, rule.Required, rule.Min(8), hash.Password, rule.Confirmed),
	)
}

func ShowResetPassword(r *web.Request) *web.Response {
	return inertia.Render("auth/ResetPassword", inertia.Props{
		"token": r.PathValue("token"),
		"email": r.URL.Query().Get("email"),
	})
}

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

	if _, err := auth.ResetPassword[models.User](r, form.Email, form.Token, form.Password); err != nil {
		return web.Fail(err)
	}

	inertia.Flash(r, "status", "Your password has been reset.")

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


パスワードマネージャーがそのアカウントの新しいパスワードを保存できるように、メールアドレスのフィールドを読み取り専用にして `autocomplete="username"` を指定してください。


`ResetPassword` はトークンを検証し、新しいパスワードを保存してユーザーを返します。トークンは一回限りで 60 分間有効です。無効または期限切れなら、`ResetPassword` は `email` フィールドに "This password reset token is invalid." のバリデーションエラーを返すため、そのフィールドのエラーを表示してください。[changing a password](/ja/go/docs/authentication#changing-a-password) と同じく、リセットするとすべての端末からログアウトします。

<a name="logging-the-user-in-after-a-reset"></a>

### Logging the user in after a reset


`ResetPassword` はログイン処理をしません。ログインページへ送らずログインさせるには、`ResetPassword` が返すユーザーを `auth.Login` に渡します。

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

	user, err := auth.ResetPassword[models.User](r, form.Email, form.Token, form.Password)
	if err != nil {
		return web.Fail(err)
	}

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

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

<a name="checking-a-link-before-showing-the-form"></a>

### Checking a link before showing the form


期限切れや使用済みのリンクを開く場合があります。入力前に知らせるには、ページのハンドラーで `auth.ValidateResetToken` を呼び出します。トークンを消費せず、一致するユーザーまたは `nil` を返します。

```go
func ShowResetPassword(r *web.Request) *web.Response {
	token, email := r.PathValue("token"), r.URL.Query().Get("email")

	user, err := auth.ValidateResetToken[models.User](r, email, token)
	if err != nil {
		return web.Fail(err)
	}
	if user == nil {
		return inertia.Render("auth/ResetLinkExpired")
	}

	return inertia.Render("auth/ResetPassword", inertia.Props{"token": token, "email": email})
}
```

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

## Customizing the reset email


デフォルトでは、Laravel は件名 "Reset your password" と [mail layout](/ja/go/docs/mail#customizing-the-layout) を使う組み込みの `auth.ResetPasswordEmail` Mailable でリンクを送ります。


独自の Mailable を書かずに文面を変更するには、`auth` 名前空間とビュー名を指定して `vendor:publish` を実行します。

```shell
laravel vendor:publish auth reset-password
```


コマンドはビューを `resources/views/vendor/auth/reset-password.html` へコピーします。ブランドに合わせて編集すると、リセットメールはそのビューでレンダリングされます。ビューにはリンクの `.URL` と有効期間の `.Minutes` が渡されます。


件名の変更や、名前で挨拶する `mails.ResetPassword` など独自の [mailable](/ja/go/docs/mail#writing-mailables) を送るには、`SendResetLink` の代わりに `auth.SendResetLinkWith` を呼びます。トークンを生成してユーザーとリンクを関数に渡すため、メールをキューに入れられます。`SendResetLink` と同様、直近 1 分間にリンクを要求していないユーザーのメールである場合だけ関数を呼び出します。

```go
err := auth.SendResetLinkWith(
	r,
	form.Email,
	func(ctx context.Context, user *models.User, link string) error {
		return mail.To(user).Queue(ctx, mails.ResetPassword{Name: user.Name, Link: link})
	},
)
```


リセットリンクはパスワードを変更できるため、ログや暗号化されていないストレージに残さないでください。通常の [queued job](/ja/go/docs/queues) に入れず、キューのメールを暗号化する `mail.To(..).Queue(..)` を使います。

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

## Testing


リセットをテストするには [mail fake](/ja/go/docs/mail#testing) を設定し、キューに入った `auth.ResetPasswordEmail` のリンクからトークンを読み取り、フォームへ送信します。

```go
package feature_test

import (
	"net/url"
	"strings"
	"testing"

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

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

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

	client.Post("/forgot-password", url.Values{"email": {user.Email}}).AssertRedirect("/")

	sent := emails.Queued[auth.ResetPasswordEmail]()
	link, _ := url.Parse(sent[0].Mailable.URL)
	token := strings.TrimPrefix(link.Path, "/reset-password/")

	client.Post("/reset-password", url.Values{
		"token":                 {token},
		"email":                 {user.Email},
		"password":              {"new-password"},
		"password_confirmation": {"new-password"},
	}).AssertRedirect("/login")
}
```