diff --git a/cmd/gomvn/main.go b/cmd/gomvn/main.go index 01275d8..22449f4 100644 --- a/cmd/gomvn/main.go +++ b/cmd/gomvn/main.go @@ -1,9 +1,11 @@ package main import ( + "context" "errors" "flag" "github.com/1f349/gomvn" + "github.com/1f349/gomvn/database" "github.com/1f349/gomvn/routes" exitReload "github.com/MrMelon54/exit-reload" "gopkg.in/yaml.v3" @@ -53,6 +55,8 @@ func main() { if err != nil { log.Fatal("[GoMVN] Error: invalid database: ", err) } + mustHaveUser(db) + repoBasePath := filepath.Join(wd, "repositories") err = os.MkdirAll(repoBasePath, os.ModePerm) if err != nil { @@ -61,7 +65,7 @@ func main() { srv := &http.Server{ Addr: config.Listen, - Handler: routes.Router(db, config.Name, repoDir, config.Repository), + Handler: routes.Router(db, config.Name, repoBasePath, config.Repository), ReadTimeout: time.Minute, ReadHeaderTimeout: time.Minute, WriteTimeout: time.Minute, @@ -82,3 +86,20 @@ func main() { } }) } + +func mustHaveUser(db *database.Queries) error { + // user must exist + users, err := db.CountUsers(context.Background()) + if err != nil { + return err + } + if users == 0 { + _, err := db.CreateUser(context.Background(), database.CreateUserParams{ + Name: "admin", + Admin: true, + TokenHash: "1234", + }) + return err + } + return nil +} diff --git a/routes/router.go b/routes/router.go index bcde217..027a703 100644 --- a/routes/router.go +++ b/routes/router.go @@ -103,6 +103,11 @@ func (r *routeCtx) handlePut(rw http.ResponseWriter, req *http.Request, params h http.Error(rw, "404 Not Found", http.StatusNotFound) return } + err = os.MkdirAll(filepath.Dir(p), os.ModePerm) + if err != nil { + http.Error(rw, "500 Failed to create directory", http.StatusInternalServerError) + return + } create, err := os.Create(p) if err != nil { http.Error(rw, "500 Failed to open file", http.StatusInternalServerError)