diff --git a/net/server/internal/api_addAccount.go b/net/server/internal/api_addAccount.go index 6d7b6653..cf1dd503 100644 --- a/net/server/internal/api_addAccount.go +++ b/net/server/internal/api_addAccount.go @@ -12,15 +12,13 @@ func AddAccount(w http.ResponseWriter, r *http.Request) { token, res := BearerAccountToken(r); if res != nil || token.TokenType != "create" { - LogMsg("authentication failed") - w.WriteHeader(http.StatusUnauthorized) + ErrResponse(w, http.StatusUnauthorized, res) return } username, password, err := BasicCredentials(r); if err != nil { - LogMsg("invalid basic credentials") - w.WriteHeader(http.StatusUnauthorized) + ErrResponse(w, http.StatusUnauthorized, err) return } @@ -29,8 +27,7 @@ func AddAccount(w http.ResponseWriter, r *http.Request) { privatePem := ExportRsaPrivateKeyAsPemStr(privateKey) publicPem, err := ExportRsaPublicKeyAsPemStr(publicKey) if err != nil { - LogMsg("failed generate key") - w.WriteHeader(http.StatusInternalServerError) + ErrResponse(w, http.StatusInternalServerError, err) return } @@ -66,8 +63,7 @@ func AddAccount(w http.ResponseWriter, r *http.Request) { return nil; }); if err != nil { - LogMsg("failed to create account"); - w.WriteHeader(http.StatusInternalServerError) + ErrResponse(w, http.StatusInternalServerError, err) return } diff --git a/net/server/internal/api_addAccountApp.go b/net/server/internal/api_addAccountApp.go index 936aca55..f0bc37d1 100644 --- a/net/server/internal/api_addAccountApp.go +++ b/net/server/internal/api_addAccountApp.go @@ -12,15 +12,13 @@ func AddAccountApp(w http.ResponseWriter, r *http.Request) { id, err := AccountLogin(r) if err != nil { - LogMsg("failed to login") - w.WriteHeader(http.StatusUnauthorized); + ErrResponse(w, http.StatusUnauthorized, err) return } data, res := securerandom.Bytes(4) if res != nil { - LogMsg("failed to generate token") - w.WriteHeader(http.StatusInternalServerError) + ErrResponse(w, http.StatusInternalServerError, res) return } token := hex.EncodeToString(data) @@ -31,9 +29,8 @@ func AddAccountApp(w http.ResponseWriter, r *http.Request) { Token: token, Expires: time.Now().Unix() + APP_ATTACHEXPIRE, }; - if store.DB.Create(&accountToken).Error != nil { - LogMsg("failed to store token") - w.WriteHeader(http.StatusInternalServerError) + if err := store.DB.Create(&accountToken).Error; err != nil { + ErrResponse(w, http.StatusInternalServerError, err) return } diff --git a/net/server/internal/api_addNodeAccount.go b/net/server/internal/api_addNodeAccount.go index 32c100e2..90c74d47 100644 --- a/net/server/internal/api_addNodeAccount.go +++ b/net/server/internal/api_addNodeAccount.go @@ -10,16 +10,14 @@ import ( func AddNodeAccount(w http.ResponseWriter, r *http.Request) { - if !AdminLogin(r) { - LogMsg("invalid admin credentials"); - w.WriteHeader(http.StatusUnauthorized); + if err := AdminLogin(r); err != nil { + ErrResponse(w, http.StatusUnauthorized, err) return } data, err := securerandom.Bytes(16) if err != nil { - LogMsg("failed to generate token"); - w.WriteHeader(http.StatusInternalServerError); + ErrResponse(w, http.StatusInternalServerError, err) return } token := hex.EncodeToString(data) @@ -30,9 +28,8 @@ func AddNodeAccount(w http.ResponseWriter, r *http.Request) { Expires: time.Now().Unix() + APP_CREATEEXPIRE, }; - if store.DB.Create(&accountToken).Error != nil { - LogMsg("failed to store token"); - w.WriteHeader(http.StatusInternalServerError); + if err := store.DB.Create(&accountToken).Error; err != nil { + ErrResponse(w, http.StatusInternalServerError, err) return } diff --git a/net/server/internal/api_getNodeConfig.go b/net/server/internal/api_getNodeConfig.go index 3ab640c4..5657b705 100644 --- a/net/server/internal/api_getNodeConfig.go +++ b/net/server/internal/api_getNodeConfig.go @@ -7,9 +7,8 @@ import ( func GetNodeConfig(w http.ResponseWriter, r *http.Request) { // validate login - if !AdminLogin(r) { - LogMsg("SetNodeConfig - invalid admin credentials"); - w.WriteHeader(http.StatusUnauthorized); + if err := AdminLogin(r); err != nil { + ErrResponse(w, http.StatusUnauthorized, err) return } diff --git a/net/server/internal/api_getProfile.go b/net/server/internal/api_getProfile.go index 687a1cce..ab3a10ee 100644 --- a/net/server/internal/api_getProfile.go +++ b/net/server/internal/api_getProfile.go @@ -6,13 +6,13 @@ import ( func GetProfile(w http.ResponseWriter, r *http.Request) { - account, res := BearerAppToken(r, true); - if res != nil { - w.WriteHeader(http.StatusUnauthorized) + account, err := BearerAppToken(r, true); + if err != nil { + ErrResponse(w, http.StatusUnauthorized, err) return } if account.Disabled { - w.WriteHeader(http.StatusGone); + ErrResponse(w, http.StatusGone, nil) return } detail := account.AccountDetail diff --git a/net/server/internal/api_setNodeConfig.go b/net/server/internal/api_setNodeConfig.go index 74256087..288b5858 100644 --- a/net/server/internal/api_setNodeConfig.go +++ b/net/server/internal/api_setNodeConfig.go @@ -1,7 +1,6 @@ package databag import ( - "log" "net/http" "gorm.io/gorm" "gorm.io/gorm/clause" @@ -11,16 +10,15 @@ import ( func SetNodeConfig(w http.ResponseWriter, r *http.Request) { // validate login - if !AdminLogin(r) { - log.Printf("SetNodeConfig - invalid admin credentials"); - w.WriteHeader(http.StatusUnauthorized); + if err := AdminLogin(r); err != nil { + ErrResponse(w, http.StatusUnauthorized, err) return } // parse node config var config NodeConfig - if ParseRequest(r, w, &config) != nil { - w.WriteHeader(http.StatusBadRequest) + if err := ParseRequest(r, w, &config); err != nil { + ErrResponse(w, http.StatusBadRequest, err) return } @@ -54,8 +52,7 @@ func SetNodeConfig(w http.ResponseWriter, r *http.Request) { return nil; }) if(err != nil) { - LogMsg("failed to store config") - w.WriteHeader(http.StatusInternalServerError) + ErrResponse(w, http.StatusInternalServerError, err) return } diff --git a/net/server/internal/auth.go b/net/server/internal/auth.go index e08334d9..0c84b60f 100644 --- a/net/server/internal/auth.go +++ b/net/server/internal/auth.go @@ -15,31 +15,31 @@ type accountLogin struct { Password []byte } -func AdminLogin(r *http.Request) bool { +func AdminLogin(r *http.Request) error { // extract request auth - username, password, ok := r.BasicAuth(); + username, password, ok := r.BasicAuth() if !ok || username == "" || password == "" { - return false + return errors.New("invalid credentials") } // nothing to do if not configured if !getBoolConfigValue(CONFIG_CONFIGURED, false) { - return false; + return errors.New("node not configured") } // compare username if getStrConfigValue(CONFIG_USERNAME, "") != username { - return false + return errors.New("admin username error") } // compare password p := getBinConfigValue(CONFIG_PASSWORD, nil); if bcrypt.CompareHashAndPassword(p, []byte(password)) != nil { - return false + return errors.New("admin password error") } - return true; + return nil } func AccountLogin(r *http.Request) (uint, error) { @@ -72,11 +72,13 @@ func BearerAccountToken(r *http.Request) (store.AccountToken, error) { // find token record var accountToken store.AccountToken - err := store.DB.Where("token = ?", token).First(&accountToken).Error + if err := store.DB.Where("token = ?", token).First(&accountToken).Error; err != nil { + return accountToken, err + } if accountToken.Expires < time.Now().Unix() { return accountToken, errors.New("expired token") } - return accountToken, err + return accountToken, nil } func BearerAppToken(r *http.Request, detail bool) (store.Account, error) { @@ -88,12 +90,12 @@ func BearerAppToken(r *http.Request, detail bool) (store.Account, error) { // find token record var app store.App if detail { - if store.DB.Preload("Account.AccountDetail").Where("token = ?", token).First(&app).Error != nil { - return app.Account, errors.New("failed to load account"); + if err := store.DB.Preload("Account.AccountDetail").Where("token = ?", token).First(&app).Error; err != nil { + return app.Account, err } } else { - if store.DB.Preload("Account").Where("token = ?", token).First(&app).Error != nil { - return app.Account, errors.New("failed to load account"); + if err := store.DB.Preload("Account").Where("token = ?", token).First(&app).Error; err != nil { + return app.Account, err } } return app.Account, nil @@ -111,14 +113,12 @@ func BasicCredentials(r *http.Request) (string, []byte, error) { // decode basic auth credentials, err := base64.StdEncoding.DecodeString(token) if err != nil { - LogMsg("faield to decode basic credentials"); return username, password, err } // parse credentials login := strings.Split(string(credentials), ":"); if login[0] == "" || login[1] == "" { - LogMsg("failed to parse basic credentials"); return username, password, errors.New("invalid credentials") } username = login[0] @@ -126,7 +126,6 @@ func BasicCredentials(r *http.Request) (string, []byte, error) { // hash password password, err = bcrypt.GenerateFromPassword([]byte(login[1]), bcrypt.DefaultCost) if err != nil { - LogMsg("failed to hash password") return username, password, err } diff --git a/net/server/internal/logger.go b/net/server/internal/logger.go index f7bbffb5..0fc8c08c 100644 --- a/net/server/internal/logger.go +++ b/net/server/internal/logger.go @@ -38,7 +38,11 @@ func Logger(inner http.Handler, name string) http.Handler { } func ErrResponse(w http.ResponseWriter, code int, err error) { - ErrMsg(err) + if !hideLog && err != nil { + _, file, line, _ := runtime.Caller(1) + p, _ := os.Getwd() + log.Printf("%s:%d %s", strings.TrimPrefix(file, p), line, err.Error()) + } w.WriteHeader(code) } @@ -47,7 +51,6 @@ func ErrMsg(err error) { _, file, line, _ := runtime.Caller(1) p, _ := os.Getwd() log.Printf("%s:%d %s", strings.TrimPrefix(file, p), line, err.Error()) - pretty.Println(err) } } diff --git a/net/server/internal/status_test.go b/net/server/internal/status_test.go index 3974fcc0..da2ca124 100644 --- a/net/server/internal/status_test.go +++ b/net/server/internal/status_test.go @@ -4,6 +4,7 @@ import ( "net/url" "net/http" "net/http/httptest" + "github.com/gorilla/websocket" ) type StatusHandler struct {} @@ -12,10 +13,14 @@ func (h *StatusHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { Status(w, r) } -func StartTestWebsocketServer() string { +func getTestWebsocket() *websocket.Conn { h := StatusHandler{} s := httptest.NewServer(&h) wsUrl, _ := url.Parse(s.URL) wsUrl.Scheme = "ws" - return wsUrl.String() + ws, _, err := websocket.DefaultDialer.Dial(wsUrl.String(), nil) + if err != nil { + PrintMsg(err.Error()); + } + return ws } diff --git a/net/server/internal/ucAttachApp_test.go b/net/server/internal/ucAttachApp_test.go index 985c0672..cfcdcba4 100644 --- a/net/server/internal/ucAttachApp_test.go +++ b/net/server/internal/ucAttachApp_test.go @@ -9,15 +9,12 @@ import ( "crypto/rsa" "crypto" "time" + "github.com/gorilla/websocket" "github.com/stretchr/testify/assert" - "github.com/gorilla/websocket" ) func TestAttachAccount(t *testing.T) { - // setup websocket server - wsUrl := StartTestWebsocketServer() - // get account token r, w, _ := NewRequest("POST", "/admin/accounts", nil) SetBasicAuth(r, "admin:pass") @@ -84,7 +81,7 @@ func TestAttachAccount(t *testing.T) { assert.Less(t, cur - 60, auth.Timestamp) // app connects websocket - ws, _, _ := websocket.DefaultDialer.Dial(wsUrl, nil) + ws := getTestWebsocket() announce := Announce{ AppToken: access } msg, _ := json.Marshal(&announce) ws.WriteMessage(websocket.TextMessage, msg)