chore(tfstated): refactor helpers to their own package
This commit is contained in:
parent
5b6da56089
commit
25ed1188ed
11 changed files with 78 additions and 62 deletions
|
@ -2,10 +2,12 @@ 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"
|
||||
)
|
||||
|
||||
|
@ -15,26 +17,22 @@ func Middleware(db *database.DB) func(http.Handler) http.Handler {
|
|||
username, password, ok := r.BasicAuth()
|
||||
if !ok {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="tfstated", charset="UTF-8"`)
|
||||
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||||
helpers.ErrorResponse(w, http.StatusUnauthorized, fmt.Errorf("Unauthorized"))
|
||||
return
|
||||
}
|
||||
account, err := db.LoadAccountByUsername(username)
|
||||
if err != nil {
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
helpers.ErrorResponse(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
if account == nil {
|
||||
http.Error(w, "Forbidden", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if !account.CheckPassword(password) {
|
||||
http.Error(w, "Forbidden", http.StatusForbidden)
|
||||
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 {
|
||||
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||
helpers.ErrorResponse(w, http.StatusInternalServerError, err)
|
||||
return
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), model.AccountContextKey{}, account)
|
||||
|
|
|
@ -7,6 +7,7 @@ import (
|
|||
"log/slog"
|
||||
"time"
|
||||
|
||||
"git.adyxax.org/adyxax/tfstated/pkg/helpers"
|
||||
"git.adyxax.org/adyxax/tfstated/pkg/model"
|
||||
"go.n16f.net/uuid"
|
||||
)
|
||||
|
@ -69,8 +70,8 @@ func (db *DB) InitAdminAccount() error {
|
|||
if err = password.Generate(uuid.V4); err != nil {
|
||||
return fmt.Errorf("failed to generate initial admin password: %w", err)
|
||||
}
|
||||
salt := model.GenerateSalt()
|
||||
hash := model.HashPassword(password.String(), salt)
|
||||
salt := helpers.GenerateSalt()
|
||||
hash := helpers.HashPassword(password.String(), salt)
|
||||
if _, err = tx.ExecContext(db.ctx,
|
||||
`INSERT INTO accounts(username, salt, password_hash, is_admin)
|
||||
VALUES ("admin", :salt, :hash, TRUE)
|
||||
|
|
21
pkg/helpers/crypto.go
Normal file
21
pkg/helpers/crypto.go
Normal file
|
@ -0,0 +1,21 @@
|
|||
package helpers
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
|
||||
"git.adyxax.org/adyxax/tfstated/pkg/scrypto"
|
||||
"golang.org/x/crypto/pbkdf2"
|
||||
)
|
||||
|
||||
const (
|
||||
PBKDF2Iterations = 600000
|
||||
SaltSize = 32
|
||||
)
|
||||
|
||||
func GenerateSalt() []byte {
|
||||
return scrypto.RandomBytes(SaltSize)
|
||||
}
|
||||
|
||||
func HashPassword(password string, salt []byte) []byte {
|
||||
return pbkdf2.Key([]byte(password), salt, PBKDF2Iterations, 32, sha256.New)
|
||||
}
|
17
pkg/helpers/error.go
Normal file
17
pkg/helpers/error.go
Normal file
|
@ -0,0 +1,17 @@
|
|||
package helpers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func ErrorResponse(w http.ResponseWriter, status int, err error) {
|
||||
type errorResponse struct {
|
||||
Msg string `json:"msg"`
|
||||
Status int `json:"status"`
|
||||
}
|
||||
_ = Encode(w, status, &errorResponse{
|
||||
Msg: fmt.Sprintf("%+v", err),
|
||||
Status: status,
|
||||
})
|
||||
}
|
25
pkg/helpers/json.go
Normal file
25
pkg/helpers/json.go
Normal file
|
@ -0,0 +1,25 @@
|
|||
package helpers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func Decode(r *http.Request, data any) error {
|
||||
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
|
||||
return fmt.Errorf("failed to decode json: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func Encode(w http.ResponseWriter, status int, data any) error {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
if err := json.NewEncoder(w).Encode(data); err != nil {
|
||||
slog.Error("failed to encode json", "err", err)
|
||||
return fmt.Errorf("failed to encode json: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
|
@ -1,17 +1,10 @@
|
|||
package model
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"time"
|
||||
|
||||
"git.adyxax.org/adyxax/tfstated/pkg/scrypto"
|
||||
"golang.org/x/crypto/pbkdf2"
|
||||
)
|
||||
|
||||
const (
|
||||
PBKDF2Iterations = 600000
|
||||
SaltSize = 32
|
||||
"git.adyxax.org/adyxax/tfstated/pkg/helpers"
|
||||
)
|
||||
|
||||
type AccountContextKey struct{}
|
||||
|
@ -28,14 +21,6 @@ type Account struct {
|
|||
}
|
||||
|
||||
func (account *Account) CheckPassword(password string) bool {
|
||||
hash := HashPassword(password, account.Salt)
|
||||
hash := helpers.HashPassword(password, account.Salt)
|
||||
return subtle.ConstantTimeCompare(hash, account.PasswordHash) == 1
|
||||
}
|
||||
|
||||
func GenerateSalt() []byte {
|
||||
return scrypto.RandomBytes(SaltSize)
|
||||
}
|
||||
|
||||
func HashPassword(password string, salt []byte) []byte {
|
||||
return pbkdf2.Key([]byte(password), salt, PBKDF2Iterations, 32, sha256.New)
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue