aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/middleware
diff options
context:
space:
mode:
authorGravatar Frédéric Guillot <fred@miniflux.net>2017-11-19 21:10:04 -0800
committerGravatar Frédéric Guillot <fred@miniflux.net>2017-11-19 22:01:46 -0800
commit8ffb773f43c8dc54801ca1d111854e7e881c93c9 (patch)
tree38133a2fc612597a75fed1d13e5b4042f58a2b7e /server/middleware
First commit
Diffstat (limited to 'server/middleware')
-rw-r--r--server/middleware/basic_auth.go61
-rw-r--r--server/middleware/csrf.go48
-rw-r--r--server/middleware/middleware.go31
-rw-r--r--server/middleware/session.go72
4 files changed, 212 insertions, 0 deletions
diff --git a/server/middleware/basic_auth.go b/server/middleware/basic_auth.go
new file mode 100644
index 0000000..73dfb98
--- /dev/null
+++ b/server/middleware/basic_auth.go
@@ -0,0 +1,61 @@
+// Copyright 2017 Frédéric Guillot. All rights reserved.
+// Use of this source code is governed by the Apache 2.0
+// license that can be found in the LICENSE file.
+
+package middleware
+
+import (
+ "context"
+ "github.com/miniflux/miniflux2/storage"
+ "log"
+ "net/http"
+)
+
+type BasicAuthMiddleware struct {
+ store *storage.Storage
+}
+
+func (b *BasicAuthMiddleware) Handler(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
+ errorResponse := `{"error_message": "Not Authorized"}`
+
+ username, password, authOK := r.BasicAuth()
+ if !authOK {
+ log.Println("[Middleware:BasicAuth] No authentication headers sent")
+ w.WriteHeader(http.StatusUnauthorized)
+ w.Write([]byte(errorResponse))
+ return
+ }
+
+ if err := b.store.CheckPassword(username, password); err != nil {
+ log.Println("[Middleware:BasicAuth] Invalid username or password:", username)
+ w.WriteHeader(http.StatusUnauthorized)
+ w.Write([]byte(errorResponse))
+ return
+ }
+
+ user, err := b.store.GetUserByUsername(username)
+ if err != nil || user == nil {
+ log.Println("[Middleware:BasicAuth] User not found:", username)
+ w.WriteHeader(http.StatusUnauthorized)
+ w.Write([]byte(errorResponse))
+ return
+ }
+
+ log.Println("[Middleware:BasicAuth] User authenticated:", username)
+ b.store.SetLastLogin(user.ID)
+
+ ctx := r.Context()
+ ctx = context.WithValue(ctx, "UserId", user.ID)
+ ctx = context.WithValue(ctx, "UserTimezone", user.Timezone)
+ ctx = context.WithValue(ctx, "IsAdminUser", user.IsAdmin)
+ ctx = context.WithValue(ctx, "IsAuthenticated", true)
+
+ next.ServeHTTP(w, r.WithContext(ctx))
+ })
+}
+
+func NewBasicAuthMiddleware(s *storage.Storage) *BasicAuthMiddleware {
+ return &BasicAuthMiddleware{store: s}
+}
diff --git a/server/middleware/csrf.go b/server/middleware/csrf.go
new file mode 100644
index 0000000..74736b5
--- /dev/null
+++ b/server/middleware/csrf.go
@@ -0,0 +1,48 @@
+// Copyright 2017 Frédéric Guillot. All rights reserved.
+// Use of this source code is governed by the Apache 2.0
+// license that can be found in the LICENSE file.
+
+package middleware
+
+import (
+ "context"
+ "github.com/miniflux/miniflux2/helper"
+ "log"
+ "net/http"
+)
+
+func Csrf(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var csrfToken string
+
+ csrfCookie, err := r.Cookie("csrfToken")
+ if err == http.ErrNoCookie || csrfCookie.Value == "" {
+ csrfToken = helper.GenerateRandomString(64)
+ cookie := &http.Cookie{
+ Name: "csrfToken",
+ Value: csrfToken,
+ Path: "/",
+ Secure: r.URL.Scheme == "https",
+ HttpOnly: true,
+ }
+
+ http.SetCookie(w, cookie)
+ } else {
+ csrfToken = csrfCookie.Value
+ }
+
+ ctx := r.Context()
+ ctx = context.WithValue(ctx, "CsrfToken", csrfToken)
+
+ w.Header().Add("Vary", "Cookie")
+ isTokenValid := csrfToken == r.FormValue("csrf") || csrfToken == r.Header.Get("X-Csrf-Token")
+
+ if r.Method == "POST" && !isTokenValid {
+ log.Println("[Middleware:CSRF] Invalid or missing CSRF token!")
+ w.WriteHeader(http.StatusBadRequest)
+ w.Write([]byte("Invalid or missing CSRF token!"))
+ } else {
+ next.ServeHTTP(w, r.WithContext(ctx))
+ }
+ })
+}
diff --git a/server/middleware/middleware.go b/server/middleware/middleware.go
new file mode 100644
index 0000000..cab01c8
--- /dev/null
+++ b/server/middleware/middleware.go
@@ -0,0 +1,31 @@
+// Copyright 2017 Frédéric Guillot. All rights reserved.
+// Use of this source code is governed by the Apache 2.0
+// license that can be found in the LICENSE file.
+
+package middleware
+
+import (
+ "net/http"
+)
+
+type Middleware func(http.Handler) http.Handler
+
+type MiddlewareChain struct {
+ middlewares []Middleware
+}
+
+func (m *MiddlewareChain) Wrap(h http.Handler) http.Handler {
+ for i := range m.middlewares {
+ h = m.middlewares[len(m.middlewares)-1-i](h)
+ }
+
+ return h
+}
+
+func (m *MiddlewareChain) WrapFunc(fn http.HandlerFunc) http.Handler {
+ return m.Wrap(fn)
+}
+
+func NewMiddlewareChain(middlewares ...Middleware) *MiddlewareChain {
+ return &MiddlewareChain{append(([]Middleware)(nil), middlewares...)}
+}
diff --git a/server/middleware/session.go b/server/middleware/session.go
new file mode 100644
index 0000000..5455972
--- /dev/null
+++ b/server/middleware/session.go
@@ -0,0 +1,72 @@
+// Copyright 2017 Frédéric Guillot. All rights reserved.
+// Use of this source code is governed by the Apache 2.0
+// license that can be found in the LICENSE file.
+
+package middleware
+
+import (
+ "context"
+ "github.com/miniflux/miniflux2/model"
+ "github.com/miniflux/miniflux2/server/route"
+ "github.com/miniflux/miniflux2/storage"
+ "log"
+ "net/http"
+
+ "github.com/gorilla/mux"
+)
+
+type SessionMiddleware struct {
+ store *storage.Storage
+ router *mux.Router
+}
+
+func (s *SessionMiddleware) Handler(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ session := s.getSessionFromCookie(r)
+
+ if session == nil {
+ log.Println("[Middleware:Session] Session not found")
+ if s.isPublicRoute(r) {
+ next.ServeHTTP(w, r)
+ } else {
+ http.Redirect(w, r, route.GetRoute(s.router, "login"), http.StatusFound)
+ }
+ } else {
+ log.Println("[Middleware:Session]", session)
+ ctx := r.Context()
+ ctx = context.WithValue(ctx, "UserId", session.UserID)
+ ctx = context.WithValue(ctx, "IsAuthenticated", true)
+
+ next.ServeHTTP(w, r.WithContext(ctx))
+ }
+ })
+}
+
+func (s *SessionMiddleware) isPublicRoute(r *http.Request) bool {
+ route := mux.CurrentRoute(r)
+ switch route.GetName() {
+ case "login", "checkLogin", "stylesheet", "javascript":
+ return true
+ default:
+ return false
+ }
+}
+
+func (s *SessionMiddleware) getSessionFromCookie(r *http.Request) *model.Session {
+ sessionCookie, err := r.Cookie("sessionID")
+ if err == http.ErrNoCookie {
+ return nil
+ }
+
+ session, err := s.store.GetSessionByToken(sessionCookie.Value)
+ if err != nil {
+ log.Println(err)
+ return nil
+ }
+
+ return session
+}
+
+func NewSessionMiddleware(s *storage.Storage, r *mux.Router) *SessionMiddleware {
+ return &SessionMiddleware{store: s, router: r}
+}