Backend: Customers, Auth (JWT), Agent-Kundenzuordnung, CORS

This commit is contained in:
cynfo3000
2026-02-28 15:28:02 +01:00
parent 5daf81b9de
commit c6c8257cf0
15 changed files with 717 additions and 17 deletions
+144
View File
@@ -0,0 +1,144 @@
package api
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"log"
"net/http"
"time"
"github.com/cynfo/rmm-backend/db"
"github.com/cynfo/rmm-backend/models"
"github.com/golang-jwt/jwt/v5"
"golang.org/x/crypto/bcrypt"
)
type AuthHandler struct {
db *db.Database
secret []byte
}
type JWTClaims struct {
UserID int `json:"user_id"`
Username string `json:"username"`
Role string `json:"role"`
jwt.RegisteredClaims
}
func NewAuthHandler(database *db.Database, jwtSecret string) *AuthHandler {
secret := jwtSecret
if secret == "" {
b := make([]byte, 32)
rand.Read(b)
secret = hex.EncodeToString(b)
log.Println("JWT Secret automatisch generiert (nicht persistent)")
}
return &AuthHandler{db: database, secret: []byte(secret)}
}
func (a *AuthHandler) EnsureDefaultAdmin() {
count, err := a.db.UserCount()
if err != nil {
log.Printf("User-Count Fehler: %v", err)
return
}
if count == 0 {
_, err := a.db.CreateUser("admin", "admin", "Administrator", "admin")
if err != nil {
log.Printf("Default-Admin anlegen fehlgeschlagen: %v", err)
} else {
log.Println("Default-Admin angelegt (admin/admin) - bitte Passwort aendern!")
}
}
}
func (a *AuthHandler) GenerateToken(user *models.User) (string, time.Time, error) {
expiresAt := time.Now().Add(8 * time.Hour)
claims := JWTClaims{
UserID: user.ID,
Username: user.Username,
Role: user.Role,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(expiresAt),
IssuedAt: jwt.NewNumericDate(time.Now()),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signed, err := token.SignedString(a.secret)
return signed, expiresAt, err
}
func (a *AuthHandler) ValidateToken(tokenStr string) (*JWTClaims, error) {
token, err := jwt.ParseWithClaims(tokenStr, &JWTClaims{}, func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
}
return a.secret, nil
})
if err != nil {
return nil, err
}
claims, ok := token.Claims.(*JWTClaims)
if !ok || !token.Valid {
return nil, fmt.Errorf("invalid token")
}
return claims, nil
}
// POST /api/v1/auth/login
func (a *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
var req models.LoginRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "Ungueltige Anfrage")
return
}
user, err := a.db.GetUserByUsername(req.Username)
if err != nil || user == nil {
writeError(w, http.StatusUnauthorized, "Ungueltige Anmeldedaten")
return
}
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password)); err != nil {
writeError(w, http.StatusUnauthorized, "Ungueltige Anmeldedaten")
return
}
token, expiresAt, err := a.GenerateToken(user)
if err != nil {
writeError(w, http.StatusInternalServerError, "Token-Generierung fehlgeschlagen")
return
}
a.db.UpdateUserLastLogin(user.ID)
writeJSON(w, http.StatusOK, models.LoginResponse{
Token: token,
ExpiresAt: expiresAt.Format(time.RFC3339),
User: *user,
})
}
// GET /api/v1/auth/me
func (a *AuthHandler) Me(w http.ResponseWriter, r *http.Request) {
claims, ok := r.Context().Value(UserContextKey).(*JWTClaims)
if !ok {
writeError(w, http.StatusUnauthorized, "Nicht authentifiziert")
return
}
user, err := a.db.GetUserByUsername(claims.Username)
if err != nil || user == nil {
writeError(w, http.StatusNotFound, "User nicht gefunden")
return
}
writeJSON(w, http.StatusOK, user)
}
// SetupAuthRoutes registriert Auth-Routes (ohne Auth-Middleware)
func (a *AuthHandler) SetupAuthRoutes(mux *http.ServeMux) {
mux.HandleFunc("POST /api/v1/auth/login", a.Login)
}
+137
View File
@@ -0,0 +1,137 @@
package api
import (
"encoding/json"
"net/http"
"strconv"
)
// GET /api/v1/customers
func (h *Handler) listCustomers(w http.ResponseWriter, r *http.Request) {
customers, err := h.db.GetCustomers()
if err != nil {
writeError(w, http.StatusInternalServerError, "Fehler beim Laden")
return
}
writeJSON(w, http.StatusOK, customers)
}
// POST /api/v1/customers
func (h *Handler) createCustomer(w http.ResponseWriter, r *http.Request) {
var req struct {
Number string `json:"number"`
Name string `json:"name"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Number == "" || req.Name == "" {
writeError(w, http.StatusBadRequest, "number und name sind erforderlich")
return
}
c, err := h.db.CreateCustomer(req.Number, req.Name)
if err != nil {
writeError(w, http.StatusInternalServerError, "Kunde anlegen fehlgeschlagen")
return
}
writeJSON(w, http.StatusCreated, c)
}
// GET /api/v1/customers/{id}
func (h *Handler) getCustomer(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
writeError(w, http.StatusBadRequest, "Ungueltige ID")
return
}
c, err := h.db.GetCustomer(id)
if err != nil {
writeError(w, http.StatusInternalServerError, "Fehler beim Laden")
return
}
if c == nil {
writeError(w, http.StatusNotFound, "Kunde nicht gefunden")
return
}
writeJSON(w, http.StatusOK, c)
}
// PUT /api/v1/customers/{id}
func (h *Handler) updateCustomer(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
writeError(w, http.StatusBadRequest, "Ungueltige ID")
return
}
var req struct {
Number string `json:"number"`
Name string `json:"name"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Number == "" || req.Name == "" {
writeError(w, http.StatusBadRequest, "number und name sind erforderlich")
return
}
if err := h.db.UpdateCustomer(id, req.Number, req.Name); err != nil {
writeError(w, http.StatusInternalServerError, "Aktualisierung fehlgeschlagen")
return
}
writeJSON(w, http.StatusOK, map[string]string{"message": "Kunde aktualisiert"})
}
// DELETE /api/v1/customers/{id}
func (h *Handler) deleteCustomer(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
writeError(w, http.StatusBadRequest, "Ungueltige ID")
return
}
deleted, err := h.db.DeleteCustomer(id)
if err != nil {
writeError(w, http.StatusInternalServerError, "Loeschen fehlgeschlagen")
return
}
if !deleted {
writeError(w, http.StatusNotFound, "Kunde nicht gefunden")
return
}
writeJSON(w, http.StatusOK, map[string]string{"message": "Kunde geloescht"})
}
// GET /api/v1/customers/{id}/agents
func (h *Handler) getCustomerAgents(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
writeError(w, http.StatusBadRequest, "Ungueltige ID")
return
}
agents, err := h.db.GetAgentsByCustomer(id)
if err != nil {
writeError(w, http.StatusInternalServerError, "Fehler beim Laden")
return
}
writeJSON(w, http.StatusOK, agents)
}
// PUT /api/v1/agents/{id}/customer
func (h *Handler) assignAgentCustomer(w http.ResponseWriter, r *http.Request) {
agentID := r.PathValue("id")
var req struct {
CustomerID int `json:"customer_id"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.CustomerID == 0 {
writeError(w, http.StatusBadRequest, "customer_id erforderlich")
return
}
if err := h.db.AssignAgentCustomer(agentID, req.CustomerID); err != nil {
writeError(w, http.StatusInternalServerError, "Zuordnung fehlgeschlagen")
return
}
writeJSON(w, http.StatusOK, map[string]string{"message": "Agent zugeordnet"})
}
// DELETE /api/v1/agents/{id}/customer
func (h *Handler) unassignAgentCustomer(w http.ResponseWriter, r *http.Request) {
agentID := r.PathValue("id")
if err := h.db.UnassignAgentCustomer(agentID); err != nil {
writeError(w, http.StatusInternalServerError, "Zuordnung entfernen fehlgeschlagen")
return
}
writeJSON(w, http.StatusOK, map[string]string{"message": "Zuordnung entfernt"})
}
+17
View File
@@ -35,6 +35,23 @@ func (h *Handler) SetupRoutes(mux *http.ServeMux, hub *ws.Hub) {
mux.HandleFunc("GET /api/v1/agents/{id}/system", h.getSystemData)
mux.HandleFunc("DELETE /api/v1/agents/{id}", h.deleteAgent)
// Customer-Routes
mux.HandleFunc("GET /api/v1/customers", h.listCustomers)
mux.HandleFunc("POST /api/v1/customers", h.createCustomer)
mux.HandleFunc("GET /api/v1/customers/{id}", h.getCustomer)
mux.HandleFunc("PUT /api/v1/customers/{id}", h.updateCustomer)
mux.HandleFunc("DELETE /api/v1/customers/{id}", h.deleteCustomer)
mux.HandleFunc("GET /api/v1/customers/{id}/agents", h.getCustomerAgents)
// Agent-Customer Zuordnung
mux.HandleFunc("PUT /api/v1/agents/{id}/customer", h.assignAgentCustomer)
mux.HandleFunc("DELETE /api/v1/agents/{id}/customer", h.unassignAgentCustomer)
// User-Routes
mux.HandleFunc("GET /api/v1/users", h.listUsers)
mux.HandleFunc("POST /api/v1/users", h.createUser)
mux.HandleFunc("DELETE /api/v1/users/{id}", h.deleteUser)
// WebSocket und Tunnel-Routes
h.setupTunnelRoutes(mux, hub)
}
+54 -1
View File
@@ -1,11 +1,17 @@
package api
import (
"context"
"log"
"net/http"
"strings"
"time"
)
type contextKey string
const UserContextKey contextKey = "user"
// APIKeyAuth - Middleware fuer API-Key Authentifizierung
func APIKeyAuth(validKeys []string, next http.Handler) http.Handler {
keySet := make(map[string]bool, len(validKeys))
@@ -15,7 +21,6 @@ func APIKeyAuth(validKeys []string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key := r.Header.Get("X-API-Key")
// Fallback: Query-Parameter (fuer WebSocket-Verbindungen)
if key == "" {
key = r.URL.Query().Get("api_key")
}
@@ -27,6 +32,54 @@ func APIKeyAuth(validKeys []string, next http.Handler) http.Handler {
})
}
// CombinedAuth - API-Key ODER JWT Token
func CombinedAuth(validKeys []string, auth *AuthHandler, next http.Handler) http.Handler {
keySet := make(map[string]bool, len(validKeys))
for _, k := range validKeys {
keySet[k] = true
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Try API key first
key := r.Header.Get("X-API-Key")
if key == "" {
key = r.URL.Query().Get("api_key")
}
if key != "" && keySet[key] {
next.ServeHTTP(w, r)
return
}
// Try JWT
authHeader := r.Header.Get("Authorization")
if strings.HasPrefix(authHeader, "Bearer ") {
token := strings.TrimPrefix(authHeader, "Bearer ")
claims, err := auth.ValidateToken(token)
if err == nil {
ctx := context.WithValue(r.Context(), UserContextKey, claims)
next.ServeHTTP(w, r.WithContext(ctx))
return
}
}
http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
})
}
// CORS Middleware
func CORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-API-Key")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}
// Logging - Request-Logging Middleware
func Logging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+59
View File
@@ -0,0 +1,59 @@
package api
import (
"encoding/json"
"net/http"
"strconv"
)
// GET /api/v1/users
func (h *Handler) listUsers(w http.ResponseWriter, r *http.Request) {
users, err := h.db.GetUsers()
if err != nil {
writeError(w, http.StatusInternalServerError, "Fehler beim Laden")
return
}
writeJSON(w, http.StatusOK, users)
}
// POST /api/v1/users
func (h *Handler) createUser(w http.ResponseWriter, r *http.Request) {
var req struct {
Username string `json:"username"`
Password string `json:"password"`
DisplayName string `json:"display_name"`
Role string `json:"role"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Username == "" || req.Password == "" {
writeError(w, http.StatusBadRequest, "username und password sind erforderlich")
return
}
if req.Role == "" {
req.Role = "admin"
}
u, err := h.db.CreateUser(req.Username, req.Password, req.DisplayName, req.Role)
if err != nil {
writeError(w, http.StatusInternalServerError, "User anlegen fehlgeschlagen")
return
}
writeJSON(w, http.StatusCreated, u)
}
// DELETE /api/v1/users/{id}
func (h *Handler) deleteUser(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
writeError(w, http.StatusBadRequest, "Ungueltige ID")
return
}
deleted, err := h.db.DeleteUser(id)
if err != nil {
writeError(w, http.StatusInternalServerError, "Loeschen fehlgeschlagen")
return
}
if !deleted {
writeError(w, http.StatusNotFound, "User nicht gefunden")
return
}
writeJSON(w, http.StatusOK, map[string]string{"message": "User geloescht"})
}