| Giorgi Lekveishvili | 12850ee | 2023-06-22 13:11:17 +0400 | [diff] [blame^] | 1 | package welcome |
| 2 | |
| 3 | import ( |
| 4 | "embed" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "log" |
| 8 | "net/http" |
| 9 | |
| 10 | "github.com/labstack/echo/v4" |
| 11 | |
| 12 | "github.com/giolekva/pcloud/core/installer" |
| 13 | ) |
| 14 | |
| 15 | //go:embed index.html |
| 16 | var indexHtml string |
| 17 | |
| 18 | //go:embed static/* |
| 19 | var staticAssets embed.FS |
| 20 | |
| 21 | type Server struct { |
| 22 | port int |
| 23 | repo installer.RepoIO |
| 24 | } |
| 25 | |
| 26 | func NewServer(port int, repo installer.RepoIO) *Server { |
| 27 | return &Server{ |
| 28 | port, |
| 29 | repo, |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | func (s *Server) Start() { |
| 34 | e := echo.New() |
| 35 | e.StaticFS("/static", echo.MustSubFS(staticAssets, "static")) |
| 36 | e.POST("/create-admin-account", s.createAdminAccount) |
| 37 | e.GET("/", s.createAdminAccountForm) |
| 38 | log.Fatal(e.Start(fmt.Sprintf(":%d", s.port))) |
| 39 | } |
| 40 | |
| 41 | func (s *Server) createAdminAccountForm(c echo.Context) error { |
| 42 | return c.HTML(http.StatusOK, indexHtml) |
| 43 | } |
| 44 | |
| 45 | type createAdminAccountReq struct { |
| 46 | Username string `json:"username,omitempty"` |
| 47 | Password string `json:"password,omitempty"` // TODO(giolekva): actually use this |
| 48 | GandiAPIToken string `json:"gandiAPIToken,omitempty"` |
| 49 | SecretToken string `json:"secretToken,omitempty"` |
| 50 | } |
| 51 | |
| 52 | func (s *Server) createAdminAccount(c echo.Context) error { |
| 53 | var req createAdminAccountReq |
| 54 | if err := json.NewDecoder(c.Request().Body).Decode(&req); err != nil { |
| 55 | return err |
| 56 | } |
| 57 | // TODO(giolekva): accounts-ui create user req |
| 58 | { |
| 59 | appManager, err := installer.NewAppManager(s.repo) |
| 60 | if err != nil { |
| 61 | return err |
| 62 | } |
| 63 | appsRepo := installer.NewInMemoryAppRepository(installer.CreateAllApps()) |
| 64 | { |
| 65 | app, err := appsRepo.Find("certificate-issuer-private") |
| 66 | if err != nil { |
| 67 | return err |
| 68 | } |
| 69 | if err := appManager.Install(*app, map[string]any{ |
| 70 | "GandiAPIToken": req.GandiAPIToken, |
| 71 | }); err != nil { |
| 72 | return err |
| 73 | } |
| 74 | } |
| 75 | { |
| 76 | app, err := appsRepo.Find("tailscale-proxy") |
| 77 | if err != nil { |
| 78 | return err |
| 79 | } |
| 80 | if err := appManager.Install(*app, map[string]any{ |
| 81 | "Username": req.Username, |
| 82 | "IPSubnet": "10.1.0.0/24", // TODO(giolekva): this should be taken from the config generated during new env creation |
| 83 | }); err != nil { |
| 84 | return err |
| 85 | } |
| 86 | // TODO(giolekva): headscale accept routes |
| 87 | } |
| 88 | } |
| 89 | return c.String(http.StatusOK, "OK") |
| 90 | } |