feat(auth): add password reset #178
This commit was merged in pull request #180.
This commit is contained in:
@@ -34,12 +34,15 @@ func getHandler(db *sql.DB) http.Handler {
|
|||||||
router.Handle("/auth/delete-account", service.HandleDeleteAccountPage(db))
|
router.Handle("/auth/delete-account", service.HandleDeleteAccountPage(db))
|
||||||
router.Handle("/auth/verify-email", service.HandleSignUpVerifyResponsePage(db)) // The link contained in the email
|
router.Handle("/auth/verify-email", service.HandleSignUpVerifyResponsePage(db)) // The link contained in the email
|
||||||
router.Handle("/auth/change-password", service.HandleChangePasswordPage(db))
|
router.Handle("/auth/change-password", service.HandleChangePasswordPage(db))
|
||||||
|
router.Handle("/auth/reset-password", service.HandleResetPasswordPage(db))
|
||||||
router.Handle("/api/auth/signup", service.HandleSignUpComp(db))
|
router.Handle("/api/auth/signup", service.HandleSignUpComp(db))
|
||||||
router.Handle("/api/auth/signin", service.HandleSignInComp(db))
|
router.Handle("/api/auth/signin", service.HandleSignInComp(db))
|
||||||
router.Handle("/api/auth/signout", service.HandleSignOutComp(db))
|
router.Handle("/api/auth/signout", service.HandleSignOutComp(db))
|
||||||
router.Handle("/api/auth/delete-account", service.HandleDeleteAccountComp(db))
|
router.Handle("/api/auth/delete-account", service.HandleDeleteAccountComp(db))
|
||||||
router.Handle("/api/auth/verify-resend", service.HandleVerifyResendComp(db))
|
router.Handle("/api/auth/verify-resend", service.HandleVerifyResendComp(db))
|
||||||
router.Handle("/api/auth/change-password", service.HandleChangePasswordComp(db))
|
router.Handle("/api/auth/change-password", service.HandleChangePasswordComp(db))
|
||||||
|
router.Handle("/api/auth/reset-password", service.HandleResetPasswordComp(db))
|
||||||
|
router.Handle("/api/auth/reset-password-actual", service.HandleActualResetPasswordComp(db))
|
||||||
|
|
||||||
return middleware.Logging(middleware.EnableCors(router))
|
return middleware.Logging(middleware.EnableCors(router))
|
||||||
}
|
}
|
||||||
|
|||||||
139
service/auth.go
139
service/auth.go
@@ -7,8 +7,10 @@ import (
|
|||||||
"database/sql"
|
"database/sql"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"errors"
|
"errors"
|
||||||
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/mail"
|
"net/mail"
|
||||||
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -149,12 +151,32 @@ func HandleSignUpVerifyResponsePage(db *sql.DB) http.HandlerFunc {
|
|||||||
func HandleChangePasswordPage(db *sql.DB) http.HandlerFunc {
|
func HandleChangePasswordPage(db *sql.DB) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
|
isPasswordReset := r.URL.Query().Has("token")
|
||||||
|
|
||||||
user := utils.GetUserFromSession(db, r)
|
user := utils.GetUserFromSession(db, r)
|
||||||
if user == nil {
|
if user == nil && !isPasswordReset {
|
||||||
utils.DoRedirect(w, r, "/auth/signin")
|
utils.DoRedirect(w, r, "/auth/signin")
|
||||||
} else {
|
} else {
|
||||||
userComp := UserInfoComp(user)
|
userComp := UserInfoComp(user)
|
||||||
comp := auth.ChangePasswordComp()
|
comp := auth.ChangePasswordComp(isPasswordReset)
|
||||||
|
err := template.Layout(comp, userComp).Render(r.Context(), w)
|
||||||
|
if err != nil {
|
||||||
|
utils.LogError("Failed to render change password page", err)
|
||||||
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func HandleResetPasswordPage(db *sql.DB) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
|
user := utils.GetUserFromSession(db, r)
|
||||||
|
if user != nil {
|
||||||
|
utils.DoRedirect(w, r, "/auth/signin")
|
||||||
|
} else {
|
||||||
|
userComp := UserInfoComp(nil)
|
||||||
|
comp := auth.ResetPasswordComp()
|
||||||
err := template.Layout(comp, userComp).Render(r.Context(), w)
|
err := template.Layout(comp, userComp).Render(r.Context(), w)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
utils.LogError("Failed to render change password page", err)
|
utils.LogError("Failed to render change password page", err)
|
||||||
@@ -402,6 +424,7 @@ func HandleVerifyResendComp(db *sql.DB) http.HandlerFunc {
|
|||||||
|
|
||||||
func HandleChangePasswordComp(db *sql.DB) http.HandlerFunc {
|
func HandleChangePasswordComp(db *sql.DB) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
user := utils.GetUserFromSession(db, r)
|
user := utils.GetUserFromSession(db, r)
|
||||||
if user == nil {
|
if user == nil {
|
||||||
utils.DoRedirect(w, r, "/auth/signin")
|
utils.DoRedirect(w, r, "/auth/signin")
|
||||||
@@ -453,6 +476,118 @@ func HandleChangePasswordComp(db *sql.DB) http.HandlerFunc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func HandleActualResetPasswordComp(db *sql.DB) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
|
pageUrl, err := url.Parse(r.Header.Get("HX-Current-URL"))
|
||||||
|
if err != nil {
|
||||||
|
utils.LogError("Could not get current URL", err)
|
||||||
|
utils.TriggerToast(w, r, "error", "Internal Server Error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
token := pageUrl.Query().Get("token")
|
||||||
|
if token == "" {
|
||||||
|
utils.TriggerToast(w, r, "error", "No token")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
newPass := r.FormValue("new-password")
|
||||||
|
|
||||||
|
err = checkPassword(newPass)
|
||||||
|
if err != nil {
|
||||||
|
utils.TriggerToast(w, r, "error", err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
userId uuid.UUID
|
||||||
|
salt []byte
|
||||||
|
)
|
||||||
|
|
||||||
|
err = db.QueryRow(`
|
||||||
|
SELECT u.user_uuid, salt
|
||||||
|
FROM user_token t
|
||||||
|
INNER JOIN user u ON t.user_uuid = u.user_uuid
|
||||||
|
WHERE t.token = ?
|
||||||
|
AND t.type = 'password_reset'
|
||||||
|
AND t.expires_at > datetime()
|
||||||
|
`, token).Scan(&userId, &salt)
|
||||||
|
if err != nil {
|
||||||
|
slog.Warn("Could not get user from token: " + err.Error())
|
||||||
|
utils.TriggerToast(w, r, "error", "Invalid token")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err = db.Exec("DELETE FROM user_token WHERE token = ? AND type = 'password_reset'", token)
|
||||||
|
if err != nil {
|
||||||
|
utils.LogError("Could not delete token", err)
|
||||||
|
utils.TriggerToast(w, r, "error", "Internal Server Error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
passHash := getHashPassword(newPass, salt)
|
||||||
|
|
||||||
|
_, err = db.Exec("UPDATE user SET password = ? WHERE user_uuid = ?", passHash, userId)
|
||||||
|
if err != nil {
|
||||||
|
utils.LogError("Could not update password", err)
|
||||||
|
utils.TriggerToast(w, r, "error", "Internal Server Error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
utils.TriggerToast(w, r, "success", "Password changed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func HandleResetPasswordComp(db *sql.DB) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
|
email := r.FormValue("email")
|
||||||
|
if email == "" {
|
||||||
|
utils.TriggerToast(w, r, "error", "Please enter an email")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var b []byte = make([]byte, 32)
|
||||||
|
_, err := rand.Reader.Read(b)
|
||||||
|
if err != nil {
|
||||||
|
utils.LogError("Could not generate token", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
token := base64.StdEncoding.EncodeToString(b)
|
||||||
|
|
||||||
|
res, err := db.Exec(`
|
||||||
|
INSERT INTO user_token (user_uuid, type, token, created_at, expires_at)
|
||||||
|
SELECT user_uuid, 'password_reset', ?, datetime(), datetime('now', '+15 minute')
|
||||||
|
FROM user
|
||||||
|
WHERE email = ?
|
||||||
|
`, token, email)
|
||||||
|
if err != nil {
|
||||||
|
utils.LogError("Could not insert token", err)
|
||||||
|
utils.TriggerToast(w, r, "error", "Internal Server Error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
i, err := res.RowsAffected()
|
||||||
|
if err != nil {
|
||||||
|
utils.LogError("Could not get rows affected", err)
|
||||||
|
utils.TriggerToast(w, r, "error", "Internal Server Error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if i != 0 {
|
||||||
|
var mail strings.Builder
|
||||||
|
err = tempMail.ResetPassword(token).Render(context.Background(), &mail)
|
||||||
|
if err != nil {
|
||||||
|
utils.LogError("Could not render reset password email", err)
|
||||||
|
utils.TriggerToast(w, r, "error", "Internal Server Error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
utils.SendMail(email, "Reset Password", mail.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
utils.TriggerToast(w, r, "info", "If the email exists, an email has been sent")
|
||||||
|
}
|
||||||
|
}
|
||||||
func sendVerificationEmail(db *sql.DB, userId string, email string) {
|
func sendVerificationEmail(db *sql.DB, userId string, email string) {
|
||||||
|
|
||||||
var token string
|
var token string
|
||||||
|
|||||||
@@ -1,17 +1,23 @@
|
|||||||
package auth
|
package auth
|
||||||
|
|
||||||
templ ChangePasswordComp() {
|
templ ChangePasswordComp(isPasswordReset bool) {
|
||||||
<form
|
<form
|
||||||
class="max-w-xl px-2 mx-auto flex flex-col gap-4 h-full justify-center"
|
class="max-w-xl px-2 mx-auto flex flex-col gap-4 h-full justify-center"
|
||||||
hx-post="/api/auth/change-password"
|
if isPasswordReset {
|
||||||
|
hx-post="/api/auth/reset-password-actual"
|
||||||
|
} else {
|
||||||
|
hx-post="/api/auth/change-password"
|
||||||
|
}
|
||||||
hx-swap="none"
|
hx-swap="none"
|
||||||
>
|
>
|
||||||
<h2 class="text-6xl mb-10">
|
<h2 class="text-6xl mb-10">
|
||||||
Change Password
|
Change Password
|
||||||
</h2>
|
</h2>
|
||||||
<label class="input input-bordered flex items-center gap-2">
|
if !isPasswordReset {
|
||||||
<input type="password" class="grow" placeholder="Current Password" name="current-password"/>
|
<label class="input input-bordered flex items-center gap-2">
|
||||||
</label>
|
<input type="password" class="grow" placeholder="Current Password" name="current-password"/>
|
||||||
|
</label>
|
||||||
|
}
|
||||||
<label class="input input-bordered flex items-center gap-2">
|
<label class="input input-bordered flex items-center gap-2">
|
||||||
<input type="password" class="grow" placeholder="New Password" name="new-password"/>
|
<input type="password" class="grow" placeholder="New Password" name="new-password"/>
|
||||||
</label>
|
</label>
|
||||||
|
|||||||
19
template/auth/reset_password.templ
Normal file
19
template/auth/reset_password.templ
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
templ ResetPasswordComp() {
|
||||||
|
<form
|
||||||
|
class="max-w-xl px-2 mx-auto flex flex-col gap-4 h-full justify-center"
|
||||||
|
hx-post="/api/auth/reset-password"
|
||||||
|
hx-swap="none"
|
||||||
|
>
|
||||||
|
<h2 class="text-6xl mb-10">
|
||||||
|
Reset Password
|
||||||
|
</h2>
|
||||||
|
<label class="input input-bordered flex items-center gap-2">
|
||||||
|
<input type="email" class="grow" placeholder="E-Mail" name="email"/>
|
||||||
|
</label>
|
||||||
|
<button class="btn btn-primary self-end">
|
||||||
|
Request Password Reset
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
}
|
||||||
@@ -50,8 +50,9 @@ templ SignInOrUpComp(isSignIn bool) {
|
|||||||
</label>
|
</label>
|
||||||
<div class="flex justify-end items-center gap-2">
|
<div class="flex justify-end items-center gap-2">
|
||||||
if isSignIn {
|
if isSignIn {
|
||||||
|
<a href="/auth/reset-password" class="grow link text-gray-500 text-sm">Forgot Password?</a>
|
||||||
<a href="/auth/signup" class="link text-gray-500 text-sm">Don't have an account? Sign Up</a>
|
<a href="/auth/signup" class="link text-gray-500 text-sm">Don't have an account? Sign Up</a>
|
||||||
<button class="btn btn-primary self-end">
|
<button class="btn btn-primary">
|
||||||
Sign In
|
Sign In
|
||||||
</button>
|
</button>
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import (
|
|||||||
"net/url"
|
"net/url"
|
||||||
)
|
)
|
||||||
|
|
||||||
templ Register(mailCode string) {
|
templ Register(token string) {
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
@@ -15,7 +15,7 @@ templ Register(mailCode string) {
|
|||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<h4>Thank you for Sign Up!</h4>
|
<h4>Thank you for Sign Up!</h4>
|
||||||
<p>Click <a href={ templ.URL(utils.BaseUrl + "/auth/verify-email?token=" + url.QueryEscape(mailCode)) }>here</a> to verify your account.</p>
|
<p>Click <a href={ templ.URL(utils.BaseUrl + "/auth/verify-email?token=" + url.QueryEscape(token)) }>here</a> to verify your account.</p>
|
||||||
<p>Kind regards</p>
|
<p>Kind regards</p>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
22
template/mail/reset-password.templ
Normal file
22
template/mail/reset-password.templ
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
package mail;
|
||||||
|
|
||||||
|
import (
|
||||||
|
"me-fit/utils"
|
||||||
|
"net/url"
|
||||||
|
)
|
||||||
|
|
||||||
|
templ ResetPassword(token string) {
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8"/>
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
|
||||||
|
<title>Reset Password</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<h4>Reset your password</h4>
|
||||||
|
<p>Click <a href={ templ.URL(utils.BaseUrl + "/auth/change-password?token=" + url.QueryEscape(token)) }>here</a> to change your password.</p>
|
||||||
|
<p>Kind regards</p>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user