Refactor authenticated redirection to a common handler

This commit is contained in:
jordi fita mas 2023-01-24 21:44:23 +01:00
parent d9c93b8797
commit c037f671f8
3 changed files with 16 additions and 13 deletions

View File

@ -61,13 +61,9 @@ func LoginHandler() http.Handler {
func LogoutHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := getUser(r)
if user.LoggedIn {
conn := getConn(r)
conn.MustExec(r.Context(), "select logout()")
http.SetCookie(w, createSessionCookie("", -24*time.Hour))
}
http.Redirect(w, r, "/login", http.StatusSeeOther)
conn := getConn(r)
conn.MustExec(r.Context(), "select logout()")
http.SetCookie(w, createSessionCookie("", -24*time.Hour))
})
}
@ -130,3 +126,14 @@ func getUser(r *http.Request) *AppUser {
func getConn(r *http.Request) *Conn {
return r.Context().Value(ContextConnKey).(*Conn)
}
func Authenticated(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := getUser(r)
if user.LoggedIn {
next.ServeHTTP(w, r);
} else {
http.Redirect(w, r, "/login", http.StatusSeeOther)
}
});
}

View File

@ -23,10 +23,6 @@ type ProfilePage struct {
func ProfileHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := getUser(r)
if !user.LoggedIn {
http.Redirect(w, r, "/login", http.StatusUnauthorized)
return
}
conn := getConn(r)
locale := getLocale(r)
page := ProfilePage{

View File

@ -8,8 +8,8 @@ func NewRouter(db *Db) http.Handler {
router := http.NewServeMux()
router.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("web/static"))))
router.Handle("/login", LoginHandler())
router.Handle("/logout", LogoutHandler())
router.Handle("/profile", ProfileHandler())
router.Handle("/logout", Authenticated(LogoutHandler()))
router.Handle("/profile", Authenticated(ProfileHandler()))
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
user := getUser(r)
if user.LoggedIn {