package app import ( md "farga/app/middleware" "farga/app/templating" "farga/db/types" "farga/lib" hk "farga/lib/hackatime" "net/http" "github.com/google/uuid" ) type BranchForm struct { Branch string `form:"branch" validate:"required,max=100"` } type AddSSHKeyForm struct { Name string `form:"name" validate:"required,max=100"` Key string `form:"key" validate:"required"` } type DeleteSSHKeyForm struct { ID string `form:"key" validate:"required,uuid,max=100"` } func (a *App) UserConfigHandler(w http.ResponseWriter, r *http.Request) { user := r.Context().Value(lib.UserKey).(*types.User) var hkUser *hk.User var err error if user.HackatimeToken != "" && r.URL.Query().Get("err") != "WarnOffline" { hkUser, err = hk.UserInfo(user.HackatimeToken) if err != nil { http.Redirect(w, r, "?err=WarnOffline", http.StatusSeeOther) return } } templating.Render(w, r, "base", "config", map[string]any{"User": user, "Config": user.Config, "Hackatime": hkUser}) } func (a *App) branchHandler(w http.ResponseWriter, r *http.Request) { form, _ := md.Form[BranchForm](r) user := r.Context().Value(lib.UserKey).(*types.User) branch := form.Branch if lib.GitBranchRegex.MatchString(branch) { a.Store.UpdateUserConfig(user.ID, types.UserConfig{GitDefaultBranch: branch}) http.Redirect(w, r, "/config?msg=UpdateSuccess", http.StatusFound) } else if len(branch) > lib.GitBranchMaxLen { // ik it's duplicated, but in case I ever forget IT'LL BE HERE. http.Redirect(w, r, "/config?err=GitBranchTooLong", http.StatusFound) } else if len(branch) < lib.GitBranchMinLen { http.Redirect(w, r, "/config?err=GitBranchTooShort", http.StatusFound) } else { http.Redirect(w, r, "/config?err=GitInvalidBranchName", http.StatusFound) } } func (a *App) newSSHKeyHandler(w http.ResponseWriter, r *http.Request) { form, _ := md.Form[AddSSHKeyForm](r) name := form.Name user, ok := r.Context().Value(lib.UserKey).(*types.User) if !ok { http.Error(w, "Bad Request: Not logged in.", http.StatusBadRequest) return } key, err := lib.ParseKey(form.Key) if err != nil { http.Error(w, "Malformed SSH Key", http.StatusBadRequest) return } _, err = a.Store.NewPubKey(name, key, user.ID) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } http.Redirect(w, r, "/config?msg=GeneralSuccess", http.StatusFound) } func (a *App) deleteSSHKeyHandler(w http.ResponseWriter, r *http.Request) { form, _ := md.Form[DeleteSSHKeyForm](r) keyId, err := uuid.Parse(form.ID) user := r.Context().Value(lib.UserKey).(*types.User) if err != nil { http.Error(w, "Invalid key UUID.", http.StatusBadRequest) return } err = a.Store.DeletePubKey(keyId, user.ID) if err != nil { http.Error(w, "500 Something went wrong on our end.", http.StatusInternalServerError) return } http.Redirect(w, r, "/config?msg=DeleteSuccess", http.StatusFound) }