gophertype/pkg/controllers/initial_setup.go

75 lines
1.9 KiB
Go

package controllers
import (
"errors"
"fmt"
"net/http"
"git.kirsle.net/apps/gophertype/pkg/constants"
"git.kirsle.net/apps/gophertype/pkg/glue"
"git.kirsle.net/apps/gophertype/pkg/middleware"
"git.kirsle.net/apps/gophertype/pkg/models"
"git.kirsle.net/apps/gophertype/pkg/responses"
"github.com/gorilla/mux"
)
func init() {
glue.Register(glue.Endpoint{
Path: "/admin/setup",
Methods: []string{"GET", "POST"},
Middleware: []mux.MiddlewareFunc{
middleware.ExampleMiddleware,
},
Handler: func(w http.ResponseWriter, r *http.Request) {
// See if we already have an admin account.
if _, err := models.FirstAdmin(); err == nil {
responses.Panic(w, http.StatusForbidden, "This site is already initialized.")
return
}
// Template variables.
v := map[string]interface{}{}
// POST handler: create the admin account.
if r.Method == http.MethodPost {
var (
username = r.FormValue("username")
displayName = r.FormValue("name")
password = r.FormValue("password")
password2 = r.FormValue("password2")
)
// Username and display name validation happens in CreateUser.
// Validate the passwords match here.
if len(password) < constants.PasswordMinLength {
v["Error"] = fmt.Errorf("your password is too short (must be %d+ characters)", constants.PasswordMinLength)
}
if password != password2 {
v["Error"] = errors.New("your passwords don't match")
} else {
admin := models.User{
Username: username,
Name: displayName,
IsAdmin: true,
}
admin.SetPassword(password)
if err := models.CreateUser(admin); err != nil {
v["Error"] = err
} else {
// Admin created! Make the default config.
cfg := models.GetSettings()
cfg.Save()
w.Write([]byte("Success"))
return
}
}
}
responses.RenderTemplate(w, r, "_builtin/initial_setup.gohtml", v)
},
})
}