1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
package basic_auth
import (
"context"
"fmt"
"net/http"
"time"
"git.adyxax.org/adyxax/tfstated/pkg/database"
"git.adyxax.org/adyxax/tfstated/pkg/helpers"
"git.adyxax.org/adyxax/tfstated/pkg/model"
)
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"`)
helpers.ErrorResponse(w, http.StatusUnauthorized, fmt.Errorf("Unauthorized"))
return
}
account, err := db.LoadAccountByUsername(username)
if err != nil {
helpers.ErrorResponse(w, http.StatusInternalServerError, err)
return
}
if account == nil || !account.CheckPassword(password) {
helpers.ErrorResponse(w, http.StatusForbidden, fmt.Errorf("Forbidden"))
return
}
now := time.Now().UTC()
_, err = db.Exec(`UPDATE accounts SET last_login = ? WHERE id = ?`, now.Unix(), account.Id)
if err != nil {
helpers.ErrorResponse(w, http.StatusInternalServerError, err)
return
}
ctx := context.WithValue(r.Context(), model.AccountContextKey{}, account)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
|