go-examples/photoblog/admin/admin.go

53 lines
1.3 KiB
Go

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"
}
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 RedirectHome(res http.ResponseWriter, req *http.Request) {
http.Redirect(res, req, "/", http.StatusSeeOther)
}