gophertype/pkg/controllers/authentication.go
Noah 5b6712ea97 Blog Archive, RSS Feeds, and Model Cleanup
* Legacy-importer tool updates the DB primary key serial after migrating
  the posts, to be max(posts.id)+1 -- especially important for
  PostgreSQL and MySQL (SQLite3 correctly picked the next ID by
  default?)
* Add blog archive page and RSS, Atom and JSON feeds for the blog.
  URLs are /blog.rss, /blog.atom and /blog.json
2020-02-17 18:10:35 -08:00

65 lines
1.5 KiB
Go

package controllers
import (
"net/http"
"git.kirsle.net/apps/gophertype/pkg/authentication"
"git.kirsle.net/apps/gophertype/pkg/glue"
"git.kirsle.net/apps/gophertype/pkg/models"
"git.kirsle.net/apps/gophertype/pkg/responses"
"git.kirsle.net/apps/gophertype/pkg/session"
"github.com/albrow/forms"
)
func init() {
glue.Register(glue.Endpoint{
Path: "/login",
Methods: []string{"GET", "POST"},
Handler: func(w http.ResponseWriter, r *http.Request) {
// Template variables.
v := responses.NewTemplateVars(w, r)
// POST handler: create the admin account.
for r.Method == http.MethodPost {
form, _ := forms.Parse(r)
v.FormValues = form.Values
// Validate form parameters.
val := form.Validator()
val.Require("email")
val.MatchEmail("email")
val.Require("password")
if val.HasErrors() {
v.ValidationError = val.ErrorMap()
break
}
// Check authentication.
user, err := models.Users.AuthenticateUser(form.Get("email"), form.Get("password"))
if err != nil {
v.Error = err
break
}
_ = user
authentication.Login(w, r, user)
session.Flash(w, r, "Signed in!")
responses.Redirect(w, r, "/") // TODO: next URL
return
}
responses.RenderTemplate(w, r, "_builtin/users/login.gohtml", v)
},
})
glue.Register(glue.Endpoint{
Path: "/logout",
Handler: func(w http.ResponseWriter, r *http.Request) {
authentication.Logout(w, r)
session.Flash(w, r, "Signed out!")
responses.Redirect(w, r, "/")
},
})
}