user_session.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. "net/http"
  8. "github.com/miniflux/miniflux/http/cookie"
  9. "github.com/miniflux/miniflux/http/request"
  10. "github.com/miniflux/miniflux/http/response"
  11. "github.com/miniflux/miniflux/http/route"
  12. "github.com/miniflux/miniflux/logger"
  13. "github.com/miniflux/miniflux/model"
  14. "github.com/gorilla/mux"
  15. )
  16. // UserSession handles the user session middleware.
  17. func (m *Middleware) UserSession(next http.Handler) http.Handler {
  18. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  19. session := m.getUserSessionFromCookie(r)
  20. if session == nil {
  21. logger.Debug("[Middleware:UserSession] Session not found")
  22. if m.isPublicRoute(r) {
  23. next.ServeHTTP(w, r)
  24. } else {
  25. response.Redirect(w, r, route.Path(m.router, "login"))
  26. }
  27. } else {
  28. logger.Debug("[Middleware:UserSession] %s", session)
  29. ctx := r.Context()
  30. ctx = context.WithValue(ctx, UserIDContextKey, session.UserID)
  31. ctx = context.WithValue(ctx, IsAuthenticatedContextKey, true)
  32. ctx = context.WithValue(ctx, UserSessionTokenContextKey, session.Token)
  33. next.ServeHTTP(w, r.WithContext(ctx))
  34. }
  35. })
  36. }
  37. func (m *Middleware) isPublicRoute(r *http.Request) bool {
  38. route := mux.CurrentRoute(r)
  39. switch route.GetName() {
  40. case "login",
  41. "checkLogin",
  42. "stylesheet",
  43. "javascript",
  44. "oauth2Redirect",
  45. "oauth2Callback",
  46. "appIcon",
  47. "favicon",
  48. "webManifest":
  49. return true
  50. default:
  51. return false
  52. }
  53. }
  54. func (m *Middleware) getUserSessionFromCookie(r *http.Request) *model.UserSession {
  55. cookieValue := request.Cookie(r, cookie.CookieUserSessionID)
  56. if cookieValue == "" {
  57. return nil
  58. }
  59. session, err := m.store.UserSessionByToken(cookieValue)
  60. if err != nil {
  61. logger.Error("[Middleware:UserSession] %v", err)
  62. return nil
  63. }
  64. return session
  65. }