basic_auth.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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/logger"
  9. "github.com/miniflux/miniflux/storage"
  10. )
  11. // BasicAuthMiddleware is the middleware for HTTP Basic authentication.
  12. type BasicAuthMiddleware struct {
  13. store *storage.Storage
  14. }
  15. // Handler executes the middleware.
  16. func (b *BasicAuthMiddleware) Handler(next http.Handler) http.Handler {
  17. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  18. w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
  19. errorResponse := `{"error_message": "Not Authorized"}`
  20. username, password, authOK := r.BasicAuth()
  21. if !authOK {
  22. logger.Debug("[Middleware:BasicAuth] No authentication headers sent")
  23. w.WriteHeader(http.StatusUnauthorized)
  24. w.Write([]byte(errorResponse))
  25. return
  26. }
  27. if err := b.store.CheckPassword(username, password); err != nil {
  28. logger.Info("[Middleware:BasicAuth] Invalid username or password: %s", username)
  29. w.WriteHeader(http.StatusUnauthorized)
  30. w.Write([]byte(errorResponse))
  31. return
  32. }
  33. user, err := b.store.UserByUsername(username)
  34. if err != nil || user == nil {
  35. logger.Info("[Middleware:BasicAuth] User not found: %s", username)
  36. w.WriteHeader(http.StatusUnauthorized)
  37. w.Write([]byte(errorResponse))
  38. return
  39. }
  40. logger.Info("[Middleware:BasicAuth] User authenticated: %s", username)
  41. b.store.SetLastLogin(user.ID)
  42. ctx := r.Context()
  43. ctx = context.WithValue(ctx, UserIDContextKey, user.ID)
  44. ctx = context.WithValue(ctx, UserTimezoneContextKey, user.Timezone)
  45. ctx = context.WithValue(ctx, IsAdminUserContextKey, user.IsAdmin)
  46. ctx = context.WithValue(ctx, IsAuthenticatedContextKey, true)
  47. next.ServeHTTP(w, r.WithContext(ctx))
  48. })
  49. }
  50. // NewBasicAuthMiddleware returns a new BasicAuthMiddleware.
  51. func NewBasicAuthMiddleware(s *storage.Storage) *BasicAuthMiddleware {
  52. return &BasicAuthMiddleware{store: s}
  53. }