2017-11-20 06:10:04 +01:00
|
|
|
// Copyright 2017 Frédéric Guillot. All rights reserved.
|
|
|
|
// Use of this source code is governed by the Apache 2.0
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"log"
|
|
|
|
"net/http"
|
2017-11-28 06:30:04 +01:00
|
|
|
|
2017-12-13 06:48:13 +01:00
|
|
|
"github.com/miniflux/miniflux/storage"
|
2017-11-20 06:10:04 +01:00
|
|
|
)
|
|
|
|
|
2017-11-28 06:30:04 +01:00
|
|
|
// BasicAuthMiddleware is the middleware for HTTP Basic authentication.
|
2017-11-20 06:10:04 +01:00
|
|
|
type BasicAuthMiddleware struct {
|
|
|
|
store *storage.Storage
|
|
|
|
}
|
|
|
|
|
2017-11-28 06:30:04 +01:00
|
|
|
// Handler executes the middleware.
|
2017-11-20 06:10:04 +01:00
|
|
|
func (b *BasicAuthMiddleware) Handler(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
|
|
|
|
errorResponse := `{"error_message": "Not Authorized"}`
|
|
|
|
|
|
|
|
username, password, authOK := r.BasicAuth()
|
|
|
|
if !authOK {
|
|
|
|
log.Println("[Middleware:BasicAuth] No authentication headers sent")
|
|
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
|
|
w.Write([]byte(errorResponse))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := b.store.CheckPassword(username, password); err != nil {
|
|
|
|
log.Println("[Middleware:BasicAuth] Invalid username or password:", username)
|
|
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
|
|
w.Write([]byte(errorResponse))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-11-28 06:30:04 +01:00
|
|
|
user, err := b.store.UserByUsername(username)
|
2017-11-20 06:10:04 +01:00
|
|
|
if err != nil || user == nil {
|
|
|
|
log.Println("[Middleware:BasicAuth] User not found:", username)
|
|
|
|
w.WriteHeader(http.StatusUnauthorized)
|
|
|
|
w.Write([]byte(errorResponse))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
log.Println("[Middleware:BasicAuth] User authenticated:", username)
|
|
|
|
b.store.SetLastLogin(user.ID)
|
|
|
|
|
|
|
|
ctx := r.Context()
|
2017-11-28 06:30:04 +01:00
|
|
|
ctx = context.WithValue(ctx, UserIDContextKey, user.ID)
|
|
|
|
ctx = context.WithValue(ctx, UserTimezoneContextKey, user.Timezone)
|
|
|
|
ctx = context.WithValue(ctx, IsAdminUserContextKey, user.IsAdmin)
|
|
|
|
ctx = context.WithValue(ctx, IsAuthenticatedContextKey, true)
|
2017-11-20 06:10:04 +01:00
|
|
|
|
|
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2017-11-28 06:30:04 +01:00
|
|
|
// NewBasicAuthMiddleware returns a new BasicAuthMiddleware.
|
2017-11-20 06:10:04 +01:00
|
|
|
func NewBasicAuthMiddleware(s *storage.Storage) *BasicAuthMiddleware {
|
|
|
|
return &BasicAuthMiddleware{store: s}
|
|
|
|
}
|