Merge branch 'main' into release
This commit is contained in:
+206
-6
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/cynfo/rmm-backend/db"
|
||||
"github.com/cynfo/rmm-backend/models"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/pquerna/otp/totp"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
@@ -21,9 +22,10 @@ type AuthHandler struct {
|
||||
}
|
||||
|
||||
type JWTClaims struct {
|
||||
UserID int `json:"user_id"`
|
||||
Username string `json:"username"`
|
||||
Role string `json:"role"`
|
||||
UserID int `json:"user_id"`
|
||||
Username string `json:"username"`
|
||||
Role string `json:"role"`
|
||||
TOTPPending bool `json:"totp_pending,omitempty"` // temp token während 2FA-Schritt
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
@@ -70,6 +72,22 @@ func (a *AuthHandler) GenerateToken(user *models.User) (string, time.Time, error
|
||||
return signed, expiresAt, err
|
||||
}
|
||||
|
||||
// Kurzlebiger Token nur für den TOTP-Schritt (5 Minuten, kein echter API-Zugriff)
|
||||
func (a *AuthHandler) generateTOTPPendingToken(user *models.User) (string, error) {
|
||||
claims := JWTClaims{
|
||||
UserID: user.ID,
|
||||
Username: user.Username,
|
||||
Role: user.Role,
|
||||
TOTPPending: true,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(5 * time.Minute)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
}
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString(a.secret)
|
||||
}
|
||||
|
||||
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 {
|
||||
@@ -84,6 +102,10 @@ func (a *AuthHandler) ValidateToken(tokenStr string) (*JWTClaims, error) {
|
||||
if !ok || !token.Valid {
|
||||
return nil, fmt.Errorf("invalid token")
|
||||
}
|
||||
// Echte API-Calls mit Pending-Token ablehnen
|
||||
if claims.TOTPPending {
|
||||
return nil, fmt.Errorf("totp pending token not valid for api access")
|
||||
}
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
@@ -106,6 +128,22 @@ func (a *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// 2FA aktiv → Pending-Token zurückgeben
|
||||
if user.TOTPEnabled {
|
||||
pendingToken, err := a.generateTOTPPendingToken(user)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Token-Generierung fehlgeschlagen")
|
||||
return
|
||||
}
|
||||
go a.db.AddAuditLog(user.Username, "login_2fa_pending", "user", "", user.Username, "", r.RemoteAddr)
|
||||
writeJSON(w, http.StatusOK, models.LoginResponse{
|
||||
TOTPRequired: true,
|
||||
TOTPToken: pendingToken,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Kein 2FA → direkt JWT
|
||||
token, expiresAt, err := a.GenerateToken(user)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Token-Generierung fehlgeschlagen")
|
||||
@@ -113,17 +151,178 @@ func (a *AuthHandler) Login(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
a.db.UpdateUserLastLogin(user.ID)
|
||||
|
||||
// Audit log
|
||||
go a.db.AddAuditLog(user.Username, "login", "user", "", user.Username, "", r.RemoteAddr)
|
||||
|
||||
writeJSON(w, http.StatusOK, models.LoginResponse{
|
||||
Token: token,
|
||||
ExpiresAt: expiresAt.Format(time.RFC3339),
|
||||
User: *user,
|
||||
User: user,
|
||||
})
|
||||
}
|
||||
|
||||
// POST /api/v1/auth/2fa/validate — zweiter Schritt beim Login
|
||||
func (a *AuthHandler) TOTPValidate(w http.ResponseWriter, r *http.Request) {
|
||||
var req models.TOTPValidateRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "Ungueltige Anfrage")
|
||||
return
|
||||
}
|
||||
|
||||
// Pending-Token parsen (ohne ValidateToken, der lehnt Pending-Tokens ab)
|
||||
jwtToken, err := jwt.ParseWithClaims(req.TOTPToken, &JWTClaims{}, func(t *jwt.Token) (interface{}, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method")
|
||||
}
|
||||
return a.secret, nil
|
||||
})
|
||||
if err != nil {
|
||||
writeError(w, http.StatusUnauthorized, "Ungueltige Session")
|
||||
return
|
||||
}
|
||||
claims, ok := jwtToken.Claims.(*JWTClaims)
|
||||
if !ok || !jwtToken.Valid || !claims.TOTPPending {
|
||||
writeError(w, http.StatusUnauthorized, "Ungueltige Session")
|
||||
return
|
||||
}
|
||||
|
||||
user, err := a.db.GetUserByID(claims.UserID)
|
||||
if err != nil || user == nil || !user.TOTPEnabled {
|
||||
writeError(w, http.StatusUnauthorized, "Ungueltige Session")
|
||||
return
|
||||
}
|
||||
|
||||
if !totp.Validate(req.Code, user.TOTPSecret) {
|
||||
writeError(w, http.StatusUnauthorized, "Ungültiger 2FA-Code")
|
||||
return
|
||||
}
|
||||
|
||||
token, expiresAt, err := a.GenerateToken(user)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Token-Generierung fehlgeschlagen")
|
||||
return
|
||||
}
|
||||
|
||||
a.db.UpdateUserLastLogin(user.ID)
|
||||
go a.db.AddAuditLog(user.Username, "login_2fa_success", "user", "", user.Username, "", r.RemoteAddr)
|
||||
|
||||
writeJSON(w, http.StatusOK, models.LoginResponse{
|
||||
Token: token,
|
||||
ExpiresAt: expiresAt.Format(time.RFC3339),
|
||||
User: user,
|
||||
})
|
||||
}
|
||||
|
||||
// POST /api/v1/auth/2fa/setup — Secret generieren, QR-URI zurückgeben
|
||||
func (a *AuthHandler) TOTPSetup(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.GetUserByID(claims.UserID)
|
||||
if err != nil || user == nil {
|
||||
writeError(w, http.StatusNotFound, "User nicht gefunden")
|
||||
return
|
||||
}
|
||||
|
||||
key, err := totp.Generate(totp.GenerateOpts{
|
||||
Issuer: "cynfo RMM",
|
||||
AccountName: user.Username,
|
||||
Period: 30,
|
||||
Digits: 6,
|
||||
})
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "TOTP-Generierung fehlgeschlagen")
|
||||
return
|
||||
}
|
||||
|
||||
if err := a.db.SetTOTPSecret(user.ID, key.Secret()); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Speichern fehlgeschlagen")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, models.TOTPSetupResponse{
|
||||
Secret: key.Secret(),
|
||||
URI: key.URL(),
|
||||
})
|
||||
}
|
||||
|
||||
// POST /api/v1/auth/2fa/confirm — ersten Code prüfen und 2FA aktivieren
|
||||
func (a *AuthHandler) TOTPConfirm(w http.ResponseWriter, r *http.Request) {
|
||||
claims, ok := r.Context().Value(UserContextKey).(*JWTClaims)
|
||||
if !ok {
|
||||
writeError(w, http.StatusUnauthorized, "Nicht authentifiziert")
|
||||
return
|
||||
}
|
||||
|
||||
var req models.TOTPConfirmRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "Ungueltige Anfrage")
|
||||
return
|
||||
}
|
||||
|
||||
user, err := a.db.GetUserByID(claims.UserID)
|
||||
if err != nil || user == nil || user.TOTPSecret == "" {
|
||||
writeError(w, http.StatusBadRequest, "Kein Setup gefunden — bitte zuerst /2fa/setup aufrufen")
|
||||
return
|
||||
}
|
||||
|
||||
if !totp.Validate(req.Code, user.TOTPSecret) {
|
||||
writeError(w, http.StatusUnauthorized, "Ungültiger Code")
|
||||
return
|
||||
}
|
||||
|
||||
if err := a.db.EnableTOTP(user.ID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Aktivierung fehlgeschlagen")
|
||||
return
|
||||
}
|
||||
|
||||
go a.db.AddAuditLog(claims.Username, "2fa_enabled", "user", "", claims.Username, "", r.RemoteAddr)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
}
|
||||
|
||||
// POST /api/v1/auth/2fa/disable — 2FA deaktivieren (Passwort + aktueller Code nötig)
|
||||
func (a *AuthHandler) TOTPDisable(w http.ResponseWriter, r *http.Request) {
|
||||
claims, ok := r.Context().Value(UserContextKey).(*JWTClaims)
|
||||
if !ok {
|
||||
writeError(w, http.StatusUnauthorized, "Nicht authentifiziert")
|
||||
return
|
||||
}
|
||||
|
||||
var req models.TOTPDisableRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "Ungueltige Anfrage")
|
||||
return
|
||||
}
|
||||
|
||||
user, err := a.db.GetUserByID(claims.UserID)
|
||||
if err != nil || user == nil {
|
||||
writeError(w, http.StatusNotFound, "User nicht gefunden")
|
||||
return
|
||||
}
|
||||
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password)); err != nil {
|
||||
writeError(w, http.StatusUnauthorized, "Falsches Passwort")
|
||||
return
|
||||
}
|
||||
|
||||
if user.TOTPEnabled {
|
||||
if !totp.Validate(req.Code, user.TOTPSecret) {
|
||||
writeError(w, http.StatusUnauthorized, "Ungültiger 2FA-Code")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if err := a.db.DisableTOTP(user.ID); err != nil {
|
||||
writeError(w, http.StatusInternalServerError, "Deaktivierung fehlgeschlagen")
|
||||
return
|
||||
}
|
||||
|
||||
go a.db.AddAuditLog(claims.Username, "2fa_disabled", "user", "", claims.Username, "", r.RemoteAddr)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
|
||||
}
|
||||
|
||||
// GET /api/v1/auth/me
|
||||
func (a *AuthHandler) Me(w http.ResponseWriter, r *http.Request) {
|
||||
claims, ok := r.Context().Value(UserContextKey).(*JWTClaims)
|
||||
@@ -144,4 +343,5 @@ func (a *AuthHandler) Me(w http.ResponseWriter, r *http.Request) {
|
||||
// SetupAuthRoutes registriert Auth-Routes (ohne Auth-Middleware)
|
||||
func (a *AuthHandler) SetupAuthRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("POST /api/v1/auth/login", a.Login)
|
||||
mux.HandleFunc("POST /api/v1/auth/2fa/validate", a.TOTPValidate)
|
||||
}
|
||||
|
||||
@@ -63,6 +63,17 @@ func (s *TaskScheduler) executeTask(task models.Task) {
|
||||
result, taskErr = s.executeBackup(task.AgentID)
|
||||
case "update":
|
||||
result, taskErr = s.executeUpdateWithHealthCheck(task.AgentID, task.Reboot, task.HealthCheck, task.HealthCheckTimeout, task.SecurityOnly)
|
||||
case "zpoolscrub":
|
||||
result, taskErr = s.executeSimpleCommand(task.AgentID, "zpoolscrub", map[string]interface{}{})
|
||||
case "script":
|
||||
timeout := task.ScriptTimeout
|
||||
if timeout <= 0 {
|
||||
timeout = 300
|
||||
}
|
||||
result, taskErr = s.executeSimpleCommand(task.AgentID, "exec", map[string]interface{}{
|
||||
"command": task.Script,
|
||||
"timeout": timeout,
|
||||
})
|
||||
default:
|
||||
taskErr = fmt.Errorf("unbekannte Aktion: %s", task.Action)
|
||||
}
|
||||
@@ -106,6 +117,36 @@ func (s *TaskScheduler) executeTask(task models.Task) {
|
||||
}
|
||||
}
|
||||
|
||||
// executeSimpleCommand schickt einen beliebigen Command an den Agenten und wartet auf Antwort
|
||||
func (s *TaskScheduler) executeSimpleCommand(agentID, command string, params map[string]interface{}) (interface{}, error) {
|
||||
if !s.hub.IsAgentConnected(agentID) {
|
||||
return nil, fmt.Errorf("Agent nicht verbunden")
|
||||
}
|
||||
cmdID := generateID()
|
||||
cmd := map[string]interface{}{
|
||||
"type": "command",
|
||||
"id": cmdID,
|
||||
"command": command,
|
||||
"params": params,
|
||||
}
|
||||
responseCh := s.hub.RegisterResponseWaiter(cmdID)
|
||||
defer s.hub.UnregisterResponseWaiter(cmdID)
|
||||
cmdJSON, _ := json.Marshal(cmd)
|
||||
if err := s.hub.SendToAgent(agentID, cmdJSON); err != nil {
|
||||
return nil, fmt.Errorf("Senden fehlgeschlagen: %w", err)
|
||||
}
|
||||
select {
|
||||
case resp := <-responseCh:
|
||||
if status, _ := resp["status"].(string); status == "error" {
|
||||
errMsg, _ := resp["error"].(string)
|
||||
return resp["data"], fmt.Errorf("%s", errMsg)
|
||||
}
|
||||
return resp["data"], nil
|
||||
case <-time.After(120 * time.Second):
|
||||
return nil, fmt.Errorf("Timeout nach 120s")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TaskScheduler) executeBackup(agentID string) (interface{}, error) {
|
||||
if !s.hub.IsAgentConnected(agentID) {
|
||||
return nil, fmt.Errorf("Agent nicht verbunden")
|
||||
|
||||
@@ -80,6 +80,8 @@ func (h *Handler) createTask(hub *ws.Hub) http.HandlerFunc {
|
||||
HealthCheck bool `json:"health_check"`
|
||||
HealthCheckTimeout int `json:"health_check_timeout"`
|
||||
SecurityOnly bool `json:"security_only"`
|
||||
Script string `json:"script"`
|
||||
ScriptTimeout int `json:"script_timeout"`
|
||||
WebhookURL string `json:"webhook_url"`
|
||||
Active *bool `json:"active"`
|
||||
}
|
||||
@@ -93,8 +95,12 @@ func (h *Handler) createTask(hub *ws.Hub) http.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
if req.Action != "backup" && req.Action != "update" {
|
||||
writeError(w, http.StatusBadRequest, "Ungueltige Aktion (backup, update)")
|
||||
if req.Action != "backup" && req.Action != "update" && req.Action != "zpoolscrub" && req.Action != "script" {
|
||||
writeError(w, http.StatusBadRequest, "Ungueltige Aktion (backup, update, zpoolscrub, script)")
|
||||
return
|
||||
}
|
||||
if req.Action == "script" && req.Script == "" {
|
||||
writeError(w, http.StatusBadRequest, "Skript-Inhalt darf nicht leer sein")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -119,6 +125,7 @@ func (h *Handler) createTask(hub *ws.Hub) http.HandlerFunc {
|
||||
req.Name, req.ScheduleType, req.ScheduleTime,
|
||||
req.ScheduleWeekday, req.ScheduleMonthday,
|
||||
req.Reboot, req.HealthCheck, req.HealthCheckTimeout, req.SecurityOnly, active,
|
||||
req.Script, req.ScriptTimeout,
|
||||
)
|
||||
if err != nil {
|
||||
log.Printf("Task erstellen fehlgeschlagen: %v", err)
|
||||
|
||||
@@ -128,6 +128,10 @@ func (d *Database) migrate() error {
|
||||
return fmt.Errorf("Schema anlegen: %w", err)
|
||||
}
|
||||
|
||||
// TOTP 2FA Spalten
|
||||
d.db.Exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS totp_secret TEXT")
|
||||
d.db.Exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT false")
|
||||
|
||||
// Agents um customer_id erweitern
|
||||
d.db.Exec("ALTER TABLE agents ADD COLUMN IF NOT EXISTS customer_id INTEGER REFERENCES customers(id)")
|
||||
d.db.Exec("CREATE INDEX IF NOT EXISTS idx_agents_customer ON agents(customer_id)")
|
||||
@@ -266,6 +270,8 @@ func (d *Database) migrate() error {
|
||||
d.db.Exec(`ALTER TABLE tasks ADD COLUMN IF NOT EXISTS last_run TIMESTAMPTZ`)
|
||||
d.db.Exec(`ALTER TABLE tasks ADD COLUMN IF NOT EXISTS next_run TIMESTAMPTZ`)
|
||||
d.db.Exec(`ALTER TABLE tasks ADD COLUMN IF NOT EXISTS run_count INT DEFAULT 0`)
|
||||
d.db.Exec(`ALTER TABLE tasks ADD COLUMN IF NOT EXISTS script TEXT`)
|
||||
d.db.Exec(`ALTER TABLE tasks ADD COLUMN IF NOT EXISTS script_timeout INT DEFAULT 300`)
|
||||
d.db.Exec(`CREATE INDEX IF NOT EXISTS idx_tasks_active_next_run ON tasks(active, next_run) WHERE active = TRUE`)
|
||||
|
||||
// Retention Policy (90 Tage)
|
||||
|
||||
+22
-7
@@ -62,9 +62,10 @@ func CalculateNextRun(scheduleType, scheduleTime string, weekday, monthday *int,
|
||||
|
||||
func (d *Database) CreateTask(agentID, action, scheduledAt, webhookURL, createdBy string,
|
||||
name, scheduleType, scheduleTime string, weekday, monthday *int,
|
||||
reboot, healthCheck bool, healthCheckTimeout int, securityOnly bool, active bool) (*models.Task, error) {
|
||||
reboot, healthCheck bool, healthCheckTimeout int, securityOnly bool, active bool,
|
||||
script string, scriptTimeout int) (*models.Task, error) {
|
||||
|
||||
validActions := map[string]bool{"backup": true, "update": true}
|
||||
validActions := map[string]bool{"backup": true, "update": true, "zpoolscrub": true, "script": true}
|
||||
if !validActions[action] {
|
||||
return nil, fmt.Errorf("ungueltige Aktion: %s", action)
|
||||
}
|
||||
@@ -103,16 +104,22 @@ func (d *Database) CreateTask(agentID, action, scheduledAt, webhookURL, createdB
|
||||
nextRun = CalculateNextRun(scheduleType, scheduleTime, weekday, monthday, now)
|
||||
}
|
||||
|
||||
if scriptTimeout <= 0 {
|
||||
scriptTimeout = 300
|
||||
}
|
||||
|
||||
var taskID int
|
||||
err := d.db.QueryRow(`
|
||||
INSERT INTO tasks (agent_id, name, action, scheduled_at, webhook_url, created_by,
|
||||
schedule_type, schedule_time, schedule_weekday, schedule_monthday,
|
||||
reboot, health_check, health_check_timeout, security_only, active, next_run)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16)
|
||||
reboot, health_check, health_check_timeout, security_only, active, next_run,
|
||||
script, script_timeout)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18)
|
||||
RETURNING id
|
||||
`, agentID, name, action, schedTime, webhookURL, createdBy,
|
||||
scheduleType, scheduleTime, weekday, monthday,
|
||||
reboot, healthCheck, healthCheckTimeout, securityOnly, active, nextRun).Scan(&taskID)
|
||||
reboot, healthCheck, healthCheckTimeout, securityOnly, active, nextRun,
|
||||
script, scriptTimeout).Scan(&taskID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Task erstellen: %w", err)
|
||||
}
|
||||
@@ -130,7 +137,8 @@ func scanTask(scan func(dest ...interface{}) error) (*models.Task, error) {
|
||||
var name, scheduleType, scheduleTime sql.NullString
|
||||
var scheduleWeekday, scheduleMonthday sql.NullInt32
|
||||
var reboot, healthCheck, securityOnly, active sql.NullBool
|
||||
var healthCheckTimeout, runCount sql.NullInt32
|
||||
var healthCheckTimeout, runCount, scriptTimeout sql.NullInt32
|
||||
var script sql.NullString
|
||||
|
||||
err := scan(
|
||||
&t.ID, &t.AgentID, &agentName, &customerName, &customerNumber,
|
||||
@@ -139,6 +147,7 @@ func scanTask(scan func(dest ...interface{}) error) (*models.Task, error) {
|
||||
&createdBy, &createdAt,
|
||||
&scheduleType, &scheduleTime, &scheduleWeekday, &scheduleMonthday,
|
||||
&reboot, &healthCheck, &healthCheckTimeout, &securityOnly, &active, &lastRun, &nextRun, &runCount,
|
||||
&script, &scriptTimeout,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -171,6 +180,11 @@ func scanTask(scan func(dest ...interface{}) error) (*models.Task, error) {
|
||||
t.HealthCheckTimeout = int(healthCheckTimeout.Int32)
|
||||
}
|
||||
t.SecurityOnly = securityOnly.Valid && securityOnly.Bool
|
||||
t.Script = script.String
|
||||
t.ScriptTimeout = 300
|
||||
if scriptTimeout.Valid && scriptTimeout.Int32 > 0 {
|
||||
t.ScriptTimeout = int(scriptTimeout.Int32)
|
||||
}
|
||||
t.Active = !active.Valid || active.Bool
|
||||
t.RunCount = int(runCount.Int32)
|
||||
|
||||
@@ -215,7 +229,8 @@ const taskSelectCols = `t.id, t.agent_id, COALESCE(a.name, ''), COALESCE(c.name,
|
||||
t.result, t.webhook_url, t.webhook_sent, t.webhook_response,
|
||||
t.created_by, t.created_at,
|
||||
t.schedule_type, t.schedule_time, t.schedule_weekday, t.schedule_monthday,
|
||||
t.reboot, t.health_check, t.health_check_timeout, COALESCE(t.security_only, FALSE), t.active, t.last_run, t.next_run, t.run_count`
|
||||
t.reboot, t.health_check, t.health_check_timeout, COALESCE(t.security_only, FALSE), t.active, t.last_run, t.next_run, t.run_count,
|
||||
COALESCE(t.script, ''), COALESCE(t.script_timeout, 300)`
|
||||
|
||||
const taskFromJoin = `FROM tasks t
|
||||
LEFT JOIN agents a ON a.id = t.agent_id
|
||||
|
||||
+44
-2
@@ -27,10 +27,11 @@ func (d *Database) CreateUser(username, password, displayName, role string) (*mo
|
||||
func (d *Database) GetUserByUsername(username string) (*models.User, error) {
|
||||
var u models.User
|
||||
var lastLogin sql.NullTime
|
||||
var totpSecret sql.NullString
|
||||
err := d.db.QueryRow(
|
||||
"SELECT id, username, password_hash, display_name, role, created_at, last_login FROM users WHERE username = $1",
|
||||
"SELECT id, username, password_hash, display_name, role, totp_enabled, totp_secret, created_at, last_login FROM users WHERE username = $1",
|
||||
username,
|
||||
).Scan(&u.ID, &u.Username, &u.PasswordHash, &u.DisplayName, &u.Role, &u.CreatedAt, &lastLogin)
|
||||
).Scan(&u.ID, &u.Username, &u.PasswordHash, &u.DisplayName, &u.Role, &u.TOTPEnabled, &totpSecret, &u.CreatedAt, &lastLogin)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -40,9 +41,50 @@ func (d *Database) GetUserByUsername(username string) (*models.User, error) {
|
||||
if lastLogin.Valid {
|
||||
u.LastLogin = &lastLogin.Time
|
||||
}
|
||||
if totpSecret.Valid {
|
||||
u.TOTPSecret = totpSecret.String
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
func (d *Database) GetUserByID(id int) (*models.User, error) {
|
||||
var u models.User
|
||||
var lastLogin sql.NullTime
|
||||
var totpSecret sql.NullString
|
||||
err := d.db.QueryRow(
|
||||
"SELECT id, username, password_hash, display_name, role, totp_enabled, totp_secret, created_at, last_login FROM users WHERE id = $1",
|
||||
id,
|
||||
).Scan(&u.ID, &u.Username, &u.PasswordHash, &u.DisplayName, &u.Role, &u.TOTPEnabled, &totpSecret, &u.CreatedAt, &lastLogin)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if lastLogin.Valid {
|
||||
u.LastLogin = &lastLogin.Time
|
||||
}
|
||||
if totpSecret.Valid {
|
||||
u.TOTPSecret = totpSecret.String
|
||||
}
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
func (d *Database) SetTOTPSecret(userID int, secret string) error {
|
||||
_, err := d.db.Exec("UPDATE users SET totp_secret = $1, totp_enabled = false WHERE id = $2", secret, userID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *Database) EnableTOTP(userID int) error {
|
||||
_, err := d.db.Exec("UPDATE users SET totp_enabled = true WHERE id = $1", userID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *Database) DisableTOTP(userID int) error {
|
||||
_, err := d.db.Exec("UPDATE users SET totp_enabled = false, totp_secret = NULL WHERE id = $1", userID)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *Database) GetUsers() ([]models.User, error) {
|
||||
rows, err := d.db.Query("SELECT id, username, display_name, role, created_at, last_login FROM users ORDER BY username")
|
||||
if err != nil {
|
||||
|
||||
@@ -9,11 +9,13 @@ require (
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc // indirect
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/pquerna/otp v1.5.0 // indirect
|
||||
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
||||
golang.org/x/crypto v0.48.0 // indirect
|
||||
golang.org/x/sync v0.19.0 // indirect
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc h1:biVzkmvwrH8WK8raXaxBx6fRVTlJILwEwQGL1I/ByEI=
|
||||
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
@@ -20,6 +22,8 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pquerna/otp v1.5.0 h1:NMMR+WrmaqXU4EzdGJEE1aUUI0AMRzsp96fFFWNPwxs=
|
||||
github.com/pquerna/otp v1.5.0/go.mod h1:dkJfzwRKNiegxyNb54X/3fLwhCynbMspSyWKnvi1AEg=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
|
||||
@@ -84,9 +84,15 @@ func main() {
|
||||
// GET /api/v1/auth/me braucht JWT
|
||||
protectedMux.HandleFunc("GET /api/v1/auth/me", authHandler.Me)
|
||||
|
||||
// Geschuetzte 2FA-Routen
|
||||
protectedMux.HandleFunc("POST /api/v1/auth/2fa/setup", authHandler.TOTPSetup)
|
||||
protectedMux.HandleFunc("POST /api/v1/auth/2fa/confirm", authHandler.TOTPConfirm)
|
||||
protectedMux.HandleFunc("POST /api/v1/auth/2fa/disable", authHandler.TOTPDisable)
|
||||
|
||||
// Combined router: auth routes ungeschuetzt, rest mit DB-basierter Auth
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("POST /api/v1/auth/login", authMux)
|
||||
mux.Handle("POST /api/v1/auth/2fa/validate", authMux) // 2FA-Schritt 2 ebenfalls ohne JWT
|
||||
mux.Handle("/", api.CombinedAuthWithCache(apiKeyCache, authHandler, protectedMux))
|
||||
|
||||
// Middleware-Chain: CORS -> Logging -> Handler
|
||||
|
||||
@@ -21,6 +21,8 @@ type Task struct {
|
||||
HealthCheck bool `json:"health_check"`
|
||||
HealthCheckTimeout int `json:"health_check_timeout"`
|
||||
SecurityOnly bool `json:"security_only,omitempty"`
|
||||
Script string `json:"script,omitempty"`
|
||||
ScriptTimeout int `json:"script_timeout,omitempty"`
|
||||
WebhookURL string `json:"webhook_url,omitempty"`
|
||||
WebhookSent bool `json:"webhook_sent"`
|
||||
WebhookResponse string `json:"webhook_response,omitempty"`
|
||||
|
||||
+26
-3
@@ -8,6 +8,8 @@ type User struct {
|
||||
PasswordHash string `json:"-"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Role string `json:"role"`
|
||||
TOTPEnabled bool `json:"totp_enabled"`
|
||||
TOTPSecret string `json:"-"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
LastLogin *time.Time `json:"last_login,omitempty"`
|
||||
}
|
||||
@@ -18,7 +20,28 @@ type LoginRequest struct {
|
||||
}
|
||||
|
||||
type LoginResponse struct {
|
||||
Token string `json:"token"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
User User `json:"user"`
|
||||
Token string `json:"token,omitempty"`
|
||||
ExpiresAt string `json:"expires_at,omitempty"`
|
||||
User *User `json:"user,omitempty"`
|
||||
TOTPRequired bool `json:"totp_required,omitempty"`
|
||||
TOTPToken string `json:"totp_token,omitempty"`
|
||||
}
|
||||
|
||||
type TOTPValidateRequest struct {
|
||||
TOTPToken string `json:"totp_token"`
|
||||
Code string `json:"code"`
|
||||
}
|
||||
|
||||
type TOTPSetupResponse struct {
|
||||
Secret string `json:"secret"`
|
||||
URI string `json:"uri"`
|
||||
}
|
||||
|
||||
type TOTPConfirmRequest struct {
|
||||
Code string `json:"code"`
|
||||
}
|
||||
|
||||
type TOTPDisableRequest struct {
|
||||
Password string `json:"password"`
|
||||
Code string `json:"code"`
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user