| Giorgi Lekveishvili | 52814d9 | 2023-06-15 19:30:32 +0400 | [diff] [blame] | 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "flag" |
| 6 | "fmt" |
| 7 | "log" |
| 8 | "net/http" |
| 9 | |
| 10 | "github.com/labstack/echo/v4" |
| 11 | ) |
| 12 | |
| 13 | var port = flag.Int("port", 3000, "Port to listen on") |
| 14 | var config = flag.String("config", "", "Path to headscale config") |
| 15 | |
| 16 | type server struct { |
| 17 | port int |
| 18 | client *client |
| 19 | } |
| 20 | |
| 21 | func newServer(port int, client *client) *server { |
| 22 | return &server{ |
| 23 | port, |
| 24 | client, |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | func (s *server) start() { |
| 29 | e := echo.New() |
| 30 | e.POST("/user/:user/preauthkey", s.createReusablePreAuthKey) |
| 31 | e.POST("/user", s.createUser) |
| 32 | e.POST("/routes/:id/enable", s.enableRoute) |
| 33 | log.Fatal(e.Start(fmt.Sprintf(":%d", s.port))) |
| 34 | } |
| 35 | |
| 36 | type createUserReq struct { |
| 37 | Name string `json:"name"` |
| 38 | } |
| 39 | |
| 40 | func (s *server) createUser(c echo.Context) error { |
| 41 | var req createUserReq |
| 42 | if err := json.NewDecoder(c.Request().Body).Decode(&req); err != nil { |
| 43 | return err |
| 44 | } |
| 45 | if err := s.client.createUser(req.Name); err != nil { |
| 46 | return err |
| 47 | } else { |
| 48 | return c.String(http.StatusOK, "") |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | func (s *server) createReusablePreAuthKey(c echo.Context) error { |
| 53 | if key, err := s.client.createPreAuthKey(c.Param("user")); err != nil { |
| 54 | return err |
| 55 | } else { |
| 56 | return c.String(http.StatusOK, key) |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | func (s *server) enableRoute(c echo.Context) error { |
| 61 | if err := s.client.enableRoute(c.Param("id")); err != nil { |
| 62 | return err |
| 63 | } else { |
| 64 | return c.String(http.StatusOK, "") |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | func main() { |
| 69 | flag.Parse() |
| 70 | c := newClient(*config) |
| 71 | s := newServer(*port, c) |
| 72 | s.start() |
| 73 | } |