gitstack

demo/acme-pay code browser

962 B Go 35 lines 2024-01-17 · 1055b53 raw
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
package auth

import (
	"encoding/json"
	"net/http"
)

// LoginRequest is the JSON body for POST /login.
type LoginRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

// LoginHandler handles POST /login and returns a session token on success.
func LoginHandler(store UserStore) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req LoginRequest
		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
			http.Error(w, "bad request", http.StatusBadRequest)
			return
		}
		u, ok := store.ByUsername(req.Username)
		if !ok || !CheckPassword(req.Password, u.PassHash) {
			http.Error(w, "unauthorized", http.StatusUnauthorized)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
	}
}

// UserStore is the minimal interface LoginHandler needs.
type UserStore interface {
	ByUsername(name string) (*User, bool)
}