package main import ( "github.com/gorilla/mux" "github.com/gorilla/sessions" "net/http" "github.com/dballard/transmet/user" "fmt" "time" "io/ioutil" "regexp" "strings" "strconv" "github.com/dballard/transmet/categories" "github.com/dballard/transmet/news" "bytes" txtTemplate "text/template" "path" ) func GetFlashes(session *sessions.Session) map[string]interface{} { var flashes = make(map[string]interface{}) flashes["error"] = session.Flashes(flash_err) flashes["info"] = session.Flashes(flash_info) return flashes } func sessionWipe(session *sessions.Session) { session.Values = make(map[interface{}]interface{}) } func initSessionUser(r *http.Request) (*user.User, *sessions.Session) { session, _ := store.Get(r, "c_user") if session.Values["username"] == nil { return nil, session } return user.NewUserFromUsername(db, session.Values["username"].(string)), session } // wrapper for handlers requiring a User func userHandler(next func(http.ResponseWriter, *http.Request, *user.User, *sessions.Session)) func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { user, session := initSessionUser(r) if user == nil { http.Redirect(w, r, "/login", http.StatusFound) } else { next(w, r, user, session) } } } // wrapper for handlers forking on GET and POST // r.HandleFunc("/login", getPostHandler(LoginFormHandler, LoginPostHandler)) func getPostHandler(getFn, postFn func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { getFn(w, r) } else { // POST postFn(w, r) } } } // Log in page handler func LoginFormHandler(w http.ResponseWriter, r *http.Request) { session, _ := store.Get(r, "c_user") flashes := GetFlashes(session) session.Save(r, w) ShowTemplate("login", w, map[string]interface{}{"flashes": flashes}) } // handler for login POST // TODO: proper per account and client flood control rate limiting // currently weak per call slow down is by-passable at scale func LoginPostHandler(w http.ResponseWriter, r *http.Request) { time.Sleep(500 * time.Millisecond) // WEAK poor mans rate limiting for logins r.ParseForm() username := r.PostFormValue("username") // lookup user password := r.PostFormValue("password") user := user.NewUserFromAuth(db, username, password) if user != nil { session, _ := store.Get(r, "c_user") session.Values["username"] = user.Username session.Save(r, w) if r.URL.Query().Get("url") != "" { http.Redirect(w, r, "/add?" + r.URL.RawQuery, http.StatusFound) } http.Redirect(w, r, "/", http.StatusFound) } else { time.Sleep(500 * time.Millisecond) // WEAK bypassable poor mans rate limiting for failed logins session, _ := store.Get(r, "c_user") session.AddFlash("Username or password", flash_err) session.Save(r, w) http.Redirect(w, r, "/login?"+r.URL.RawQuery, http.StatusFound) } } // logout POST handler func LogoutHandler(w http.ResponseWriter, r *http.Request, user *user.User, session *sessions.Session) { //session.Options = &sessions.Options{MaxAge: -1} sessionWipe(session) session.Save(r, w) http.Redirect(w, r, "/", http.StatusFound) } func getUrlTitle(url string) string { resp, err := http.Get(url) if err != nil { fmt.Println("Error looking up link", url, ":", err) } else { body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("Error reading link", url, ":", err) } else { re := regexp.MustCompile("< *[Tt][Ii][Tt][Ll][Ee] *>(.*)") title := re.FindStringSubmatch(string(body)) if title != nil { return strings.TrimSpace(title[1]) } } } return "" } // ?url= func addFormHandler(w http.ResponseWriter, r *http.Request, user *user.User, session *sessions.Session) { categories.LoadCategories(db) flashes := GetFlashes(session) popup := session.Values["popup"] delete(session.Values, "popup") title := session.Values["title"] delete(session.Values, "title") link := session.Values["link"] delete(session.Values, "link") description := session.Values["description"] delete(session.Values, "description") session.Save(r, w) if link != nil { //TODO category_id ShowTemplate("add", w, map[string]interface{}{"user": user, "flashes": flashes, "categories": categories.CategoriesTree, "link": link, "title": title, "description": description, "popup": popup}) return } var url = r.URL.Query().Get("url") reHttp := regexp.MustCompile("^https?://") if url != "" && ! reHttp.Match([]byte(url)) { url = "http://" + url } title = r.URL.Query().Get("title") if title == "" && url != "" { title = getUrlTitle(url) } popup = r.URL.Query().Get("popup") ShowTemplate("add", w, map[string]interface{}{"user": user, "flashes": flashes, "link": url, "categories": categories.CategoriesTree, "title": title, "popup": popup}) } func addPostHandler(w http.ResponseWriter, r *http.Request, user *user.User, session *sessions.Session) { var news news.News news.Title = r.FormValue("title") news.Notes = r.FormValue("notes") news.Url = r.FormValue("link") popup := r.FormValue("popup") category_id, err := strconv.Atoi(r.FormValue("category")) if err != nil { category_id = -1 } news.Category_id = category_id err = (&news).Insert(db) if err != nil { session.AddFlash("Error saving news: " + err.Error(), flash_err) session.Values["title"] = news.Title session.Values["link"] = news.Url session.Values["notes"] = news.Notes session.Values["popup"] = popup session.Save(r, w) http.Redirect(w, r, "/add", http.StatusFound) } else { // TODO auto close? redirect session.AddFlash("Added news \""+news.Title+"\"", flash_info) session.Save(r, w) if popup == "1" { http.Redirect(w, r, "/added", http.StatusFound) } else { http.Redirect(w, r, "/", http.StatusFound) } } } func templateFormHandler(w http.ResponseWriter, r *http.Request, user *user.User, session *sessions.Session) { flashes := GetFlashes(session) session.Save(r, w) news, count, err := news.Unexported(db) if err != nil { return } var templateBuf bytes.Buffer template, err := txtTemplate.ParseFiles("templates/html_template.txt") if err != nil { fmt.Println("Error processing html_tempalte:" , err) } err = template.Execute(&templateBuf, map[string]interface{}{"news": news}) if err != nil { fmt.Println("Exec err: ", err) } ShowTemplate("export", w, map[string]interface{}{"user": user, "flashes": flashes, "template": &templateBuf, "count": count, "url": config.Url}) } func exportHandler(w http.ResponseWriter, r *http.Request, user *user.User, session *sessions.Session) { err := news.MarkExported(db) if err != nil { session.AddFlash("Error marking last batch of news exported", flash_err) } else { session.AddFlash("Last batch of news marked exported", flash_info) } session.Save(r, w) http.Redirect(w, r, "/", http.StatusFound) } func addedHandler(w http.ResponseWriter, r *http.Request, user *user.User, session *sessions.Session) { flashes := GetFlashes(session) session.Save(r, w) ShowTemplate("added", w, map[string]interface{}{"user": user, "flashes": flashes}) } func categoriesFormHandler(w http.ResponseWriter, r *http.Request, user *user.User, session *sessions.Session) { flashes := GetFlashes(session) session.Save(r, w) categories.LoadCategories(db) ShowTemplate("categories", w, map[string]interface{}{"user": user, "flashes": flashes, "categories": categories.CategoriesTree}) } func categoriesPostHandler(w http.ResponseWriter, r *http.Request, user *user.User, session *sessions.Session) { http.Redirect(w, r, "/categories", http.StatusFound) } func categoryFromReqArg(arg string) *categories.Category { if cid, err := strconv.Atoi(arg); err != nil { return nil } else if category, ok := categories.CategoriesFlat[cid]; !ok { return nil } else { return category } } func categoryChangeParentHandler(w http.ResponseWriter, r *http.Request, user *user.User, session *sessions.Session) { categories.LoadCategories(db) category := categoryFromReqArg(r.FormValue("cid")) parent := categoryFromReqArg(r.FormValue("parent")) if category == nil { session.AddFlash("Invalid category", flash_err) } else if parent != nil && category.Id == parent.Id { session.AddFlash("Cannot set category parent to itself", flash_err) } else { err := category.ChangeParent(db, parent) if err != nil { session.AddFlash("Error commiting to Database", flash_err) } else { session.AddFlash("Changed category parent", flash_info) } } session.Save(r, w) http.Redirect(w, r, "/categories", http.StatusFound) } func categoryAddHandler(w http.ResponseWriter, r *http.Request, user *user.User, session *sessions.Session) { name := r.FormValue("name") parent, perr := strconv.Atoi(r.FormValue("parent")) if perr != nil { parent = -1 } if name == "" { session.AddFlash("Invalid category name", flash_err) } else { err := categories.Add(db, name, parent) if err != nil { session.AddFlash("Error commiting to Database", flash_err) } else { session.AddFlash("Added category", flash_info) } } session.Save(r, w) http.Redirect(w, r, "/categories", http.StatusFound) } func categoryDeleteHandler(w http.ResponseWriter, r *http.Request, user *user.User, session *sessions.Session) { id, idErr := strconv.Atoi(r.FormValue("id")) if idErr != nil { session.AddFlash("Invalid category to delete", flash_err) } else { err := categories.Delete(db, id) if err != nil { session.AddFlash("Error commiting to Database", flash_err) } else { session.AddFlash("Deleted category", flash_info) } } session.Save(r, w) http.Redirect(w, r, "/categories", http.StatusFound) } func newsFormHandler(w http.ResponseWriter, r *http.Request, user *user.User, session *sessions.Session) { flashes := GetFlashes(session) session.Save(r, w) var offset = 0 var amount = 100 argOffset, eOffset := strconv.Atoi(r.FormValue("offset")) if eOffset == nil { offset = amount * argOffset } news, count, err := news.LoadPage(db, offset, amount) if err != nil { session.AddFlash("Error loading news", flash_err) } ShowTemplate("news", w, map[string]interface{}{"user": user, "flashes": flashes, "news": news, "count": count, "categories": categories.CategoriesFlat}) } func ServeFileHandler(res http.ResponseWriter, req *http.Request) { fname := path.Base(req.URL.Path) http.ServeFile(res, req, "./"+fname) } func init_route_handlers() { http.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("js/")))) http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css/")))) http.Handle("/fonts/", http.StripPrefix("/fonts", http.FileServer(http.Dir("fonts/")))) http.HandleFunc("/favicon.ico", ServeFileHandler) r := mux.NewRouter() r.HandleFunc("/login", getPostHandler(LoginFormHandler, LoginPostHandler)) r.HandleFunc("/logout", userHandler(LogoutHandler)) r.HandleFunc("/add", getPostHandler(userHandler(addFormHandler), userHandler(addPostHandler))) r.HandleFunc("/", userHandler(newsFormHandler)) r.HandleFunc("/news", userHandler(newsFormHandler)) r.HandleFunc("/export", userHandler(templateFormHandler)) r.HandleFunc("/export-commit", userHandler(exportHandler)) r.HandleFunc("/added", userHandler(addedHandler)) r.HandleFunc("/categories", getPostHandler(userHandler(categoriesFormHandler), userHandler(categoriesPostHandler))) r.HandleFunc("/categories/change-parent", userHandler(categoryChangeParentHandler)) r.HandleFunc("/categories/add", userHandler(categoryAddHandler)) r.HandleFunc("/categories/delete", userHandler(categoryDeleteHandler)) http.Handle("/", r) }