- Clarified web handler name

- Implemented Configuration Loader with unauthorized error handling
- More elaborate test user config
- Use Viper Unmarshalling for User Config loading
- Centralized password hasing code
This commit is contained in:
2021-08-22 14:36:55 +02:00
parent 9f1b9f1690
commit 9a31bbc912
4 changed files with 98 additions and 17 deletions

View File

@ -7,7 +7,6 @@ import (
"gitea.nehmer.net/torben/dyndns/service"
"github.com/gorilla/mux"
"golang.org/x/crypto/bcrypt"
)
func Server() {
@ -15,7 +14,7 @@ func Server() {
r.StrictSlash(true)
r.HandleFunc("/hello", handleHello)
r.HandleFunc("/update", handleDNSUpdate)
r.HandleFunc("/update", handleUpdate)
log.Printf("Listening to: %s", C.ListenAddress)
go log.Fatal(http.ListenAndServe(C.ListenAddress, r))
@ -30,7 +29,7 @@ func handleHello(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "<html><body><p>Hello World</p></body></html>")
}
func handleDNSUpdate(w http.ResponseWriter, r *http.Request) {
func handleUpdate(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
@ -43,11 +42,16 @@ func handleDNSUpdate(w http.ResponseWriter, r *http.Request) {
return
}
v, err := service.LoadConfigForUser(ur.UserName)
uc, err := service.LoadConfigForUser(ur.UserName, ur.Password)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
if _, ok := err.(*service.UnauthorizedError); ok {
http.Error(w, err.Error(), http.StatusUnauthorized)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
v := uc.DB
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintln(w, "OK")
@ -57,7 +61,6 @@ func handleDNSUpdate(w http.ResponseWriter, r *http.Request) {
log.Println(ur.IPv6Net.Mask)
log.Println(v.AllSettings())
log.Printf("Request PW: %s, Config PW: %s", ur.Password, v.GetString("password"))
err = bcrypt.CompareHashAndPassword([]byte(v.GetString("password")), []byte(ur.Password))
log.Printf("PW Compare Result: %v", err)
fmt.Fprintln(w, "Unmarshalled userconfig:")
fmt.Fprintln(w, uc.PrettyPrint())
}