|
1 | 1 | package session |
2 | 2 |
|
3 | | -/* TODO: watchdog for session */ |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "net/http" |
| 6 | + "time" |
| 7 | + |
| 8 | + "github.com/PythonHacker24/linux-acl-management-backend/internal/types" |
| 9 | + "github.com/google/uuid" |
| 10 | +) |
| 11 | + |
| 12 | +/* |
| 13 | + TODO: watchdog for session |
| 14 | + Live sessions and transactions can be montired through Redis and PostgreSQL |
| 15 | + the watchdog here shows the processing happening, which needs to be done in the |
| 16 | + later stages of development |
| 17 | +*/ |
| 18 | + |
| 19 | +/* frontend safe handler for issuing transaction */ |
| 20 | +func (m *Manager) IssueTransaction(w http.ResponseWriter, r *http.Request) { |
| 21 | + /* extract username from JWT Token */ |
| 22 | + username := r.Context().Value("username") |
| 23 | + |
| 24 | + /* acquire manager lock to access sessions map */ |
| 25 | + m.mutex.Lock() |
| 26 | + session := m.sessionsMap[username.(string)] |
| 27 | + m.mutex.Unlock() |
| 28 | + |
| 29 | + if session == nil { |
| 30 | + http.Error(w, "Session not found", http.StatusNotFound) |
| 31 | + return |
| 32 | + } |
| 33 | + |
| 34 | + /* acquire session lock for transaction operations */ |
| 35 | + session.Mutex.Lock() |
| 36 | + defer session.Mutex.Unlock() |
| 37 | + |
| 38 | + var req types.ScheduleTransactionRequest |
| 39 | + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { |
| 40 | + http.Error(w, "Invalid request", http.StatusBadRequest) |
| 41 | + return |
| 42 | + } |
| 43 | + |
| 44 | + tx := &types.Transaction{ |
| 45 | + ID: uuid.New(), |
| 46 | + SessionID: session.ID, |
| 47 | + Timestamp: time.Now(), |
| 48 | + Operation: req.Operation, |
| 49 | + TargetPath: req.TargetPath, |
| 50 | + Entries: req.Entries, |
| 51 | + Status: types.StatusPending, |
| 52 | + ExecutedBy: username.(string), |
| 53 | + } |
| 54 | + |
| 55 | + /* add transaction to session - session lock is already held */ |
| 56 | + if err := m.AddTransaction(session, tx); err != nil { |
| 57 | + http.Error(w, "Failed to add transaction", http.StatusInternalServerError) |
| 58 | + return |
| 59 | + } |
| 60 | + |
| 61 | + w.WriteHeader(http.StatusCreated) |
| 62 | + json.NewEncoder(w).Encode(map[string]string{ |
| 63 | + "message": "Transaction scheduled", |
| 64 | + "txn_id": tx.ID.String(), |
| 65 | + }) |
| 66 | +} |
0 commit comments