全棧身份認證實作:使用 Next.js、NextAuth.js 和 MongoDB-13. 密碼變更

Claire Wei
ClaireWei
Published in
Dec 13, 2023

實現用戶的密碼更改功能,包括創建界面和處理密碼更新請求。

13–1. 建立變更密碼頁面

  • 在 lib/validations/auth.ts 中新增 changePasswordValidation 來確保密碼的有效性。
  • 於 components/form 資料夾建立 ChangePasswordForm 組件(change-password-form.tsx)。
  • app/(auth) 資料夾中建立 change-password 資料夾,存放對應頁面 (page.tsx),import ChangePasswordForm。
  • 在 update-form.tsx 中添加到 change-password 頁面的鏈接,僅當用戶的登入方式為 credentials 時顯示此鏈接。

13–2. 設定用戶變更密碼功能

  • 在 auth.actions.ts 中新增 changeUserPassword 以處理密碼變更請求,使用 bcrypt 驗證舊密碼並加密新密碼。
  • change-password-form.tsx 修改 onSubmit function,使用 changeUserPassword 處理密碼變更,在變更成功後顯示通知,並執行登出及導向登入頁面。

程式碼

變更密碼頁面 及 輸入內容驗證

單元重點:

  • (auth) 資料夾中,建立 change-password 路徑內容,並且將當中會使用到 “use client” 的表單獨立成 ChangePasswordForm 組件。
  • 新增 server actions:changeUserPassword。

回到目錄
https://medium.com/p/3d2a3ec1d3b6

--

--