miniflux/middleware/basic_auth.go

58 lines
1.6 KiB
Go
Raw Normal View History

2018-04-28 05:38:46 +02:00
// Copyright 2018 Frédéric Guillot. All rights reserved.
2017-11-20 06:10:04 +01:00
// 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"
"net/http"
2017-11-28 06:30:04 +01:00
"github.com/miniflux/miniflux/http/response/json"
2017-12-16 03:55:57 +01:00
"github.com/miniflux/miniflux/logger"
2017-11-20 06:10:04 +01:00
)
2018-04-28 05:38:46 +02:00
// BasicAuth handles HTTP basic authentication.
func (m *Middleware) BasicAuth(next http.Handler) http.Handler {
2017-11-20 06:10:04 +01:00
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
username, password, authOK := r.BasicAuth()
if !authOK {
2017-12-16 03:55:57 +01:00
logger.Debug("[Middleware:BasicAuth] No authentication headers sent")
json.Unauthorized(w)
2017-11-20 06:10:04 +01:00
return
}
2018-04-28 05:38:46 +02:00
if err := m.store.CheckPassword(username, password); err != nil {
2017-12-16 03:55:57 +01:00
logger.Info("[Middleware:BasicAuth] Invalid username or password: %s", username)
json.Unauthorized(w)
2017-11-20 06:10:04 +01:00
return
}
2018-04-28 05:38:46 +02:00
user, err := m.store.UserByUsername(username)
2017-12-29 22:53:02 +01:00
if err != nil {
logger.Error("[Middleware:BasicAuth] %v", err)
json.ServerError(w, err)
2017-12-29 22:53:02 +01:00
return
}
if user == nil {
2017-12-16 03:55:57 +01:00
logger.Info("[Middleware:BasicAuth] User not found: %s", username)
json.Unauthorized(w)
2017-11-20 06:10:04 +01:00
return
}
2017-12-16 03:55:57 +01:00
logger.Info("[Middleware:BasicAuth] User authenticated: %s", username)
2018-04-28 05:38:46 +02:00
m.store.SetLastLogin(user.ID)
2017-11-20 06:10:04 +01:00
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))
})
}