+type authenticatedHandler func(http.ResponseWriter, *http.Request, User)
+
+type AuthMiddleware struct {
+ handler authenticatedHandler
+ mustBeAdmin bool
+}
+
+func (m AuthMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ user, err := currentUser(w, r)
+ if err != nil || (m.mustBeAdmin && !user.IsAdmin) {
+ http.Redirect(w, r, "/login", http.StatusFound)
+ return
+ }
+ m.handler(w, r, user)
+}
+
+func requireUser(handler authenticatedHandler) AuthMiddleware {
+ return AuthMiddleware{
+ handler: handler,
+ mustBeAdmin: false,
+ }
+}
+
+func requireAdmin(handler authenticatedHandler) AuthMiddleware {
+ return AuthMiddleware{
+ handler: handler,
+ mustBeAdmin: true,
+ }
+}
+