package admin import ( "html/template" "net/http" "github.com/gorilla/sessions" ) type AuthCookie struct { Templates *template.Template Store *sessions.CookieStore } func (app *AuthCookie) LoginPage(res http.ResponseWriter, req *http.Request) { formErr := make(map[string]string) switch req.Method { case "POST": username := req.FormValue("username") if username == "" { formErr["username"] = "Empty username" } password := req.FormValue("password") if password == "" { formErr["password"] = "Empty password" } // FIXME verifiy password with file in data dir if len(formErr) == 0 { app.SaveUsername(username, res, req) RedirectHome(res, req) return } fallthrough case "GET": app.Templates.ExecuteTemplate(res, "login.html", formErr) } } func (app *AuthCookie) LogoutPage(res http.ResponseWriter, req *http.Request) { app.SaveUsername("", res, req) RedirectHome(res, req) } func (app *AuthCookie) CurrentSession(res http.ResponseWriter, req *http.Request) *sessions.Session { session, _ := app.Store.Get(req, "session") return session } func (app *AuthCookie) SaveUsername(username string, res http.ResponseWriter, req *http.Request) { session := app.CurrentSession(res, req) session.Values["username"] = username session.Save(req, res) } func (app *AuthCookie) IsLoggedIn(res http.ResponseWriter, req *http.Request) bool { session := app.CurrentSession(res, req) return session != nil && session.Values["username"] != "" } func (app *AuthCookie) Username(res http.ResponseWriter, req *http.Request) string { session := app.CurrentSession(res, req) if session == nil { return "" } return session.Values["username"].(string) } func RedirectHome(res http.ResponseWriter, req *http.Request) { http.Redirect(res, req, "/", http.StatusSeeOther) }