2017-10-08 04:48:58 +00:00
|
|
|
package core
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
2017-11-03 16:52:40 +00:00
|
|
|
"path/filepath"
|
2017-10-08 04:48:58 +00:00
|
|
|
|
|
|
|
"github.com/gorilla/mux"
|
2017-11-07 17:53:02 +00:00
|
|
|
"github.com/gorilla/sessions"
|
2017-11-03 16:52:40 +00:00
|
|
|
"github.com/kirsle/blog/core/jsondb"
|
2017-11-07 17:01:02 +00:00
|
|
|
"github.com/kirsle/blog/core/models/users"
|
2017-10-08 04:48:58 +00:00
|
|
|
"github.com/urfave/negroni"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Blog is the root application object that maintains the app configuration
|
|
|
|
// and helper objects.
|
|
|
|
type Blog struct {
|
2017-10-31 16:42:15 +00:00
|
|
|
Debug bool
|
|
|
|
|
2017-10-08 04:48:58 +00:00
|
|
|
// DocumentRoot is the core static files root; UserRoot masks over it.
|
|
|
|
DocumentRoot string
|
|
|
|
UserRoot string
|
|
|
|
|
2017-11-03 16:52:40 +00:00
|
|
|
DB *jsondb.DB
|
|
|
|
|
2017-10-08 04:48:58 +00:00
|
|
|
// Web app objects.
|
2017-11-07 17:53:02 +00:00
|
|
|
n *negroni.Negroni // Negroni middleware manager
|
|
|
|
r *mux.Router // Router
|
|
|
|
store sessions.Store
|
2017-10-08 04:48:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// New initializes the Blog application.
|
|
|
|
func New(documentRoot, userRoot string) *Blog {
|
|
|
|
blog := &Blog{
|
|
|
|
DocumentRoot: documentRoot,
|
|
|
|
UserRoot: userRoot,
|
2017-11-03 16:52:40 +00:00
|
|
|
DB: jsondb.New(filepath.Join(userRoot, ".private")),
|
2017-11-07 17:53:02 +00:00
|
|
|
|
|
|
|
store: sessions.NewCookieStore([]byte("secret-key")), // TODO configurable!
|
2017-10-08 04:48:58 +00:00
|
|
|
}
|
2017-11-03 16:52:40 +00:00
|
|
|
|
2017-11-07 17:01:02 +00:00
|
|
|
// Initialize all the models.
|
|
|
|
users.DB = blog.DB
|
|
|
|
|
2017-10-08 04:48:58 +00:00
|
|
|
r := mux.NewRouter()
|
|
|
|
blog.r = r
|
2017-10-31 16:42:15 +00:00
|
|
|
r.HandleFunc("/admin/setup", blog.SetupHandler)
|
2017-11-07 17:53:02 +00:00
|
|
|
r.HandleFunc("/login", blog.LoginHandler)
|
|
|
|
r.HandleFunc("/logout", blog.LogoutHandler)
|
2017-10-08 04:48:58 +00:00
|
|
|
r.HandleFunc("/", blog.PageHandler)
|
|
|
|
r.NotFoundHandler = http.HandlerFunc(blog.PageHandler)
|
|
|
|
|
|
|
|
n := negroni.New(
|
|
|
|
negroni.NewRecovery(),
|
|
|
|
negroni.NewLogger(),
|
|
|
|
)
|
|
|
|
blog.n = n
|
2017-11-07 17:53:02 +00:00
|
|
|
n.Use(negroni.HandlerFunc(blog.AuthMiddleware))
|
2017-10-08 04:48:58 +00:00
|
|
|
n.UseHandler(r)
|
|
|
|
|
|
|
|
return blog
|
|
|
|
}
|
|
|
|
|
|
|
|
// ListenAndServe begins listening on the given bind address.
|
|
|
|
func (b *Blog) ListenAndServe(address string) {
|
|
|
|
log.Info("Listening on %s", address)
|
|
|
|
http.ListenAndServe(address, b.n)
|
|
|
|
}
|