middleware.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package googlereader // import "miniflux.app/googlereader"
  4. import (
  5. "context"
  6. "crypto/hmac"
  7. "crypto/sha1"
  8. "encoding/hex"
  9. "net/http"
  10. "strings"
  11. "miniflux.app/http/request"
  12. "miniflux.app/http/response"
  13. "miniflux.app/http/response/json"
  14. "miniflux.app/logger"
  15. "miniflux.app/model"
  16. "miniflux.app/storage"
  17. )
  18. type middleware struct {
  19. store *storage.Storage
  20. }
  21. func newMiddleware(s *storage.Storage) *middleware {
  22. return &middleware{s}
  23. }
  24. func (m *middleware) clientLogin(w http.ResponseWriter, r *http.Request) {
  25. clientIP := request.ClientIP(r)
  26. var username, password, output string
  27. var integration *model.Integration
  28. err := r.ParseForm()
  29. if err != nil {
  30. logger.Error("[GoogleReader][Login] [ClientIP=%s] Could not parse form", clientIP)
  31. json.Unauthorized(w, r)
  32. return
  33. }
  34. username = r.Form.Get("Email")
  35. password = r.Form.Get("Passwd")
  36. output = r.Form.Get("output")
  37. if username == "" || password == "" {
  38. logger.Error("[GoogleReader][Login] [ClientIP=%s] Empty username or password", clientIP)
  39. json.Unauthorized(w, r)
  40. return
  41. }
  42. if err = m.store.GoogleReaderUserCheckPassword(username, password); err != nil {
  43. logger.Error("[GoogleReader][Login] [ClientIP=%s] Invalid username or password: %s", clientIP, username)
  44. json.Unauthorized(w, r)
  45. return
  46. }
  47. logger.Info("[GoogleReader][Login] [ClientIP=%s] User authenticated: %s", clientIP, username)
  48. if integration, err = m.store.GoogleReaderUserGetIntegration(username); err != nil {
  49. logger.Error("[GoogleReader][Login] [ClientIP=%s] Could not load integration: %s", clientIP, username)
  50. json.Unauthorized(w, r)
  51. return
  52. }
  53. m.store.SetLastLogin(integration.UserID)
  54. token := getAuthToken(integration.GoogleReaderUsername, integration.GoogleReaderPassword)
  55. logger.Info("[GoogleReader][Login] [ClientIP=%s] Created token: %s", clientIP, token)
  56. result := login{SID: token, LSID: token, Auth: token}
  57. if output == "json" {
  58. json.OK(w, r, result)
  59. return
  60. }
  61. builder := response.New(w, r)
  62. builder.WithHeader("Content-Type", "text/plain; charset=UTF-8")
  63. builder.WithBody(result.String())
  64. builder.Write()
  65. }
  66. func (m *middleware) token(w http.ResponseWriter, r *http.Request) {
  67. clientIP := request.ClientIP(r)
  68. if !request.IsAuthenticated(r) {
  69. logger.Error("[GoogleReader][Token] [ClientIP=%s] User is not authenticated", clientIP)
  70. json.Unauthorized(w, r)
  71. return
  72. }
  73. token := request.GoolgeReaderToken(r)
  74. if token == "" {
  75. logger.Error("[GoogleReader][Token] [ClientIP=%s] User does not have token: %s", clientIP, request.UserID(r))
  76. json.Unauthorized(w, r)
  77. return
  78. }
  79. logger.Info("[GoogleReader][Token] [ClientIP=%s] token: %s", clientIP, token)
  80. w.Header().Add("Content-Type", "text/plain; charset=UTF-8")
  81. w.WriteHeader(http.StatusOK)
  82. w.Write([]byte(token))
  83. }
  84. func (m *middleware) handleCORS(next http.Handler) http.Handler {
  85. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  86. w.Header().Set("Access-Control-Allow-Origin", "*")
  87. w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
  88. w.Header().Set("Access-Control-Allow-Headers", "Authorization")
  89. if r.Method == http.MethodOptions {
  90. w.WriteHeader(http.StatusOK)
  91. return
  92. }
  93. next.ServeHTTP(w, r)
  94. })
  95. }
  96. func (m *middleware) apiKeyAuth(next http.Handler) http.Handler {
  97. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  98. clientIP := request.ClientIP(r)
  99. var token string
  100. if r.Method == http.MethodPost {
  101. err := r.ParseForm()
  102. if err != nil {
  103. logger.Error("[GoogleReader][Login] [ClientIP=%s] Could not parse form", clientIP)
  104. Unauthorized(w, r)
  105. return
  106. }
  107. token = r.Form.Get("T")
  108. if token == "" {
  109. logger.Error("[GoogleReader][Auth] [ClientIP=%s] Post-Form T field is empty", clientIP)
  110. Unauthorized(w, r)
  111. return
  112. }
  113. } else {
  114. authorization := r.Header.Get("Authorization")
  115. if authorization == "" {
  116. logger.Error("[GoogleReader][Auth] [ClientIP=%s] No token provided", clientIP)
  117. Unauthorized(w, r)
  118. return
  119. }
  120. fields := strings.Fields(authorization)
  121. if len(fields) != 2 {
  122. logger.Error("[GoogleReader][Auth] [ClientIP=%s] Authorization header does not have the expected structure GoogleLogin auth=xxxxxx - '%s'", clientIP, authorization)
  123. Unauthorized(w, r)
  124. return
  125. }
  126. if fields[0] != "GoogleLogin" {
  127. logger.Error("[GoogleReader][Auth] [ClientIP=%s] Authorization header does not begin with GoogleLogin - '%s'", clientIP, authorization)
  128. Unauthorized(w, r)
  129. return
  130. }
  131. auths := strings.Split(fields[1], "=")
  132. if len(auths) != 2 {
  133. logger.Error("[GoogleReader][Auth] [ClientIP=%s] Authorization header does not have the expected structure GoogleLogin auth=xxxxxx - '%s'", clientIP, authorization)
  134. Unauthorized(w, r)
  135. return
  136. }
  137. if auths[0] != "auth" {
  138. logger.Error("[GoogleReader][Auth] [ClientIP=%s] Authorization header does not have the expected structure GoogleLogin auth=xxxxxx - '%s'", clientIP, authorization)
  139. Unauthorized(w, r)
  140. return
  141. }
  142. token = auths[1]
  143. }
  144. parts := strings.Split(token, "/")
  145. if len(parts) != 2 {
  146. logger.Error("[GoogleReader][Auth] [ClientIP=%s] Auth token does not have the expected structure username/hash - '%s'", clientIP, token)
  147. Unauthorized(w, r)
  148. return
  149. }
  150. var integration *model.Integration
  151. var user *model.User
  152. var err error
  153. if integration, err = m.store.GoogleReaderUserGetIntegration(parts[0]); err != nil {
  154. logger.Error("[GoogleReader][Auth] [ClientIP=%s] token: %s", clientIP, token)
  155. logger.Error("[GoogleReader][Auth] [ClientIP=%s] No user found with the given google reader username: %s", clientIP, parts[0])
  156. Unauthorized(w, r)
  157. return
  158. }
  159. expectedToken := getAuthToken(integration.GoogleReaderUsername, integration.GoogleReaderPassword)
  160. if expectedToken != token {
  161. logger.Error("[GoogleReader][Auth] [ClientIP=%s] Token does not match: %s", clientIP, token)
  162. Unauthorized(w, r)
  163. return
  164. }
  165. if user, err = m.store.UserByID(integration.UserID); err != nil {
  166. logger.Error("[GoogleReader][Auth] [ClientIP=%s] No user found with the userID: %d", clientIP, integration.UserID)
  167. Unauthorized(w, r)
  168. return
  169. }
  170. m.store.SetLastLogin(integration.UserID)
  171. ctx := r.Context()
  172. ctx = context.WithValue(ctx, request.UserIDContextKey, user.ID)
  173. ctx = context.WithValue(ctx, request.UserTimezoneContextKey, user.Timezone)
  174. ctx = context.WithValue(ctx, request.IsAdminUserContextKey, user.IsAdmin)
  175. ctx = context.WithValue(ctx, request.IsAuthenticatedContextKey, true)
  176. ctx = context.WithValue(ctx, request.GoogleReaderToken, token)
  177. next.ServeHTTP(w, r.WithContext(ctx))
  178. })
  179. }
  180. func getAuthToken(username, password string) string {
  181. token := hex.EncodeToString(hmac.New(sha1.New, []byte(username+password)).Sum(nil))
  182. token = username + "/" + token
  183. return token
  184. }