gosscms/admin_endpoints.go
2017-08-29 14:33:09 -05:00

104 lines
2.5 KiB
Go

package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
"github.com/gorilla/sessions"
)
func initAdminRequest(w http.ResponseWriter, req *http.Request) *pageData {
p := InitPageData(w, req)
return p
}
// Main admin handler, routes the request based on the category
func handleAdmin(w http.ResponseWriter, req *http.Request) {
page := initAdminRequest(w, req)
if !page.LoggedIn {
page.SubTitle = "Admin Login"
page.show("admin-login.html", w)
} else {
vars := mux.Vars(req)
adminCategory := vars["category"]
switch adminCategory {
case "users":
handleAdminUsers(w, req, page)
default:
page.show("admin-main.html", w)
}
}
}
func AdminAssetHandler(w http.ResponseWriter, r *http.Request) {
http.FileServer(FS(site.DevMode))
}
func InitPageData(w http.ResponseWriter, req *http.Request) *pageData {
if site.DevMode {
w.Header().Set("Cache-Control", "no-cache")
}
p := new(pageData)
// Get session
var err error
var s *sessions.Session
if s, err = sessionStore.Get(req, site.SessionName); err != nil {
http.Error(w, err.Error(), 500)
return p
}
p.session = new(pageSession)
p.session.session = s
p.session.req = req
p.session.w = w
// First check if we're logged in
userEmail, _ := p.session.getStringValue("email")
// With a valid account
p.LoggedIn = dbIsValidUserEmail(userEmail)
p.Site = site
p.SubTitle = "Administration"
p.Stylesheets = make([]string, 0, 0)
p.Stylesheets = append(p.Stylesheets, "/admin/assets/vendor/font-awesome/css/font-awesome.min.css")
p.Stylesheets = append(p.Stylesheets, "/admin/assets/css/main.css")
p.HeaderScripts = make([]string, 0, 0)
p.Scripts = make([]string, 0, 0)
p.Scripts = append(p.Scripts, "/admin/assets/js/main.js")
p.FlashMessage, p.FlashClass = p.session.getFlashMessage()
if p.FlashClass == "" {
p.FlashClass = "hidden"
}
// Build the menu
if p.LoggedIn {
p.Menu = append(p.Menu, menuItem{"Admin", "/admin", "fa-key"})
p.BottomMenu = append(p.BottomMenu, menuItem{"Users", "/admin/users", "fa-user"})
p.BottomMenu = append(p.BottomMenu, menuItem{"Logout", "/admin/dologout", "fa-sign-out"})
} else {
p.BottomMenu = append(p.BottomMenu, menuItem{"Admin", "/admin", "fa-sign-in"})
}
return p
}
func (p *pageData) show(tmplName string, w http.ResponseWriter) error {
for _, tmpl := range []string{
"htmlheader.html",
"header.html",
tmplName,
"footer.html",
"htmlfooter.html",
} {
if err := outputTemplate(tmpl, p, w); err != nil {
fmt.Printf("%s\n", err)
return err
}
}
return nil
}