Commit test program

This commit is contained in:
Melon 2024-05-12 22:23:34 +01:00
parent fff0b27a95
commit e3f5f4371d
Signed by: melon
GPG Key ID: 6C9D970C50D26A25
3 changed files with 67 additions and 2 deletions

1
.gitignore vendored
View File

@ -1,2 +1 @@
.idea/ .idea/
cardcal-auth-tester

18
auth.go
View File

@ -3,7 +3,9 @@ package cardcaldav
import ( import (
"cardcaldav/database" "cardcaldav/database"
"context" "context"
"database/sql"
"errors" "errors"
"github.com/charmbracelet/log"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
"net/http" "net/http"
"strings" "strings"
@ -34,6 +36,21 @@ type ProviderMiddleware interface {
var authError = errors.New("auth context error") var authError = errors.New("auth context error")
func NewAuth(dbStr string, logger *log.Logger) *Auth {
dbOpen, err := sql.Open("mysql", dbStr)
if err != nil {
logger.Fatal("sql.Open()", "err", err)
}
err = dbOpen.Ping()
if err != nil {
logger.Fatal("db.Ping()", "err", err)
}
dbQueries := database.New(dbOpen)
return &Auth{DB: dbQueries}
}
type Auth struct { type Auth struct {
DB *database.Queries DB *database.Queries
} }
@ -58,7 +75,6 @@ func (a *Auth) Middleware(next http.Handler) http.Handler {
} }
r = r.WithContext(NewContext(r.Context(), &Context{UserName: username})) r = r.WithContext(NewContext(r.Context(), &Context{UserName: username}))
r.BasicAuth()
next.ServeHTTP(w, r) next.ServeHTTP(w, r)
}) })
} }

View File

@ -0,0 +1,50 @@
package main
import (
"cardcaldav"
"context"
"flag"
"fmt"
"github.com/charmbracelet/log"
"golang.org/x/term"
"os"
)
var Logger = log.NewWithOptions(os.Stderr, log.Options{
ReportTimestamp: true,
ReportCaller: true,
})
func main() {
var un, dbStr string
var debugMode bool
flag.StringVar(&un, "un", "", "username of user to authenticate")
flag.StringVar(&dbStr, "db", "", "Connection string for the database - user:password@tcp(127.0.0.1:3306)/dbname")
flag.BoolVar(&debugMode, "debug", false, "enable debug logging")
flag.Parse()
if debugMode {
Logger.SetLevel(log.DebugLevel)
}
if !term.IsTerminal(int(os.Stdin.Fd())) {
Logger.Fatal("No terminal input found")
}
auth := cardcaldav.NewAuth(dbStr, Logger)
_, _ = fmt.Fprint(os.Stderr, "Password: ")
password, err := term.ReadPassword(int(os.Stdin.Fd()))
if err != nil {
Logger.Fatal("ReadPassword()", "err", err)
}
_, _ = fmt.Fprintln(os.Stderr)
Logger.Info("Verifying password...")
err = auth.ValidateCredentials(context.Background(), un, string(password))
if err != nil {
Logger.Fatal("auth.ValidateCredentials()", "err", err)
}
Logger.Info("Password verified")
}