numerus/pkg/router.go
jordi fita mas f1bf1f896d Implement login cookie, its verification, and logout
At first i thought that i would need to implement sessions, the ones
that keep small files onto the disk, to know which user is talking to
the server, but then i realized that, for now at least, i only need a
very large number, plus the email address, to be used as a lookup, and
that can be stored in the user table, in a separate schema.

Had to change login to avoid raising exceptions when login failed
because i now keep a record of login attemps, and functions are always
run in a single transaction, thus the exception would prevent me to
insert into login_attempt.  Even if i use a separate procedure, i could
not keep the records.

I did not want to add a parameter to the logout function because i was
afraid that it could be called from separate users.  I do not know
whether it is possible with the current approach, since the settings
variable is also set by the same applications; time will tell.
2023-01-17 20:58:13 +01:00

41 lines
823 B
Go

package pkg
import (
"html/template"
"net/http"
)
func NewRouter(db *Db) http.Handler {
router := http.NewServeMux()
router.Handle("/login", LoginHandler(db))
router.Handle("/logout", LogoutHandler(db))
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
user := getUser(r)
if user.LoggedIn {
t, err := template.ParseFiles("web/template/index.html")
if err != nil {
panic(err)
}
err = t.Execute(w, nil)
if err != nil {
panic(err)
}
} else {
var page LoginPage;
t, err := template.ParseFiles("web/template/login.html")
if err != nil {
panic(err)
}
err = t.Execute(w, page)
if err != nil {
panic(err)
}
}
})
var handler http.Handler = router
handler = CheckLogin(db, handler)
handler = Recoverer(handler)
handler = Logger(handler)
return handler
}