feat(auth): replace stub auth with real JWT + bcrypt

- RealAuthManager: JWT signing/validation + bcrypt password hashing
- MemUserStore: in-memory user store with default admin
- Register endpoint: user creation with hashed password
- Login endpoint: bcrypt verification + JWT generation
- AuthManager interface extended with Login/Register methods
This commit is contained in:
Aska committed 2026-08-12 12:21:36 +08:00
1 parent 6811480786
commit fbb331ed4b
4 files changed
+158 -10

No files matched your search

+21 -9
View File
@@ -15,9 +15,11 @@ import (
// --- Interfaces for injected services ---
// AuthManager validates JWT tokens.
// AuthManager validates JWT tokens and handles login/register.
type AuthManager interface {
ValidateToken(token string) (userID, username, role string, err error)
Login(username, password string) (token string, err error)
Register(username, password string) (token string, err error)
}
// MemoryEntry is a simplified memory entry for API responses.
@@ -161,12 +163,7 @@ func (r *Router) loginHandler(w http.ResponseWriter, req *http.Request) {
}
json.NewDecoder(req.Body).Decode(&body)
mgr, ok := r.deps.AuthMgr.(*StubAuthManager)
if !ok {
writeJSON(w, 500, M{"error": "auth not configured"})
return
}
token, err := mgr.Login(body.Username, body.Password)
token, err := r.deps.AuthMgr.Login(body.Username, body.Password)
if err != nil {
writeJSON(w, 401, M{"error": "invalid credentials"})
return
@@ -174,8 +171,23 @@ func (r *Router) loginHandler(w http.ResponseWriter, req *http.Request) {
writeJSON(w, 200, M{"token": token})
}
func (r *Router) registerHandler(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, 200, M{"message": "registration not implemented"})
func (r *Router) registerHandler(w http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
writeJSON(w, 405, M{"error": "POST required"})
return
}
var body struct {
Username string `json:"username"`
Password string `json:"password"`
}
json.NewDecoder(req.Body).Decode(&body)
token, err := r.deps.AuthMgr.Register(body.Username, body.Password)
if err != nil {
writeJSON(w, 400, M{"error": err.Error()})
return
}
writeJSON(w, 201, M{"token": token})
}
// --- Sessions ---