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"
)
type LoginRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
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"})
}
}
type UserStore interface {
ByUsername(name string) (*User, bool)
}
|