log message cleanup

This commit is contained in:
Roland Osborne 2022-01-19 12:07:57 -08:00
parent 694b811a19
commit da272f386b
10 changed files with 53 additions and 63 deletions

View File

@ -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
}

View File

@ -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
}

View File

@ -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
}

View File

@ -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
}

View File

@ -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

View File

@ -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
}

View File

@ -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
}

View File

@ -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)
}
}

View File

@ -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
}

View File

@ -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)