67 lines
1.6 KiB
Go
67 lines
1.6 KiB
Go
package handler
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"net/http"
|
|
"time"
|
|
|
|
"git.haelnorr.com/h/golib/hws"
|
|
"git.haelnorr.com/h/golib/hwsauth"
|
|
"projectreshoot/internal/models"
|
|
"projectreshoot/internal/view/component/form"
|
|
|
|
"github.com/pkg/errors"
|
|
)
|
|
|
|
// Validate the provided password
|
|
func validatePassword(
|
|
auth *hwsauth.Authenticator[*models.User],
|
|
tx *sql.Tx,
|
|
r *http.Request,
|
|
) error {
|
|
r.ParseForm()
|
|
password := r.FormValue("password")
|
|
user := auth.CurrentModel(r.Context())
|
|
err := user.CheckPassword(tx, password)
|
|
if err != nil {
|
|
return errors.Wrap(err, "user.CheckPassword")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Handle request to reauthenticate (i.e. make token fresh again)
|
|
func Reauthenticate(
|
|
server *hws.Server,
|
|
auth *hwsauth.Authenticator[*models.User],
|
|
conn *sql.DB,
|
|
) http.Handler {
|
|
return http.HandlerFunc(
|
|
func(w http.ResponseWriter, r *http.Request) {
|
|
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
|
|
defer cancel()
|
|
|
|
// Start the transaction
|
|
tx, err := conn.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
server.ThrowError(w, r, hws.NewError(http.StatusInternalServerError, "Failed to start transaction", err))
|
|
return
|
|
}
|
|
defer tx.Rollback()
|
|
err = validatePassword(auth, tx, r)
|
|
if err != nil {
|
|
w.WriteHeader(445)
|
|
form.ConfirmPassword("Incorrect password").Render(r.Context(), w)
|
|
return
|
|
}
|
|
err = auth.RefreshAuthTokens(tx, w, r)
|
|
if err != nil {
|
|
server.ThrowError(w, r, hws.NewError(http.StatusInternalServerError, "Failed to refresh user tokens", err))
|
|
return
|
|
}
|
|
tx.Commit()
|
|
w.WriteHeader(http.StatusOK)
|
|
},
|
|
)
|
|
}
|