Refactor authenticated redirection to a common handler
This commit is contained in:
parent
d9c93b8797
commit
c037f671f8
21
pkg/login.go
21
pkg/login.go
|
@ -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)
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
|
@ -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{
|
||||
|
|
|
@ -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 {
|
||||
|
|
Loading…
Reference in New Issue