go-examples/authcookie/main.go
2017-07-29 10:50:41 +02:00

77 lines
2.1 KiB
Go

package main
import (
"html/template"
"log"
"net/http"
"github.com/gorilla/sessions"
)
type AuthCookie struct {
templates *template.Template
store *sessions.CookieStore
}
func (app *AuthCookie) HomePage(res http.ResponseWriter, req *http.Request) {
app.templates.ExecuteTemplate(res, "home.html", app.CurrentSession(res, req).Values)
}
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)
}
/*
Create an http application that supports at least 2 endpoints:
login and logout. login should accept a form and save a cookie.
(with at least the username) logout should clear the cookie.
*/
func main() {
tpl, err := template.ParseGlob("templates/*.html")
if err != nil {
log.Fatalln(err)
}
app := AuthCookie{
templates: tpl,
store: sessions.NewCookieStore([]byte("flQ6QzM/c3Jtdl9ycDx6OXRIfFgK")),
}
http.HandleFunc("/", app.HomePage)
http.HandleFunc("/login", app.LoginPage)
http.HandleFunc("/logout", app.LogoutPage)
http.ListenAndServeTLS(":9443", "../cert.pem", "../key.pem", nil)
}