Add admin password change flow (closes #65)
All checks were successful
check / check (push) Successful in 5s
All checks were successful
check / check (push) Successful in 5s
This commit is contained in:
@@ -4,63 +4,202 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi"
|
||||
"sneak.berlin/go/webhooker/internal/database"
|
||||
)
|
||||
|
||||
// HandleProfile returns a handler for the user profile page
|
||||
func (h *Handlers) HandleProfile() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
// Get username from URL
|
||||
requestedUsername := chi.URLParam(r, "username")
|
||||
if requestedUsername == "" {
|
||||
http.NotFound(w, r)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Get session. RequireAuth middleware guarantees an
|
||||
// authenticated session before this handler runs, so we
|
||||
// only need to guard against an unexpected retrieval error.
|
||||
sess, err := h.session.Get(r)
|
||||
if err != nil {
|
||||
h.log.Error("failed to get session", "error", err)
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Get user info from session
|
||||
sessionUsername, ok := h.session.GetUsername(sess)
|
||||
sessionUserID, sessionUsername, ok :=
|
||||
h.profileOwnerOrDeny(w, r)
|
||||
if !ok {
|
||||
h.log.Error("authenticated session missing username")
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
sessionUserID, ok := h.session.GetUserID(sess)
|
||||
if !ok {
|
||||
h.log.Error("authenticated session missing user ID")
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// For now, only allow users to view their own profile
|
||||
if requestedUsername != sessionUsername {
|
||||
http.Error(w, "Forbidden", http.StatusForbidden)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Prepare data for template
|
||||
data := map[string]any{
|
||||
"User": &UserInfo{
|
||||
ID: sessionUserID,
|
||||
Username: sessionUsername,
|
||||
},
|
||||
}
|
||||
|
||||
// Render the profile page
|
||||
h.renderTemplate(w, r, "profile.html", data)
|
||||
h.renderProfile(w, r, sessionUserID, sessionUsername, "", "")
|
||||
}
|
||||
}
|
||||
|
||||
// HandlePasswordChange returns a handler that lets an authenticated
|
||||
// user change their own password. It is served by the CSRF- and
|
||||
// auth-protected POST /password route under /user/{username}.
|
||||
func (h *Handlers) HandlePasswordChange() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
sessionUserID, sessionUsername, ok :=
|
||||
h.profileOwnerOrDeny(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
// Limit request body to prevent memory exhaustion.
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 1<<maxBodyShift)
|
||||
|
||||
err := r.ParseForm()
|
||||
if err != nil {
|
||||
h.log.Error("failed to parse form", "error", err)
|
||||
http.Error(w, "Bad request", http.StatusBadRequest)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
successMessage, errorMessage, handled := h.applyPasswordChange(
|
||||
w,
|
||||
sessionUsername,
|
||||
r.FormValue("current_password"),
|
||||
r.FormValue("new_password"),
|
||||
r.FormValue("confirm_password"),
|
||||
)
|
||||
if !handled {
|
||||
return
|
||||
}
|
||||
|
||||
h.renderProfile(
|
||||
w, r, sessionUserID, sessionUsername,
|
||||
successMessage, errorMessage,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// applyPasswordChange verifies the current password and, on success,
|
||||
// persists a fresh hash for the user, reusing the same helpers that
|
||||
// bootstrap the admin user. It returns the success and error messages
|
||||
// to display on the profile page. On an internal failure it writes a
|
||||
// 500 response itself and returns handled=false, signalling the caller
|
||||
// to stop without re-rendering the page.
|
||||
func (h *Handlers) applyPasswordChange(
|
||||
w http.ResponseWriter,
|
||||
username, currentPassword, newPassword, confirmPassword string,
|
||||
) (string, string, bool) {
|
||||
// Load the user row so we can verify the current password and
|
||||
// persist the new hash.
|
||||
var user database.User
|
||||
|
||||
err := h.db.DB().Where(
|
||||
"username = ?", username,
|
||||
).First(&user).Error
|
||||
if err != nil {
|
||||
h.serverError(
|
||||
w, "failed to load user for password change", err,
|
||||
)
|
||||
|
||||
return "", "", false
|
||||
}
|
||||
|
||||
valid, err := database.VerifyPassword(
|
||||
currentPassword, user.Password,
|
||||
)
|
||||
if err != nil {
|
||||
h.serverError(w, "failed to verify password", err)
|
||||
|
||||
return "", "", false
|
||||
}
|
||||
|
||||
if !valid {
|
||||
return "", "Current password is incorrect.", true
|
||||
}
|
||||
|
||||
if newPassword == "" {
|
||||
return "", "New password must not be empty.", true
|
||||
}
|
||||
|
||||
if newPassword != confirmPassword {
|
||||
return "", "New password and confirmation do not match.", true
|
||||
}
|
||||
|
||||
hashedPassword, err := database.HashPassword(newPassword)
|
||||
if err != nil {
|
||||
h.serverError(w, "failed to hash new password", err)
|
||||
|
||||
return "", "", false
|
||||
}
|
||||
|
||||
err = h.db.DB().Model(&user).Update(
|
||||
"password", hashedPassword,
|
||||
).Error
|
||||
if err != nil {
|
||||
h.serverError(w, "failed to update password", err)
|
||||
|
||||
return "", "", false
|
||||
}
|
||||
|
||||
h.log.Info("user changed password", "username", username)
|
||||
|
||||
return "Password changed successfully.", "", true
|
||||
}
|
||||
|
||||
// profileOwnerOrDeny resolves the session identity and enforces that a
|
||||
// user may only act on their own profile (the requested username in the
|
||||
// URL must equal the session username). On any failure it writes the
|
||||
// appropriate HTTP response and returns ok=false; callers must stop
|
||||
// when ok is false.
|
||||
func (h *Handlers) profileOwnerOrDeny(
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
) (string, string, bool) {
|
||||
requestedUsername := chi.URLParam(r, "username")
|
||||
if requestedUsername == "" {
|
||||
http.NotFound(w, r)
|
||||
|
||||
return "", "", false
|
||||
}
|
||||
|
||||
// RequireAuth middleware guarantees an authenticated session
|
||||
// before this handler runs, so we only need to guard against an
|
||||
// unexpected retrieval error.
|
||||
sess, err := h.session.Get(r)
|
||||
if err != nil {
|
||||
h.serverError(w, "failed to get session", err)
|
||||
|
||||
return "", "", false
|
||||
}
|
||||
|
||||
sessionUsername, ok := h.session.GetUsername(sess)
|
||||
if !ok {
|
||||
h.log.Error("authenticated session missing username")
|
||||
http.Error(
|
||||
w, "Internal server error",
|
||||
http.StatusInternalServerError,
|
||||
)
|
||||
|
||||
return "", "", false
|
||||
}
|
||||
|
||||
sessionUserID, ok := h.session.GetUserID(sess)
|
||||
if !ok {
|
||||
h.log.Error("authenticated session missing user ID")
|
||||
http.Error(
|
||||
w, "Internal server error",
|
||||
http.StatusInternalServerError,
|
||||
)
|
||||
|
||||
return "", "", false
|
||||
}
|
||||
|
||||
// Only allow users to act on their own profile.
|
||||
if requestedUsername != sessionUsername {
|
||||
http.Error(w, "Forbidden", http.StatusForbidden)
|
||||
|
||||
return "", "", false
|
||||
}
|
||||
|
||||
return sessionUserID, sessionUsername, true
|
||||
}
|
||||
|
||||
// renderProfile renders the profile page for the given user,
|
||||
// optionally including a success or error message.
|
||||
func (h *Handlers) renderProfile(
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
userID, username, successMessage, errorMessage string,
|
||||
) {
|
||||
data := map[string]any{
|
||||
"User": &UserInfo{
|
||||
ID: userID,
|
||||
Username: username,
|
||||
},
|
||||
"SuccessMessage": successMessage,
|
||||
"ErrorMessage": errorMessage,
|
||||
}
|
||||
|
||||
h.renderTemplate(w, r, "profile.html", data)
|
||||
}
|
||||
|
||||
@@ -4,12 +4,15 @@ import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"sneak.berlin/go/webhooker/internal/config"
|
||||
"sneak.berlin/go/webhooker/internal/database"
|
||||
"sneak.berlin/go/webhooker/internal/handlers"
|
||||
"sneak.berlin/go/webhooker/internal/logger"
|
||||
"sneak.berlin/go/webhooker/internal/middleware"
|
||||
@@ -157,3 +160,134 @@ func TestUserRoute_Unauthenticated_RedirectedByMiddleware(t *testing.T) {
|
||||
assert.Equal(t, http.StatusSeeOther, w.Code)
|
||||
assert.Equal(t, "/pages/login", w.Header().Get("Location"))
|
||||
}
|
||||
|
||||
// passwordChangeRequest builds a POST request to the password-change
|
||||
// endpoint for the given username, attaching the supplied cookies, an
|
||||
// urlencoded form body, and the chi URL parameter the handler reads.
|
||||
func passwordChangeRequest(
|
||||
username string,
|
||||
cookies []*http.Cookie,
|
||||
form url.Values,
|
||||
) *http.Request {
|
||||
req := httptest.NewRequestWithContext(
|
||||
context.Background(),
|
||||
http.MethodPost,
|
||||
"/user/"+username+"/password",
|
||||
strings.NewReader(form.Encode()),
|
||||
)
|
||||
req.Header.Set(
|
||||
"Content-Type", "application/x-www-form-urlencoded",
|
||||
)
|
||||
|
||||
for _, c := range cookies {
|
||||
req.AddCookie(c)
|
||||
}
|
||||
|
||||
rctx := chi.NewRouteContext()
|
||||
rctx.URLParams.Add("username", username)
|
||||
|
||||
return req.WithContext(
|
||||
context.WithValue(req.Context(), chi.RouteCtxKey, rctx),
|
||||
)
|
||||
}
|
||||
|
||||
func TestHandlePasswordChange_Success(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var h *handlers.Handlers
|
||||
|
||||
var sess *session.Session
|
||||
|
||||
var db *database.Database
|
||||
|
||||
app := newTestApp(t, &h, &sess, &db)
|
||||
app.RequireStart()
|
||||
|
||||
t.Cleanup(app.RequireStop)
|
||||
|
||||
oldHash, err := database.HashPassword("oldpassword")
|
||||
require.NoError(t, err)
|
||||
|
||||
user := &database.User{Username: "pwuser", Password: oldHash}
|
||||
require.NoError(t, db.DB().Create(user).Error)
|
||||
|
||||
cookies := authenticatedCookies(t, sess, user.ID, "pwuser")
|
||||
|
||||
form := url.Values{}
|
||||
form.Set("current_password", "oldpassword")
|
||||
form.Set("new_password", "newpassword")
|
||||
form.Set("confirm_password", "newpassword")
|
||||
|
||||
req := passwordChangeRequest("pwuser", cookies, form)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.HandlePasswordChange().ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
assert.Contains(
|
||||
t, w.Body.String(), "Password changed successfully.",
|
||||
)
|
||||
|
||||
var updated database.User
|
||||
|
||||
require.NoError(t,
|
||||
db.DB().Where("username = ?", "pwuser").First(&updated).Error,
|
||||
)
|
||||
assert.NotEqual(t, oldHash, updated.Password)
|
||||
|
||||
valid, err := database.VerifyPassword(
|
||||
"newpassword", updated.Password,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, valid, "new password should verify against new hash")
|
||||
}
|
||||
|
||||
func TestHandlePasswordChange_WrongCurrentPassword(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var h *handlers.Handlers
|
||||
|
||||
var sess *session.Session
|
||||
|
||||
var db *database.Database
|
||||
|
||||
app := newTestApp(t, &h, &sess, &db)
|
||||
app.RequireStart()
|
||||
|
||||
t.Cleanup(app.RequireStop)
|
||||
|
||||
oldHash, err := database.HashPassword("oldpassword")
|
||||
require.NoError(t, err)
|
||||
|
||||
user := &database.User{Username: "pwuser2", Password: oldHash}
|
||||
require.NoError(t, db.DB().Create(user).Error)
|
||||
|
||||
cookies := authenticatedCookies(t, sess, user.ID, "pwuser2")
|
||||
|
||||
form := url.Values{}
|
||||
form.Set("current_password", "wrongpassword")
|
||||
form.Set("new_password", "newpassword")
|
||||
form.Set("confirm_password", "newpassword")
|
||||
|
||||
req := passwordChangeRequest("pwuser2", cookies, form)
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
h.HandlePasswordChange().ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
assert.Contains(
|
||||
t, w.Body.String(), "Current password is incorrect.",
|
||||
)
|
||||
|
||||
var unchanged database.User
|
||||
|
||||
require.NoError(t,
|
||||
db.DB().Where(
|
||||
"username = ?", "pwuser2",
|
||||
).First(&unchanged).Error,
|
||||
)
|
||||
assert.Equal(
|
||||
t, oldHash, unchanged.Password,
|
||||
"stored hash must be unchanged after a rejected change",
|
||||
)
|
||||
}
|
||||
|
||||
@@ -110,6 +110,7 @@ func (s *Server) setupUserRoutes() {
|
||||
r.Use(s.mw.NoCache())
|
||||
r.Use(s.mw.RequireAuth())
|
||||
r.Get("/", s.h.HandleProfile())
|
||||
r.Post("/password", s.h.HandlePasswordChange())
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user