4
0

middleware.go 6.8 KB

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