miniflux-v2/server/middleware/session.go

77 lines
2.0 KiB
Go
Raw Normal View History

2017-11-20 06:10:04 +01:00
// 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"
2017-11-23 07:22:33 +01:00
"net/http"
2017-12-16 03:55:57 +01:00
"github.com/miniflux/miniflux/logger"
2017-12-13 06:48:13 +01:00
"github.com/miniflux/miniflux/model"
"github.com/miniflux/miniflux/server/route"
"github.com/miniflux/miniflux/storage"
2017-11-20 06:10:04 +01:00
"github.com/gorilla/mux"
)
2017-11-28 06:30:04 +01:00
// SessionMiddleware represents a session middleware.
2017-11-20 06:10:04 +01:00
type SessionMiddleware struct {
store *storage.Storage
router *mux.Router
}
2017-11-28 06:30:04 +01:00
// Handler execute the middleware.
2017-11-20 06:10:04 +01:00
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 {
2017-12-16 03:55:57 +01:00
logger.Debug("[Middleware:Session] Session not found")
2017-11-20 06:10:04 +01:00
if s.isPublicRoute(r) {
next.ServeHTTP(w, r)
} else {
2017-11-28 06:30:04 +01:00
http.Redirect(w, r, route.Path(s.router, "login"), http.StatusFound)
2017-11-20 06:10:04 +01:00
}
} else {
2017-12-16 03:55:57 +01:00
logger.Debug("[Middleware:Session] %s", session)
2017-11-20 06:10:04 +01:00
ctx := r.Context()
2017-11-28 06:30:04 +01:00
ctx = context.WithValue(ctx, UserIDContextKey, session.UserID)
ctx = context.WithValue(ctx, IsAuthenticatedContextKey, true)
2017-11-20 06:10:04 +01:00
next.ServeHTTP(w, r.WithContext(ctx))
}
})
}
func (s *SessionMiddleware) isPublicRoute(r *http.Request) bool {
route := mux.CurrentRoute(r)
switch route.GetName() {
2017-12-16 06:28:54 +01:00
case "login", "checkLogin", "stylesheet", "javascript", "oauth2Redirect", "oauth2Callback", "appIcon", "favicon":
2017-11-20 06:10:04 +01:00
return true
default:
return false
}
}
2017-12-16 21:15:33 +01:00
func (s *SessionMiddleware) getSessionFromCookie(r *http.Request) *model.UserSession {
2017-11-20 06:10:04 +01:00
sessionCookie, err := r.Cookie("sessionID")
if err == http.ErrNoCookie {
return nil
}
2017-12-16 21:15:33 +01:00
session, err := s.store.UserSessionByToken(sessionCookie.Value)
2017-11-20 06:10:04 +01:00
if err != nil {
2017-12-16 03:55:57 +01:00
logger.Error("[SessionMiddleware] %v", err)
2017-11-20 06:10:04 +01:00
return nil
}
return session
}
2017-11-28 06:30:04 +01:00
// NewSessionMiddleware returns a new SessionMiddleware.
2017-11-20 06:10:04 +01:00
func NewSessionMiddleware(s *storage.Storage, r *mux.Router) *SessionMiddleware {
return &SessionMiddleware{store: s, router: r}
}