blob: 198f637add94a1f527223f005aa86d4087f29fed [file] [log] [blame]
Giorgi Lekveishvili12850ee2023-06-22 13:11:17 +04001package welcome
2
3import (
Giorgi Lekveishvilic89b9002023-12-21 13:09:26 +04004 "bytes"
Giorgi Lekveishvili12850ee2023-06-22 13:11:17 +04005 "embed"
6 "encoding/json"
7 "fmt"
DTabidze52593392024-03-08 12:53:20 +04008 "html/template"
Giorgi Lekveishvilic89b9002023-12-21 13:09:26 +04009 "io"
Giorgi Lekveishvili12850ee2023-06-22 13:11:17 +040010 "log"
11 "net/http"
gio4784f8e2024-08-01 15:20:12 +040012 "os"
Giorgi Lekveishvili12850ee2023-06-22 13:11:17 +040013
Giorgi Lekveishvili123a3672023-12-04 13:01:29 +040014 "github.com/gorilla/mux"
Giorgi Lekveishvili12850ee2023-06-22 13:11:17 +040015
16 "github.com/giolekva/pcloud/core/installer"
gio59946282024-10-07 12:55:51 +040017 "github.com/giolekva/pcloud/core/installer/server"
gioe72b54f2024-04-22 10:44:41 +040018 "github.com/giolekva/pcloud/core/installer/soft"
Giorgi Lekveishvili12850ee2023-06-22 13:11:17 +040019)
20
gio59946282024-10-07 12:55:51 +040021//go:embed templates/*
22var tmpls embed.FS
Giorgi Lekveishvili83b72192024-03-11 18:36:14 +040023
Giorgi Lekveishvili12850ee2023-06-22 13:11:17 +040024//go:embed static/*
25var staticAssets embed.FS
26
gio59946282024-10-07 12:55:51 +040027type templates struct {
giodd213152024-09-27 11:26:59 +020028 createAccount *template.Template
29 createAccountSuccess *template.Template
30}
31
gio59946282024-10-07 12:55:51 +040032func parseTemplatesWelcome(fs embed.FS) (templates, error) {
33 base, err := template.New("base.html").ParseFS(fs, "templates/base.html")
giodd213152024-09-27 11:26:59 +020034 if err != nil {
gio59946282024-10-07 12:55:51 +040035 return templates{}, err
giodd213152024-09-27 11:26:59 +020036 }
37 parse := func(path string) (*template.Template, error) {
38 if b, err := base.Clone(); err != nil {
39 return nil, err
40 } else {
41 return b.ParseFS(fs, path)
42 }
43 }
gio59946282024-10-07 12:55:51 +040044 createAccount, err := parse("templates/create-account.html")
giodd213152024-09-27 11:26:59 +020045 if err != nil {
gio59946282024-10-07 12:55:51 +040046 return templates{}, err
giodd213152024-09-27 11:26:59 +020047 }
gio59946282024-10-07 12:55:51 +040048 createAccountSuccess, err := parse("templates/create-account-success.html")
giodd213152024-09-27 11:26:59 +020049 if err != nil {
gio59946282024-10-07 12:55:51 +040050 return templates{}, err
giodd213152024-09-27 11:26:59 +020051 }
gio59946282024-10-07 12:55:51 +040052 return templates{createAccount, createAccountSuccess}, nil
giodd213152024-09-27 11:26:59 +020053}
54
Giorgi Lekveishvili12850ee2023-06-22 13:11:17 +040055type Server struct {
gio2728e402024-08-01 18:14:21 +040056 port int
57 repo soft.RepoIO
58 nsCreator installer.NamespaceCreator
59 hf installer.HelmFetcher
60 createAccountAddr string
61 loginAddr string
62 membershipsAddr string
gio59946282024-10-07 12:55:51 +040063 tmpl templates
Giorgi Lekveishvili12850ee2023-06-22 13:11:17 +040064}
65
Giorgi Lekveishvilic89b9002023-12-21 13:09:26 +040066func NewServer(
67 port int,
gioe72b54f2024-04-22 10:44:41 +040068 repo soft.RepoIO,
Giorgi Lekveishvilic89b9002023-12-21 13:09:26 +040069 nsCreator installer.NamespaceCreator,
giof8843412024-05-22 16:38:05 +040070 hf installer.HelmFetcher,
Giorgi Lekveishvilic89b9002023-12-21 13:09:26 +040071 createAccountAddr string,
Giorgi Lekveishvili83b72192024-03-11 18:36:14 +040072 loginAddr string,
gio2728e402024-08-01 18:14:21 +040073 membershipsAddr string,
giodd213152024-09-27 11:26:59 +020074) (*Server, error) {
gio59946282024-10-07 12:55:51 +040075 tmplts, err := parseTemplatesWelcome(tmpls)
giodd213152024-09-27 11:26:59 +020076 if err != nil {
77 return nil, err
78 }
Giorgi Lekveishvili12850ee2023-06-22 13:11:17 +040079 return &Server{
80 port,
81 repo,
Giorgi Lekveishvili7fb28bf2023-06-24 19:51:16 +040082 nsCreator,
giof8843412024-05-22 16:38:05 +040083 hf,
Giorgi Lekveishvilic89b9002023-12-21 13:09:26 +040084 createAccountAddr,
Giorgi Lekveishvili83b72192024-03-11 18:36:14 +040085 loginAddr,
gio2728e402024-08-01 18:14:21 +040086 membershipsAddr,
giodd213152024-09-27 11:26:59 +020087 tmplts,
88 }, nil
Giorgi Lekveishvili12850ee2023-06-22 13:11:17 +040089}
90
91func (s *Server) Start() {
Giorgi Lekveishvili123a3672023-12-04 13:01:29 +040092 r := mux.NewRouter()
gio59946282024-10-07 12:55:51 +040093 r.PathPrefix("/static/").Handler(server.NewCachingHandler(http.FileServer(http.FS(staticAssets))))
Giorgi Lekveishvilid542b732024-03-25 18:17:39 +040094 r.Path("/").Methods("POST").HandlerFunc(s.createAccount)
95 r.Path("/").Methods("GET").HandlerFunc(s.createAccountForm)
Giorgi Lekveishvili123a3672023-12-04 13:01:29 +040096 http.Handle("/", r)
97 log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", s.port), nil))
Giorgi Lekveishvili12850ee2023-06-22 13:11:17 +040098}
99
Giorgi Lekveishvilid542b732024-03-25 18:17:39 +0400100func (s *Server) createAccountForm(w http.ResponseWriter, r *http.Request) {
giodd213152024-09-27 11:26:59 +0200101 s.renderRegistrationForm(w, formData{})
DTabidze52593392024-03-08 12:53:20 +0400102}
103
104type formData struct {
105 UsernameErrors []string
106 PasswordErrors []string
107 Data createAccountReq
Giorgi Lekveishvili12850ee2023-06-22 13:11:17 +0400108}
109
giodd213152024-09-27 11:26:59 +0200110type cpFormData struct {
111 UsernameErrors []string
112 PasswordErrors []string
113 Password string
114}
115
Giorgi Lekveishvili123a3672023-12-04 13:01:29 +0400116type createAccountReq struct {
Giorgi Lekveishvili260a97d2023-12-08 15:04:16 +0400117 Username string `json:"username,omitempty"`
Giorgi Lekveishvilic89b9002023-12-21 13:09:26 +0400118 Password string `json:"password,omitempty"`
Giorgi Lekveishvili260a97d2023-12-08 15:04:16 +0400119 SecretToken string `json:"secretToken,omitempty"`
Giorgi Lekveishvili12850ee2023-06-22 13:11:17 +0400120}
121
Giorgi Lekveishvilic89b9002023-12-21 13:09:26 +0400122type apiCreateAccountReq struct {
123 Username string `json:"username,omitempty"`
124 Password string `json:"password,omitempty"`
125}
126
DTabidze52593392024-03-08 12:53:20 +0400127type ValidationError struct {
128 Field string `json:"field"`
129 Message string `json:"message"`
130}
131
132type ErrorResponse struct {
133 Errors []ValidationError `json:"errors"`
134}
135
Giorgi Lekveishvili123a3672023-12-04 13:01:29 +0400136func extractReq(r *http.Request) (createAccountReq, error) {
137 var req createAccountReq
Giorgi Lekveishvili6b887be2023-06-22 14:38:19 +0400138 if err := func() error {
139 var err error
Giorgi Lekveishvili123a3672023-12-04 13:01:29 +0400140 if err = r.ParseForm(); err != nil {
Giorgi Lekveishvili6b887be2023-06-22 14:38:19 +0400141 return err
142 }
gio59946282024-10-07 12:55:51 +0400143 if req.Username, err = server.GetFormValue(r.PostForm, "username"); err != nil {
Giorgi Lekveishvili6b887be2023-06-22 14:38:19 +0400144 return err
145 }
gio59946282024-10-07 12:55:51 +0400146 if req.Password, err = server.GetFormValue(r.PostForm, "password"); err != nil {
Giorgi Lekveishvili6b887be2023-06-22 14:38:19 +0400147 return err
148 }
gio59946282024-10-07 12:55:51 +0400149 if req.SecretToken, err = server.GetFormValue(r.PostForm, "secret-token"); err != nil {
Giorgi Lekveishvili6b887be2023-06-22 14:38:19 +0400150 return err
151 }
152 return nil
153 }(); err != nil {
Giorgi Lekveishvili123a3672023-12-04 13:01:29 +0400154 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
155 return createAccountReq{}, err
Giorgi Lekveishvili6b887be2023-06-22 14:38:19 +0400156 }
Giorgi Lekveishvili12850ee2023-06-22 13:11:17 +0400157 }
Giorgi Lekveishvili123a3672023-12-04 13:01:29 +0400158 return req, nil
159}
160
giodd213152024-09-27 11:26:59 +0200161func (s *Server) renderRegistrationForm(w http.ResponseWriter, data formData) {
162 if err := s.tmpl.createAccount.Execute(w, data); err != nil {
DTabidze52593392024-03-08 12:53:20 +0400163 http.Error(w, err.Error(), http.StatusInternalServerError)
164 return
165 }
166}
167
giodd213152024-09-27 11:26:59 +0200168func (s *Server) renderRegistrationSuccess(w http.ResponseWriter, loginAddr string) {
Giorgi Lekveishvili83b72192024-03-11 18:36:14 +0400169 data := struct {
170 LoginAddr string
171 }{
172 LoginAddr: loginAddr,
173 }
giodd213152024-09-27 11:26:59 +0200174 if err := s.tmpl.createAccountSuccess.Execute(w, data); err != nil {
Giorgi Lekveishvili83b72192024-03-11 18:36:14 +0400175 http.Error(w, err.Error(), http.StatusInternalServerError)
176 return
177 }
178}
179
Giorgi Lekveishvilid542b732024-03-25 18:17:39 +0400180func (s *Server) createAccount(w http.ResponseWriter, r *http.Request) {
Giorgi Lekveishvili39913692023-12-05 08:58:08 +0400181 req, err := extractReq(r)
182 if err != nil {
183 http.Error(w, err.Error(), http.StatusInternalServerError)
184 return
185 }
Giorgi Lekveishvilic89b9002023-12-21 13:09:26 +0400186 {
187 var buf bytes.Buffer
188 cr := apiCreateAccountReq{req.Username, req.Password}
189 if err := json.NewEncoder(&buf).Encode(cr); err != nil {
190 http.Error(w, err.Error(), http.StatusInternalServerError)
191 return
192 }
193 resp, err := http.Post(s.createAccountAddr, "application/json", &buf)
194 if err != nil {
Giorgi Lekveishvili83399052024-02-14 13:27:30 +0400195 var respBody bytes.Buffer
196 if _, err := io.Copy(&respBody, resp.Body); err != nil {
197 http.Error(w, err.Error(), http.StatusInternalServerError)
198 }
199 respStr := respBody.String()
200 log.Println(respStr)
201 http.Error(w, respStr, http.StatusInternalServerError)
Giorgi Lekveishvilic89b9002023-12-21 13:09:26 +0400202 return
203 }
Giorgi Lekveishvilic89b9002023-12-21 13:09:26 +0400204 if resp.StatusCode != http.StatusOK {
DTabidze52593392024-03-08 12:53:20 +0400205 var errResponse ErrorResponse
206 if err := json.NewDecoder(resp.Body).Decode(&errResponse); err != nil {
207 http.Error(w, "Error Decoding JSON", http.StatusInternalServerError)
208 return
209 }
210 var usernameErrors, passwordErrors []string
211 for _, err := range errResponse.Errors {
212 if err.Field == "username" {
213 usernameErrors = append(usernameErrors, err.Message)
214 }
215 if err.Field == "password" {
216 passwordErrors = append(passwordErrors, err.Message)
217 }
218 }
giodd213152024-09-27 11:26:59 +0200219 s.renderRegistrationForm(w, formData{
DTabidze52593392024-03-08 12:53:20 +0400220 usernameErrors,
221 passwordErrors,
222 req,
223 })
Giorgi Lekveishvilic89b9002023-12-21 13:09:26 +0400224 return
225 }
226 }
gio2728e402024-08-01 18:14:21 +0400227 if err := s.createUser(req.Username); err != nil {
Giorgi Lekveishvilid542b732024-03-25 18:17:39 +0400228 http.Error(w, err.Error(), http.StatusInternalServerError)
229 return
230 }
giodd213152024-09-27 11:26:59 +0200231 s.renderRegistrationSuccess(w, s.loginAddr)
Giorgi Lekveishvili12850ee2023-06-22 13:11:17 +0400232}
Giorgi Lekveishvilid542b732024-03-25 18:17:39 +0400233
gio2728e402024-08-01 18:14:21 +0400234type firstAccount struct {
Giorgi Lekveishvilid542b732024-03-25 18:17:39 +0400235 Created bool `json:"created"`
gio2728e402024-08-01 18:14:21 +0400236 Domain string `json:"domain"`
Giorgi Lekveishvilid542b732024-03-25 18:17:39 +0400237 Groups []string `json:"groups"`
238}
239
240type initRequest struct {
gio2728e402024-08-01 18:14:21 +0400241 User string `json:"user"`
242 Email string `json:"email"`
Giorgi Lekveishvilid542b732024-03-25 18:17:39 +0400243 Groups []string `json:"groups"`
244}
245
gio2728e402024-08-01 18:14:21 +0400246type createUserRequest struct {
247 User string `json:"user"`
248 Email string `json:"email"`
249}
250
251func (s *Server) createUser(username string) error {
giob4a3a192024-08-19 09:55:47 +0400252 _, err := s.repo.Do(func(r soft.RepoFS) (string, error) {
gio2728e402024-08-01 18:14:21 +0400253 var fa firstAccount
gioe72b54f2024-04-22 10:44:41 +0400254 if err := soft.ReadYaml(r, "first-account.yaml", &fa); err != nil {
gio3af43942024-04-16 08:13:50 +0400255 return "", err
256 }
gio2728e402024-08-01 18:14:21 +0400257 var resp *http.Response
258 var err error
gio3af43942024-04-16 08:13:50 +0400259 if fa.Created {
gio2728e402024-08-01 18:14:21 +0400260 req := createUserRequest{username, fmt.Sprintf("%s@%s", username, fa.Domain)}
261 var buf bytes.Buffer
262 if err := json.NewEncoder(&buf).Encode(req); err != nil {
263 return "", err
264 }
265 resp, err = http.Post(
266 fmt.Sprintf("%s/api/users", s.membershipsAddr),
267 "applications/json",
268 &buf,
269 )
270 } else {
271 req := initRequest{username, fmt.Sprintf("%s@%s", username, fa.Domain), fa.Groups}
272 var buf bytes.Buffer
273 if err := json.NewEncoder(&buf).Encode(req); err != nil {
274 return "", err
275 }
276 resp, err = http.Post(
277 fmt.Sprintf("%s/api/init", s.membershipsAddr),
278 "applications/json",
279 &buf,
280 )
281 fa.Created = true
282 if err := soft.WriteYaml(r, "first-account.yaml", fa); err != nil {
283 return "", err
284 }
gio3af43942024-04-16 08:13:50 +0400285 }
gio4784f8e2024-08-01 15:20:12 +0400286 if err != nil {
gio3af43942024-04-16 08:13:50 +0400287 return "", err
288 }
gio4784f8e2024-08-01 15:20:12 +0400289 defer resp.Body.Close()
290 fmt.Printf("Memberships resp: %d", resp.StatusCode)
291 io.Copy(os.Stdout, resp.Body)
gio2728e402024-08-01 18:14:21 +0400292 if resp.StatusCode != http.StatusOK {
293 return "", fmt.Errorf("memberships error")
gio3af43942024-04-16 08:13:50 +0400294 }
295 return "initialized groups for first account", nil
296 })
giob4a3a192024-08-19 09:55:47 +0400297 return err
Giorgi Lekveishvilid542b732024-03-25 18:17:39 +0400298}