session.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2017 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package middleware
  5. import (
  6. "context"
  7. "log"
  8. "net/http"
  9. "github.com/miniflux/miniflux2/model"
  10. "github.com/miniflux/miniflux2/server/route"
  11. "github.com/miniflux/miniflux2/storage"
  12. "github.com/gorilla/mux"
  13. )
  14. // SessionMiddleware represents a session middleware.
  15. type SessionMiddleware struct {
  16. store *storage.Storage
  17. router *mux.Router
  18. }
  19. // Handler execute the middleware.
  20. func (s *SessionMiddleware) Handler(next http.Handler) http.Handler {
  21. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  22. session := s.getSessionFromCookie(r)
  23. if session == nil {
  24. log.Println("[Middleware:Session] Session not found")
  25. if s.isPublicRoute(r) {
  26. next.ServeHTTP(w, r)
  27. } else {
  28. http.Redirect(w, r, route.Path(s.router, "login"), http.StatusFound)
  29. }
  30. } else {
  31. log.Println("[Middleware:Session]", session)
  32. ctx := r.Context()
  33. ctx = context.WithValue(ctx, UserIDContextKey, session.UserID)
  34. ctx = context.WithValue(ctx, IsAuthenticatedContextKey, true)
  35. next.ServeHTTP(w, r.WithContext(ctx))
  36. }
  37. })
  38. }
  39. func (s *SessionMiddleware) isPublicRoute(r *http.Request) bool {
  40. route := mux.CurrentRoute(r)
  41. switch route.GetName() {
  42. case "login", "checkLogin", "stylesheet", "javascript", "oauth2Redirect", "oauth2Callback":
  43. return true
  44. default:
  45. return false
  46. }
  47. }
  48. func (s *SessionMiddleware) getSessionFromCookie(r *http.Request) *model.Session {
  49. sessionCookie, err := r.Cookie("sessionID")
  50. if err == http.ErrNoCookie {
  51. return nil
  52. }
  53. session, err := s.store.SessionByToken(sessionCookie.Value)
  54. if err != nil {
  55. log.Println(err)
  56. return nil
  57. }
  58. return session
  59. }
  60. // NewSessionMiddleware returns a new SessionMiddleware.
  61. func NewSessionMiddleware(s *storage.Storage, r *mux.Router) *SessionMiddleware {
  62. return &SessionMiddleware{store: s, router: r}
  63. }