summaryrefslogtreecommitdiff
path: root/internal/auth/handlers.go
blob: 78595d0e1cd05d2dbeb15a22e71704fac1ad5676 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package auth

import (
	"encoding/base64"
	"encoding/json"
	"html/template"
	"log"
	"net/http"

	"github.com/alexedwards/scs/v2"
	"github.com/go-chi/chi/v5"
	"github.com/go-webauthn/webauthn/protocol"
	"github.com/go-webauthn/webauthn/webauthn"
)

// Handlers provides HTTP handlers for authentication
type Handlers struct {
	service    *Service
	sessions   *scs.SessionManager
	middleware *Middleware
	templates  *template.Template
	webauthn   *webauthn.WebAuthn // nil if WebAuthn is not configured
}

// NewHandlers creates new auth handlers
func NewHandlers(service *Service, sessions *scs.SessionManager, templates *template.Template, wa *webauthn.WebAuthn) *Handlers {
	return &Handlers{
		service:    service,
		sessions:   sessions,
		middleware: NewMiddleware(sessions),
		templates:  templates,
		webauthn:   wa,
	}
}

// Middleware returns the auth middleware for use in routes
func (h *Handlers) Middleware() *Middleware {
	return h.middleware
}

// HandleLoginPage renders the login form
func (h *Handlers) HandleLoginPage(w http.ResponseWriter, r *http.Request) {
	// If already logged in, redirect to dashboard
	if h.middleware.IsAuthenticated(r) {
		http.Redirect(w, r, "/", http.StatusSeeOther)
		return
	}

	data := struct {
		Error          string
		CSRFToken      string
		WebAuthnEnabled bool
	}{
		Error:          "",
		CSRFToken:      h.middleware.GetCSRFToken(r),
		WebAuthnEnabled: h.webauthn != nil,
	}

	if err := h.templates.ExecuteTemplate(w, "login.html", data); err != nil {
		http.Error(w, "Failed to render template", http.StatusInternalServerError)
		log.Printf("Error rendering login template: %v", err)
	}
}

// HandleLogin processes login form submission
func (h *Handlers) HandleLogin(w http.ResponseWriter, r *http.Request) {
	if err := r.ParseForm(); err != nil {
		http.Error(w, "Failed to parse form", http.StatusBadRequest)
		return
	}

	username := r.FormValue("username")
	password := r.FormValue("password")

	if username == "" || password == "" {
		h.renderLoginError(w, r, "Username and password are required")
		return
	}

	user, err := h.service.Authenticate(username, password)
	if err != nil {
		log.Printf("Login failed for user %s: %v", username, err)
		h.renderLoginError(w, r, "Invalid username or password")
		return
	}

	// Regenerate session token to prevent session fixation
	if err := h.sessions.RenewToken(r.Context()); err != nil {
		http.Error(w, "Failed to create session", http.StatusInternalServerError)
		log.Printf("Failed to renew session token: %v", err)
		return
	}

	// Set user ID in session
	h.middleware.SetUserID(r, user.ID)

	log.Printf("User %s logged in successfully", username)
	http.Redirect(w, r, "/", http.StatusSeeOther)
}

// HandleLogout processes logout
func (h *Handlers) HandleLogout(w http.ResponseWriter, r *http.Request) {
	if err := h.middleware.ClearSession(r); err != nil {
		log.Printf("Error clearing session: %v", err)
	}

	http.Redirect(w, r, "/login", http.StatusSeeOther)
}

func (h *Handlers) renderLoginError(w http.ResponseWriter, r *http.Request, errorMsg string) {
	data := struct {
		Error          string
		CSRFToken      string
		WebAuthnEnabled bool
	}{
		Error:          errorMsg,
		CSRFToken:      h.middleware.GetCSRFToken(r),
		WebAuthnEnabled: h.webauthn != nil,
	}

	w.WriteHeader(http.StatusUnauthorized)
	if err := h.templates.ExecuteTemplate(w, "login.html", data); err != nil {
		http.Error(w, "Failed to render template", http.StatusInternalServerError)
		log.Printf("Error rendering login template: %v", err)
	}
}

// HandleListPasskeys returns the passkeys list partial for the settings page
func (h *Handlers) HandleListPasskeys(w http.ResponseWriter, r *http.Request) {
	if h.webauthn == nil {
		http.Error(w, "WebAuthn not configured", http.StatusNotFound)
		return
	}
	userID := h.middleware.GetUserID(r)
	infos, err := h.service.GetWebAuthnCredentialInfos(userID)
	if err != nil {
		log.Printf("Error getting passkeys: %v", err)
		http.Error(w, "Failed to load passkeys", http.StatusInternalServerError)
		return
	}

	data := struct {
		Passkeys  []WebAuthnCredentialInfo
		CSRFToken string
	}{
		Passkeys:  infos,
		CSRFToken: h.middleware.GetCSRFToken(r),
	}

	if err := h.templates.ExecuteTemplate(w, "passkeys_list.html", data); err != nil {
		log.Printf("Error rendering passkeys list: %v", err)
		http.Error(w, "Failed to render template", http.StatusInternalServerError)
	}
}

// HandlePasskeyRegisterBegin starts the WebAuthn registration ceremony
func (h *Handlers) HandlePasskeyRegisterBegin(w http.ResponseWriter, r *http.Request) {
	if h.webauthn == nil {
		jsonError(w, "WebAuthn not configured", http.StatusNotFound)
		return
	}

	userID := h.middleware.GetUserID(r)
	user, err := h.service.GetUserWithCredentials(userID)
	if err != nil {
		log.Printf("Error getting user for passkey registration: %v", err)
		jsonError(w, "Failed to get user", http.StatusInternalServerError)
		return
	}

	options, session, err := h.webauthn.BeginRegistration(user,
		webauthn.WithResidentKeyRequirement(protocol.ResidentKeyRequirementPreferred),
	)
	if err != nil {
		log.Printf("Error beginning passkey registration: %v", err)
		jsonError(w, "Failed to start registration", http.StatusInternalServerError)
		return
	}

	// Store session data for the finish step
	sessionBytes, err := json.Marshal(session)
	if err != nil {
		jsonError(w, "Failed to store session", http.StatusInternalServerError)
		return
	}
	h.sessions.Put(r.Context(), "webauthn_registration", string(sessionBytes))

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(options)
}

// HandlePasskeyRegisterFinish completes the WebAuthn registration ceremony
func (h *Handlers) HandlePasskeyRegisterFinish(w http.ResponseWriter, r *http.Request) {
	if h.webauthn == nil {
		jsonError(w, "WebAuthn not configured", http.StatusNotFound)
		return
	}

	userID := h.middleware.GetUserID(r)
	user, err := h.service.GetUserWithCredentials(userID)
	if err != nil {
		log.Printf("Error getting user for passkey registration finish: %v", err)
		jsonError(w, "Failed to get user", http.StatusInternalServerError)
		return
	}

	// Recover session data
	sessionJSON := h.sessions.GetString(r.Context(), "webauthn_registration")
	if sessionJSON == "" {
		jsonError(w, "No registration session found", http.StatusBadRequest)
		return
	}
	h.sessions.Remove(r.Context(), "webauthn_registration")

	var session webauthn.SessionData
	if err := json.Unmarshal([]byte(sessionJSON), &session); err != nil {
		jsonError(w, "Invalid session data", http.StatusBadRequest)
		return
	}

	cred, err := h.webauthn.FinishRegistration(user, session, r)
	if err != nil {
		log.Printf("Error finishing passkey registration: %v", err)
		jsonError(w, "Registration failed", http.StatusBadRequest)
		return
	}

	// Get the friendly name from query param or use default
	name := r.URL.Query().Get("name")
	if name == "" {
		name = "Passkey"
	}

	if err := h.service.SaveWebAuthnCredential(userID, cred, name); err != nil {
		log.Printf("Error saving passkey: %v", err)
		jsonError(w, "Failed to save passkey", http.StatusInternalServerError)
		return
	}

	log.Printf("Passkey registered for user %d: %s", userID, name)
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
}

// HandleDeletePasskey removes a passkey
func (h *Handlers) HandleDeletePasskey(w http.ResponseWriter, r *http.Request) {
	if h.webauthn == nil {
		http.Error(w, "WebAuthn not configured", http.StatusNotFound)
		return
	}

	// Extract passkey ID from URL path
	credID := chi.URLParam(r, "id")
	if credID == "" {
		http.Error(w, "Missing passkey ID", http.StatusBadRequest)
		return
	}

	if err := h.service.DeleteWebAuthnCredential(credID); err != nil {
		log.Printf("Error deleting passkey: %v", err)
		http.Error(w, "Failed to delete passkey", http.StatusInternalServerError)
		return
	}

	log.Printf("Passkey deleted: %s", credID)
	w.WriteHeader(http.StatusOK)
}

// HandlePasskeyLoginBegin starts the WebAuthn authentication ceremony (discoverable credentials)
func (h *Handlers) HandlePasskeyLoginBegin(w http.ResponseWriter, r *http.Request) {
	if h.webauthn == nil {
		jsonError(w, "WebAuthn not configured", http.StatusNotFound)
		return
	}

	options, session, err := h.webauthn.BeginDiscoverableLogin()
	if err != nil {
		log.Printf("Error beginning passkey login: %v", err)
		jsonError(w, "Failed to start login", http.StatusInternalServerError)
		return
	}

	sessionBytes, err := json.Marshal(session)
	if err != nil {
		jsonError(w, "Failed to store session", http.StatusInternalServerError)
		return
	}
	h.sessions.Put(r.Context(), "webauthn_login", string(sessionBytes))

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(options)
}

// HandlePasskeyLoginFinish completes the WebAuthn authentication ceremony
func (h *Handlers) HandlePasskeyLoginFinish(w http.ResponseWriter, r *http.Request) {
	if h.webauthn == nil {
		jsonError(w, "WebAuthn not configured", http.StatusNotFound)
		return
	}

	sessionJSON := h.sessions.GetString(r.Context(), "webauthn_login")
	if sessionJSON == "" {
		jsonError(w, "No login session found", http.StatusBadRequest)
		return
	}
	h.sessions.Remove(r.Context(), "webauthn_login")

	var session webauthn.SessionData
	if err := json.Unmarshal([]byte(sessionJSON), &session); err != nil {
		jsonError(w, "Invalid session data", http.StatusBadRequest)
		return
	}

	// User discovery handler - called by the library to find the user from the credential
	userHandler := func(rawID, userHandle []byte) (webauthn.User, error) {
		return h.service.FindUserByCredentialID(rawID)
	}

	cred, err := h.webauthn.FinishDiscoverableLogin(userHandler, session, r)
	if err != nil {
		log.Printf("Error finishing passkey login: %v", err)
		jsonError(w, "Login failed", http.StatusUnauthorized)
		return
	}

	// Find the user who owns this credential to create a session
	credIDStr := base64.RawURLEncoding.EncodeToString(cred.ID)
	user, err := h.service.FindUserByCredentialID(cred.ID)
	if err != nil {
		log.Printf("Error finding user for credential: %v", err)
		jsonError(w, "Login failed", http.StatusUnauthorized)
		return
	}

	// Update sign count
	if err := h.service.UpdateWebAuthnCredentialSignCount(credIDStr, cred.Authenticator.SignCount); err != nil {
		log.Printf("Error updating sign count: %v", err)
	}

	// Create session (same as password login)
	if err := h.sessions.RenewToken(r.Context()); err != nil {
		jsonError(w, "Failed to create session", http.StatusInternalServerError)
		return
	}
	h.middleware.SetUserID(r, user.ID)

	log.Printf("User %s logged in via passkey", user.Username)
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]string{"status": "ok", "redirect": "/"})
}

func jsonError(w http.ResponseWriter, msg string, code int) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)
	json.NewEncoder(w).Encode(map[string]string{"error": msg})
}