/ pkg / web / ssh.go
ssh.go
 1  package web
 2  
 3  import (
 4  	"encoding/json"
 5  	"io"
 6  	"net/http"
 7  	"strings"
 8  
 9  	dogeboxd "github.com/dogeorg/dogeboxd/pkg"
10  )
11  
12  type SetSSHStateRequest struct {
13  	Enabled bool `json:"enabled"`
14  }
15  
16  type AddSSHKeyRequest struct {
17  	Key string `json:"key"`
18  }
19  
20  func (t api) getSSHState(w http.ResponseWriter, r *http.Request) {
21  	dbxState := t.sm.Get().Dogebox
22  
23  	sendResponse(w, map[string]bool{"enabled": dbxState.SSH.Enabled})
24  }
25  
26  func (t api) setSSHState(w http.ResponseWriter, r *http.Request) {
27  	body, err := io.ReadAll(r.Body)
28  	if err != nil {
29  		sendErrorResponse(w, http.StatusBadRequest, "Error reading request body")
30  		return
31  	}
32  
33  	var req SetSSHStateRequest
34  	if err := json.Unmarshal(body, &req); err != nil {
35  		sendErrorResponse(w, http.StatusBadRequest, "Error unmarshalling JSON")
36  		return
37  	}
38  
39  	var action dogeboxd.Action
40  	if req.Enabled {
41  		action = dogeboxd.EnableSSH{}
42  	} else {
43  		action = dogeboxd.DisableSSH{}
44  	}
45  
46  	id := t.dbx.AddAction(action)
47  	sendResponse(w, map[string]string{"id": id})
48  }
49  
50  func (t api) listSSHKeys(w http.ResponseWriter, r *http.Request) {
51  	keys, err := t.dbx.SystemUpdater.ListSSHKeys()
52  	if err != nil {
53  		sendErrorResponse(w, http.StatusInternalServerError, "Error listing SSH keys")
54  		return
55  	}
56  
57  	sendResponse(w, map[string]any{"keys": keys})
58  }
59  
60  func (t api) addSSHKey(w http.ResponseWriter, r *http.Request) {
61  	body, err := io.ReadAll(r.Body)
62  	if err != nil {
63  		sendErrorResponse(w, http.StatusBadRequest, "Error reading request body")
64  		return
65  	}
66  
67  	var req AddSSHKeyRequest
68  	if err := json.Unmarshal(body, &req); err != nil {
69  		sendErrorResponse(w, http.StatusBadRequest, "Error unmarshalling JSON")
70  		return
71  	}
72  
73  	req.Key = strings.ReplaceAll(req.Key, "\n", "")
74  	req.Key = strings.ReplaceAll(req.Key, "\r", "")
75  
76  	if req.Key == "" {
77  		sendErrorResponse(w, http.StatusBadRequest, "SSH key is required")
78  		return
79  	}
80  
81  	id := t.dbx.AddAction(dogeboxd.AddSSHKey{Key: req.Key})
82  	sendResponse(w, map[string]string{"id": id})
83  }
84  
85  func (t api) removeSSHKey(w http.ResponseWriter, r *http.Request) {
86  	keyId := r.PathValue("id")
87  	if keyId == "" {
88  		sendErrorResponse(w, http.StatusBadRequest, "Key ID is required")
89  		return
90  	}
91  
92  	id := t.dbx.AddAction(dogeboxd.RemoveSSHKey{ID: keyId})
93  	sendResponse(w, map[string]string{"id": id})
94  }