Skip to content

Commit 8ddc0b4

Browse files
committed
require login middleware
1 parent b950411 commit 8ddc0b4

File tree

2 files changed

+19
-6
lines changed

2 files changed

+19
-6
lines changed

cmd/web/middleware.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,18 @@ func SecureHeaders(next http.Handler) http.Handler {
2222
next.ServeHTTP(w, r)
2323
})
2424
}
25+
26+
func (app *App) RequireLogin(next http.Handler) http.Handler {
27+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
28+
loggedIn, err := app.LoggedIn(r)
29+
if err != nil {
30+
app.ServerError(w, err)
31+
return
32+
}
33+
if !loggedIn {
34+
http.Redirect(w, r, "/user/login", http.StatusFound)
35+
return
36+
}
37+
next.ServeHTTP(w, r)
38+
})
39+
}

cmd/web/routes.go

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,22 +12,20 @@ func (app *App) Routes() http.Handler {
1212

1313
mux.Get("/", http.HandlerFunc(app.Home))
1414

15-
mux.Get("/snippet/new", http.HandlerFunc(app.NewSnippet))
16-
mux.Post("/snippet/new", http.HandlerFunc(app.CreateSnippet))
15+
mux.Get("/snippet/new", alice.New(app.RequireLogin).Then(http.HandlerFunc(app.NewSnippet)))
16+
mux.Post("/snippet/new", alice.New(app.RequireLogin).Then(http.HandlerFunc(app.CreateSnippet)))
1717
mux.Get("/snippet/:id", http.HandlerFunc(app.ShowSnippet))
1818

1919
mux.Get("/user/signup", http.HandlerFunc(app.SignupUser))
2020
mux.Post("/user/signup", http.HandlerFunc(app.CreateUser))
2121
mux.Get("/user/login", http.HandlerFunc(app.LoginUser))
2222
mux.Post("/user/login", http.HandlerFunc(app.VerifyUser))
23-
mux.Post("/user/logout", http.HandlerFunc(app.LogoutUser))
23+
mux.Post("/user/logout", alice.New(app.RequireLogin).Then(http.HandlerFunc(app.LogoutUser)))
2424

2525
fileServer := http.FileServer(http.Dir(app.staticDir))
2626
mux.Get("/static/", http.StripPrefix("/static", DisableIndex(fileServer)))
2727

2828
mux.Get("/version", http.HandlerFunc(app.VersionInfo))
2929

30-
chain := alice.New(LogRequest, SecureHeaders).Then(mux)
31-
32-
return chain
30+
return alice.New(LogRequest, SecureHeaders).Then(mux)
3331
}

0 commit comments

Comments
 (0)