app_session.go 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2018 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. "errors"
  8. "net/http"
  9. "github.com/miniflux/miniflux/http/cookie"
  10. "github.com/miniflux/miniflux/http/request"
  11. "github.com/miniflux/miniflux/http/response/html"
  12. "github.com/miniflux/miniflux/logger"
  13. "github.com/miniflux/miniflux/model"
  14. )
  15. // AppSession handles application session middleware.
  16. func (m *Middleware) AppSession(next http.Handler) http.Handler {
  17. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  18. var err error
  19. session := m.getAppSessionValueFromCookie(r)
  20. if session == nil {
  21. logger.Debug("[Middleware:AppSession] Session not found")
  22. session, err = m.store.CreateSession()
  23. if err != nil {
  24. logger.Error("[Middleware:AppSession] %v", err)
  25. html.ServerError(w, err)
  26. return
  27. }
  28. http.SetCookie(w, cookie.New(cookie.CookieSessionID, session.ID, m.cfg.IsHTTPS, m.cfg.BasePath()))
  29. } else {
  30. logger.Debug("[Middleware:AppSession] %s", session)
  31. }
  32. if r.Method == "POST" {
  33. formValue := r.FormValue("csrf")
  34. headerValue := r.Header.Get("X-Csrf-Token")
  35. if session.Data.CSRF != formValue && session.Data.CSRF != headerValue {
  36. logger.Error(`[Middleware:AppSession] Invalid or missing CSRF token: Form="%s", Header="%s"`, formValue, headerValue)
  37. html.BadRequest(w, errors.New("invalid or missing CSRF"))
  38. return
  39. }
  40. }
  41. ctx := r.Context()
  42. ctx = context.WithValue(ctx, SessionIDContextKey, session.ID)
  43. ctx = context.WithValue(ctx, CSRFContextKey, session.Data.CSRF)
  44. ctx = context.WithValue(ctx, OAuth2StateContextKey, session.Data.OAuth2State)
  45. ctx = context.WithValue(ctx, FlashMessageContextKey, session.Data.FlashMessage)
  46. ctx = context.WithValue(ctx, FlashErrorMessageContextKey, session.Data.FlashErrorMessage)
  47. ctx = context.WithValue(ctx, UserLanguageContextKey, session.Data.Language)
  48. ctx = context.WithValue(ctx, UserThemeContextKey, session.Data.Theme)
  49. ctx = context.WithValue(ctx, PocketRequestTokenContextKey, session.Data.PocketRequestToken)
  50. next.ServeHTTP(w, r.WithContext(ctx))
  51. })
  52. }
  53. func (m *Middleware) getAppSessionValueFromCookie(r *http.Request) *model.Session {
  54. cookieValue := request.Cookie(r, cookie.CookieSessionID)
  55. if cookieValue == "" {
  56. return nil
  57. }
  58. session, err := m.store.Session(cookieValue)
  59. if err != nil {
  60. logger.Error("[Middleware:AppSession] %v", err)
  61. return nil
  62. }
  63. return session
  64. }