session.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. type SessionMiddleware struct {
  15. store *storage.Storage
  16. router *mux.Router
  17. }
  18. func (s *SessionMiddleware) Handler(next http.Handler) http.Handler {
  19. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  20. session := s.getSessionFromCookie(r)
  21. if session == nil {
  22. log.Println("[Middleware:Session] Session not found")
  23. if s.isPublicRoute(r) {
  24. next.ServeHTTP(w, r)
  25. } else {
  26. http.Redirect(w, r, route.GetRoute(s.router, "login"), http.StatusFound)
  27. }
  28. } else {
  29. log.Println("[Middleware:Session]", session)
  30. ctx := r.Context()
  31. ctx = context.WithValue(ctx, "UserId", session.UserID)
  32. ctx = context.WithValue(ctx, "IsAuthenticated", true)
  33. next.ServeHTTP(w, r.WithContext(ctx))
  34. }
  35. })
  36. }
  37. func (s *SessionMiddleware) isPublicRoute(r *http.Request) bool {
  38. route := mux.CurrentRoute(r)
  39. switch route.GetName() {
  40. case "login", "checkLogin", "stylesheet", "javascript", "oauth2Redirect", "oauth2Callback":
  41. return true
  42. default:
  43. return false
  44. }
  45. }
  46. func (s *SessionMiddleware) getSessionFromCookie(r *http.Request) *model.Session {
  47. sessionCookie, err := r.Cookie("sessionID")
  48. if err == http.ErrNoCookie {
  49. return nil
  50. }
  51. session, err := s.store.GetSessionByToken(sessionCookie.Value)
  52. if err != nil {
  53. log.Println(err)
  54. return nil
  55. }
  56. return session
  57. }
  58. func NewSessionMiddleware(s *storage.Storage, r *mux.Router) *SessionMiddleware {
  59. return &SessionMiddleware{store: s, router: r}
  60. }