basic_auth.go 1.8 KB

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