2024-11-14 01:34:29 +01:00
|
|
|
package basic_auth
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-11-17 00:05:22 +01:00
|
|
|
"fmt"
|
2024-11-14 01:34:29 +01:00
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"git.adyxax.org/adyxax/tfstated/pkg/database"
|
2024-11-17 00:05:22 +01:00
|
|
|
"git.adyxax.org/adyxax/tfstated/pkg/helpers"
|
2024-11-15 23:48:35 +01:00
|
|
|
"git.adyxax.org/adyxax/tfstated/pkg/model"
|
2024-11-14 01:34:29 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
func Middleware(db *database.DB) func(http.Handler) http.Handler {
|
|
|
|
return func(next http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
username, password, ok := r.BasicAuth()
|
|
|
|
if !ok {
|
|
|
|
w.Header().Set("WWW-Authenticate", `Basic realm="tfstated", charset="UTF-8"`)
|
2024-11-17 00:05:22 +01:00
|
|
|
helpers.ErrorResponse(w, http.StatusUnauthorized, fmt.Errorf("Unauthorized"))
|
2024-11-14 01:34:29 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
account, err := db.LoadAccountByUsername(username)
|
|
|
|
if err != nil {
|
2024-11-17 00:05:22 +01:00
|
|
|
helpers.ErrorResponse(w, http.StatusInternalServerError, err)
|
2024-11-14 01:34:29 +01:00
|
|
|
return
|
|
|
|
}
|
2024-11-17 00:05:22 +01:00
|
|
|
if account == nil || !account.CheckPassword(password) {
|
|
|
|
helpers.ErrorResponse(w, http.StatusForbidden, fmt.Errorf("Forbidden"))
|
2024-11-14 01:34:29 +01:00
|
|
|
return
|
|
|
|
}
|
|
|
|
now := time.Now().UTC()
|
|
|
|
_, err = db.Exec(`UPDATE accounts SET last_login = ? WHERE id = ?`, now.Unix(), account.Id)
|
|
|
|
if err != nil {
|
2024-11-17 00:05:22 +01:00
|
|
|
helpers.ErrorResponse(w, http.StatusInternalServerError, err)
|
2024-11-14 01:34:29 +01:00
|
|
|
return
|
|
|
|
}
|
2024-11-15 23:48:35 +01:00
|
|
|
ctx := context.WithValue(r.Context(), model.AccountContextKey{}, account)
|
2024-11-14 01:34:29 +01:00
|
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|