2017-11-15 14:55:15 +00:00
|
|
|
package core
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
2018-02-10 02:46:58 +00:00
|
|
|
"github.com/kirsle/blog/core/internal/forms"
|
2018-02-10 18:08:45 +00:00
|
|
|
"github.com/kirsle/blog/core/internal/log"
|
2018-02-10 02:46:58 +00:00
|
|
|
"github.com/kirsle/blog/core/internal/models/settings"
|
|
|
|
"github.com/kirsle/blog/core/internal/models/users"
|
2018-02-10 18:08:45 +00:00
|
|
|
"github.com/kirsle/blog/core/internal/render"
|
2018-02-10 19:20:27 +00:00
|
|
|
"github.com/kirsle/blog/core/internal/responses"
|
2018-02-10 19:14:42 +00:00
|
|
|
"github.com/kirsle/blog/core/internal/sessions"
|
2017-11-15 14:55:15 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// SetupHandler is the initial blog setup route.
|
|
|
|
func (b *Blog) SetupHandler(w http.ResponseWriter, r *http.Request) {
|
2018-02-10 22:05:41 +00:00
|
|
|
form := &forms.Setup{}
|
|
|
|
vars := map[string]interface{}{
|
|
|
|
"Form": form,
|
2017-11-15 14:55:15 +00:00
|
|
|
}
|
|
|
|
|
2017-12-24 02:45:39 +00:00
|
|
|
// Reject if we're already set up.
|
|
|
|
s, _ := settings.Load()
|
|
|
|
if s.Initialized {
|
2018-02-10 19:20:27 +00:00
|
|
|
responses.FlashAndRedirect(w, r, "/", "This website has already been configured.")
|
2017-12-24 02:45:39 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-11-20 05:49:19 +00:00
|
|
|
if r.Method == http.MethodPost {
|
2018-02-10 22:05:41 +00:00
|
|
|
form.ParseForm(r)
|
2017-11-15 14:55:15 +00:00
|
|
|
err := form.Validate()
|
|
|
|
if err != nil {
|
2018-02-10 22:05:41 +00:00
|
|
|
vars["Error"] = err
|
2017-11-15 14:55:15 +00:00
|
|
|
} else {
|
|
|
|
// Save the site config.
|
|
|
|
log.Info("Creating default website config file")
|
|
|
|
s := settings.Defaults()
|
|
|
|
s.Save()
|
|
|
|
|
|
|
|
// Re-initialize the cookie store with the new secret key.
|
2018-02-10 19:14:42 +00:00
|
|
|
sessions.SetSecretKey([]byte(s.Security.SecretKey))
|
2017-11-15 14:55:15 +00:00
|
|
|
|
|
|
|
log.Info("Creating admin account %s", form.Username)
|
|
|
|
user := &users.User{
|
|
|
|
Username: form.Username,
|
|
|
|
Password: form.Password,
|
|
|
|
Admin: true,
|
|
|
|
Name: "Administrator",
|
|
|
|
}
|
|
|
|
err := users.Create(user)
|
|
|
|
if err != nil {
|
|
|
|
log.Error("Error: %v", err)
|
2018-02-10 22:05:41 +00:00
|
|
|
vars["Error"] = err
|
2017-11-15 14:55:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// All set!
|
|
|
|
b.Login(w, r, user)
|
2018-02-10 19:20:27 +00:00
|
|
|
responses.FlashAndRedirect(w, r, "/admin", "Admin user created and logged in.")
|
2017-11-15 14:55:15 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-10 22:05:41 +00:00
|
|
|
render.Template(w, r, "initial-setup", vars)
|
2017-11-15 14:55:15 +00:00
|
|
|
}
|