middleware.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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 ui // import "miniflux.app/ui"
  5. import (
  6. "context"
  7. "errors"
  8. "net/http"
  9. "miniflux.app/config"
  10. "miniflux.app/http/cookie"
  11. "miniflux.app/http/request"
  12. "miniflux.app/http/response/html"
  13. "miniflux.app/http/route"
  14. "miniflux.app/logger"
  15. "miniflux.app/model"
  16. "miniflux.app/storage"
  17. "miniflux.app/ui/session"
  18. "github.com/gorilla/mux"
  19. )
  20. type middleware struct {
  21. router *mux.Router
  22. store *storage.Storage
  23. }
  24. func newMiddleware(router *mux.Router, store *storage.Storage) *middleware {
  25. return &middleware{router, store}
  26. }
  27. func (m *middleware) handleUserSession(next http.Handler) http.Handler {
  28. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  29. session := m.getUserSessionFromCookie(r)
  30. if session == nil {
  31. if m.isPublicRoute(r) {
  32. next.ServeHTTP(w, r)
  33. } else {
  34. logger.Debug("[UI:UserSession] Session not found, redirect to login page")
  35. html.Redirect(w, r, route.Path(m.router, "login"))
  36. }
  37. } else {
  38. logger.Debug("[UI:UserSession] %s", session)
  39. ctx := r.Context()
  40. ctx = context.WithValue(ctx, request.UserIDContextKey, session.UserID)
  41. ctx = context.WithValue(ctx, request.IsAuthenticatedContextKey, true)
  42. ctx = context.WithValue(ctx, request.UserSessionTokenContextKey, session.Token)
  43. next.ServeHTTP(w, r.WithContext(ctx))
  44. }
  45. })
  46. }
  47. func (m *middleware) handleAppSession(next http.Handler) http.Handler {
  48. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  49. var err error
  50. session := m.getAppSessionValueFromCookie(r)
  51. if session == nil {
  52. if request.IsAuthenticated(r) {
  53. userID := request.UserID(r)
  54. logger.Debug("[UI:AppSession] Cookie expired but user #%d is logged: creating a new session", userID)
  55. session, err = m.store.CreateAppSessionWithUserPrefs(userID)
  56. if err != nil {
  57. html.ServerError(w, r, err)
  58. return
  59. }
  60. } else {
  61. logger.Debug("[UI:AppSession] Session not found, creating a new one")
  62. session, err = m.store.CreateAppSession()
  63. if err != nil {
  64. html.ServerError(w, r, err)
  65. return
  66. }
  67. }
  68. http.SetCookie(w, cookie.New(cookie.CookieAppSessionID, session.ID, config.Opts.HTTPS, config.Opts.BasePath()))
  69. } else {
  70. logger.Debug("[UI:AppSession] %s", session)
  71. }
  72. if r.Method == http.MethodPost {
  73. formValue := r.FormValue("csrf")
  74. headerValue := r.Header.Get("X-Csrf-Token")
  75. if session.Data.CSRF != formValue && session.Data.CSRF != headerValue {
  76. logger.Error(`[UI:AppSession] Invalid or missing CSRF token: Form="%s", Header="%s"`, formValue, headerValue)
  77. if mux.CurrentRoute(r).GetName() == "checkLogin" {
  78. html.Redirect(w, r, route.Path(m.router, "login"))
  79. return
  80. }
  81. html.BadRequest(w, r, errors.New("Invalid or missing CSRF"))
  82. return
  83. }
  84. }
  85. ctx := r.Context()
  86. ctx = context.WithValue(ctx, request.SessionIDContextKey, session.ID)
  87. ctx = context.WithValue(ctx, request.CSRFContextKey, session.Data.CSRF)
  88. ctx = context.WithValue(ctx, request.OAuth2StateContextKey, session.Data.OAuth2State)
  89. ctx = context.WithValue(ctx, request.FlashMessageContextKey, session.Data.FlashMessage)
  90. ctx = context.WithValue(ctx, request.FlashErrorMessageContextKey, session.Data.FlashErrorMessage)
  91. ctx = context.WithValue(ctx, request.UserLanguageContextKey, session.Data.Language)
  92. ctx = context.WithValue(ctx, request.UserThemeContextKey, session.Data.Theme)
  93. ctx = context.WithValue(ctx, request.PocketRequestTokenContextKey, session.Data.PocketRequestToken)
  94. next.ServeHTTP(w, r.WithContext(ctx))
  95. })
  96. }
  97. func (m *middleware) getAppSessionValueFromCookie(r *http.Request) *model.Session {
  98. cookieValue := request.CookieValue(r, cookie.CookieAppSessionID)
  99. if cookieValue == "" {
  100. return nil
  101. }
  102. session, err := m.store.AppSession(cookieValue)
  103. if err != nil {
  104. logger.Error("[UI:AppSession] %v", err)
  105. return nil
  106. }
  107. return session
  108. }
  109. func (m *middleware) isPublicRoute(r *http.Request) bool {
  110. route := mux.CurrentRoute(r)
  111. switch route.GetName() {
  112. case "login",
  113. "checkLogin",
  114. "stylesheet",
  115. "javascript",
  116. "oauth2Redirect",
  117. "oauth2Callback",
  118. "appIcon",
  119. "favicon",
  120. "webManifest",
  121. "robots",
  122. "sharedEntry",
  123. "healthcheck",
  124. "offline":
  125. return true
  126. default:
  127. return false
  128. }
  129. }
  130. func (m *middleware) getUserSessionFromCookie(r *http.Request) *model.UserSession {
  131. cookieValue := request.CookieValue(r, cookie.CookieUserSessionID)
  132. if cookieValue == "" {
  133. return nil
  134. }
  135. session, err := m.store.UserSessionByToken(cookieValue)
  136. if err != nil {
  137. logger.Error("[UI:UserSession] %v", err)
  138. return nil
  139. }
  140. return session
  141. }
  142. func (m *middleware) handleAuthProxy(next http.Handler) http.Handler {
  143. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  144. if request.IsAuthenticated(r) || config.Opts.AuthProxyHeader() == "" {
  145. next.ServeHTTP(w, r)
  146. return
  147. }
  148. username := r.Header.Get(config.Opts.AuthProxyHeader())
  149. if username == "" {
  150. next.ServeHTTP(w, r)
  151. return
  152. }
  153. clientIP := request.ClientIP(r)
  154. logger.Info("[AuthProxy] [ClientIP=%s] Received authenticated requested for %q", clientIP, username)
  155. user, err := m.store.UserByUsername(username)
  156. if err != nil {
  157. html.ServerError(w, r, err)
  158. return
  159. }
  160. if user == nil {
  161. logger.Error("[AuthProxy] [ClientIP=%s] %q doesn't exist", clientIP, username)
  162. if !config.Opts.IsAuthProxyUserCreationAllowed() {
  163. html.Forbidden(w, r)
  164. return
  165. }
  166. if user, err = m.store.CreateUser(&model.UserCreationRequest{Username: username}); err != nil {
  167. html.ServerError(w, r, err)
  168. return
  169. }
  170. }
  171. sessionToken, _, err := m.store.CreateUserSessionFromUsername(user.Username, r.UserAgent(), clientIP)
  172. if err != nil {
  173. html.ServerError(w, r, err)
  174. return
  175. }
  176. logger.Info("[AuthProxy] [ClientIP=%s] username=%s just logged in", clientIP, user.Username)
  177. m.store.SetLastLogin(user.ID)
  178. sess := session.New(m.store, request.SessionID(r))
  179. sess.SetLanguage(user.Language)
  180. sess.SetTheme(user.Theme)
  181. http.SetCookie(w, cookie.New(
  182. cookie.CookieUserSessionID,
  183. sessionToken,
  184. config.Opts.HTTPS,
  185. config.Opts.BasePath(),
  186. ))
  187. html.Redirect(w, r, route.Path(m.router, "unread"))
  188. })
  189. }