Interrogare il database per l'autenticazione di base utilizzando GO-HTTP-AUTH con Martini-Go
-
21-12-2019 - |
Domanda
Sto tentando di utilizzare Go-HTTP-AUTH con Martini-Go.Nell'esempio qui indicato qui - https://github.com/abbot/go-http-auth
package main
import (
auth "github.com/abbot/go-http-auth"
"fmt"
"net/http"
)
func Secret(user, realm string) string {
if user == "john" {
// password is "hello"
return "$1$dlPL2MqE$oQmn16q49SqdmhenQuNgs1"
}
return ""
}
func handle(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
fmt.Fprintf(w, "<html><body><h1>Hello, %s!</h1></body></html>", r.Username)
}
func main() {
db, err := sql.Open("postgres", "postgres://blabla:blabla@localhost/my_db")
authenticator := auth.NewBasicAuthenticator("example.com", Secret)
m := martini.Classic()
m.Map(db)
m.Get("/users", authenticator.Wrap(MyUserHandler))
m.Run()
}
.
La funzione segreta utilizza un utente hardcoded "John".
L'autenticazione ha esito positivo quando eseguo
curl --user john:hello localhost:3000/users
.
Ovviamente, questo è un esempio banale con nome utente e password hardcoded.
Ora sto cambiando la funzione Secret
in questo
func Secret(user, realm string) string {
fmt.Println("Executing Secret")
var db *sql.DB
var (
username string
password string
)
err := db.QueryRow("select username, password from users where username = ?", user).Scan(&username, &password)
if err == sql.ErrNoRows {
return ""
}
if err != nil {
log.Fatal(err)
}
//if user == "john" {
//// password is "hello"
//return "$1$dlPL2MqE$oQmn16q49SqdmhenQuNgs1"
//}
//return ""
return ""
}
.
Ma fallisce con PANIC: runtime error: invalid memory address or nil pointer dereference.
che è ovviamente perché sto tentando di istanziare var db *sql.DB
nella funzione Secret
.Non riesco a passare db *sql.DB
nella funzione Secret
perché auth.BasicNewAuthentication
si aspetta un argomento Secret
che è conforme a type func (string, string) string
.
Come posso implementare correttamente la mia query del database e restituire la password per il confronto?
Soluzione
È possibile utilizzare una semplice chiusura per passare in un riferimento al DB alla funzione Authenticator:
authenticator := auth.NewBasicAuthenticator("example.com", func(user, realm string) string {
return Secret(db, user, realm)
})
.
... e quindi modificare il Secret
per accettare il database come primo argomento:
func Secret(db *sql.DB, user, realm string) string {
// do your db lookup here…
}
. Altri suggerimenti
Approccio alternativo alle Attilas Rispondi.È possibile definire una struttura, definire il gestore Secret()
su di esso e passare solo la funzione di riferimento (GO mantiene il riferimento al "proprietario") nel authhandler
.
type SecretDb struct {
db *DB
}
func (db *SecretDb) Secret(user, realm string) string {
// .. use db.db here
}
func main() {
secretdb = SecretDb{db}
...
auth.NewBasicAuthenticator("example.com", secretdb.Secret)
...
}
.