From 8b2cd99cce0f3c5f34dd8de70d125b488ceb8dc8 Mon Sep 17 00:00:00 2001 From: yuli Date: Tue, 6 Aug 2024 17:16:37 +0300 Subject: [PATCH] using log function --- src/agreements_db.go | 20 +++++++-------- src/bunker_test.go | 2 +- src/expiration_test.go | 1 - src/lbasis_api.go | 3 ++- src/sessions_test.go | 3 ++- src/sharedrecords_db.go | 4 +-- src/sharedrecords_test.go | 4 +-- src/users_db.go | 53 ++++++++++++++++++++------------------- src/users_test.go | 8 +++--- src/utils.go | 14 +++++------ 10 files changed, 57 insertions(+), 55 deletions(-) diff --git a/src/agreements_db.go b/src/agreements_db.go index fad5c403..fc481a0d 100644 --- a/src/agreements_db.go +++ b/src/agreements_db.go @@ -2,7 +2,7 @@ package main import ( "encoding/json" - "fmt" + "log" "time" "github.com/securitybunker/databunker/src/storage" @@ -45,7 +45,7 @@ func (dbobj dbcon) acceptAgreement(userTOKEN string, mode string, identity strin // first check if this agreement exists, then update raw, err := dbobj.store.GetRecord2(storage.TblName.Agreements, "token", userTOKEN, "brief", brief) if err != nil { - fmt.Printf("error to find:%s", err) + log.Printf("Error to find:%s", err) return false, err } if raw != nil { @@ -59,7 +59,7 @@ func (dbobj dbcon) acceptAgreement(userTOKEN string, mode string, identity strin } else if len(identity) > 0 { raw, err := dbobj.store.GetRecord2(storage.TblName.Agreements, "who", encIdentity, "brief", brief) if err != nil { - fmt.Printf("error to find:%s", err) + log.Printf("Error to find:%s", err) return false, err } if raw != nil { @@ -84,7 +84,7 @@ func (dbobj dbcon) acceptAgreement(userTOKEN string, mode string, identity strin // in any case - insert record _, err := dbobj.store.CreateRecord(storage.TblName.Agreements, &bdoc) if err != nil { - fmt.Printf("error to insert record: %s\n", err) + log.Printf("Error to insert record: %s\n", err) return false, err } return true, nil @@ -113,7 +113,7 @@ func (dbobj dbcon) withdrawAgreement(userTOKEN string, brief string, mode string bdoc["status"] = "no" bdoc["lastmodifiedby"] = lastmodifiedby if len(userTOKEN) > 0 { - fmt.Printf("%s %s\n", userTOKEN, brief) + log.Printf("%s %s\n", userTOKEN, brief) dbobj.store.UpdateRecord2(storage.TblName.Agreements, "token", userTOKEN, "brief", brief, &bdoc, nil) } else if len(identity) > 0 { dbobj.store.UpdateRecord2(storage.TblName.Agreements, "who", encIdentity, "brief", brief, &bdoc, nil) @@ -143,7 +143,7 @@ func (dbobj dbcon) listAgreementRecords(userTOKEN string) ([]byte, int, error) { if err != nil { return nil, 0, err } - //fmt.Printf("Found multiple documents (array of pointers): %+v\n", results) + //log.Printf("Found multiple documents (array of pointers): %+v\n", results) return resultJSON, count, nil } @@ -164,7 +164,7 @@ func (dbobj dbcon) listAgreementRecordsByIdentity(identity string) ([]byte, int, if err != nil { return nil, 0, err } - //fmt.Printf("Found multiple documents (array of pointers): %+v\n", results) + //log.Printf("Found multiple documents (array of pointers): %+v\n", results) return resultJSON, count, nil } @@ -184,7 +184,7 @@ func (dbobj dbcon) viewAgreementRecord(userTOKEN string, brief string) ([]byte, if err != nil { return nil, err } - //fmt.Printf("Found multiple documents (array of pointers): %+v\n", results) + //log.Printf("Found multiple documents (array of pointers): %+v\n", results) return resultJSON, nil } @@ -201,9 +201,9 @@ func (dbobj dbcon) expireAgreementRecords(notifyURL string) error { bdoc["status"] = "expired" userTOKEN := rec["token"].(string) brief := rec["brief"].(string) - fmt.Printf("This Agreements record is expired: %s - %s\n", userTOKEN, brief) + log.Printf("This agreement record is expired: %s - %s\n", userTOKEN, brief) if len(userTOKEN) > 0 { - fmt.Printf("%s %s\n", userTOKEN, brief) + log.Printf("%s %s\n", userTOKEN, brief) dbobj.store.UpdateRecord2(storage.TblName.Agreements, "token", userTOKEN, "brief", brief, &bdoc, nil) notifyConsentChange(notifyURL, brief, "expired", "token", userTOKEN) } else { diff --git a/src/bunker_test.go b/src/bunker_test.go index 7506325b..0f38eda3 100644 --- a/src/bunker_test.go +++ b/src/bunker_test.go @@ -24,7 +24,7 @@ func helpServe0(request *http.Request) ([]byte, error) { request.Header.Set("Content-Type", "application/json") rr := httptest.NewRecorder() router.ServeHTTP(rr, request) - fmt.Printf("[%d] %s%s\n", rr.Code, request.Host, request.URL.Path) + log.Printf("[%d] %s%s\n", rr.Code, request.Host, request.URL.Path) if rr.Code != 200 { return rr.Body.Bytes(), fmt.Errorf("wrong status: %d", rr.Code) } diff --git a/src/expiration_test.go b/src/expiration_test.go index ba06b32c..d583df44 100644 --- a/src/expiration_test.go +++ b/src/expiration_test.go @@ -131,7 +131,6 @@ func TestExpCancel(t *testing.T) { func TestExpAuto(t *testing.T) { userJSON := `{"login":"william4"}` now := int32(time.Now().Unix())+1 - fmt.Printf("time %d\n", now) raw, _ := helpCreateUser(userJSON) if _, ok := raw["status"]; !ok || raw["status"].(string) != "ok" { t.Fatalf("Failed to create user") diff --git a/src/lbasis_api.go b/src/lbasis_api.go index 63b05205..7e3450dc 100644 --- a/src/lbasis_api.go +++ b/src/lbasis_api.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "log" "net/http" "reflect" @@ -108,7 +109,7 @@ func (e mainEnv) listLegalBasisRecords(w http.ResponseWriter, r *http.Request, p returnError(w, r, "internal error", 405, err, nil) return } - fmt.Printf("Total count of rows: %d\n", numRecords) + log.Printf("Total count of rows: %d\n", numRecords) w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(200) str := fmt.Sprintf(`{"status":"ok","total":%d,"rows":%s}`, numRecords, resultJSON) diff --git a/src/sessions_test.go b/src/sessions_test.go index 178c6061..a1b13eac 100644 --- a/src/sessions_test.go +++ b/src/sessions_test.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "log" "net/http/httptest" "strings" "testing" @@ -100,7 +101,7 @@ func TestCreateSessionAndSharedRecord(t *testing.T) { data = fmt.Sprintf(`{"expiration":"1d","session":"%s","fields":"cookie,missing"}`, sessionTOKEN) raw, _ = helpCreateSharedRecord("token", userTOKEN, data) recordTOKEN := raw["record"].(string) - fmt.Printf("User record token: %s\n", recordTOKEN) + log.Printf("User record token: %s\n", recordTOKEN) raw, _ = helpGetSharedRecord(recordTOKEN) if _, ok := raw["status"]; !ok || raw["status"].(string) != "ok" { t.Fatalf("Failed to get shared record: %s\n", raw["message"]) diff --git a/src/sharedrecords_db.go b/src/sharedrecords_db.go index 7fa09d03..dff834d4 100644 --- a/src/sharedrecords_db.go +++ b/src/sharedrecords_db.go @@ -2,7 +2,7 @@ package main import ( "errors" - "fmt" + "log" "strings" "time" @@ -25,7 +25,7 @@ func (dbobj dbcon) saveSharedRecord(userTOKEN string, fields string, expiration } } - fmt.Printf("Expiration is : %s\n", expiration) + log.Printf("Expiration is : %s\n", expiration) start, err := parseExpiration(expiration) if err != nil { return "", err diff --git a/src/sharedrecords_test.go b/src/sharedrecords_test.go index 54467844..d7d72f77 100644 --- a/src/sharedrecords_test.go +++ b/src/sharedrecords_test.go @@ -1,7 +1,7 @@ package main import ( - "fmt" + "log" "net/http/httptest" "strings" "testing" @@ -52,7 +52,7 @@ func TestCreateSharedRecord(t *testing.T) { t.Fatalf("Failed to create shared record: %s\n", raw["message"]) } recordTOKEN := raw["record"].(string) - fmt.Printf("User record token: %s\n", recordTOKEN) + log.Printf("User record token: %s\n", recordTOKEN) raw, _ = helpGetSharedRecord(recordTOKEN) if _, ok := raw["status"]; !ok || raw["status"].(string) != "ok" { t.Fatalf("Failed to get shared record: %s\n", raw["message"]) diff --git a/src/users_db.go b/src/users_db.go index 18dd462c..b0ac8f57 100644 --- a/src/users_db.go +++ b/src/users_db.go @@ -6,6 +6,7 @@ import ( "encoding/json" "errors" "fmt" + "log" "time" jsonpatch "github.com/evanphx/json-patch" @@ -32,7 +33,7 @@ func (dbobj dbcon) createUserRecord(parsedData userJSON, event *auditEvent) (str return "", err } encodedStr := base64.StdEncoding.EncodeToString(encoded) - //fmt.Printf("data %s %s\n", parsedData.jsonData, encodedStr) + //log.Printf("Data %s %s\n", parsedData.jsonData, encodedStr) bdoc["key"] = base64.StdEncoding.EncodeToString(userKeyBinary) bdoc["data"] = encodedStr //it is ok to use md5 here, it is only for data sanity @@ -58,10 +59,10 @@ func (dbobj dbcon) createUserRecord(parsedData userJSON, event *auditEvent) (str event.After = encodedStr event.Record = userTOKEN } - //fmt.Println("creating new user") + //log.Println("Creating new user") _, err = dbobj.store.CreateRecord(storage.TblName.Users, &bdoc) if err != nil { - fmt.Printf("error in create!\n") + log.Printf("Error in create!\n") return "", err } return userTOKEN, nil @@ -93,32 +94,32 @@ func (dbobj dbcon) updateUserExpStatus(userTOKEN string, status string) error { func (dbobj dbcon) generateTempLoginCode(userTOKEN string) int32 { rnd := randNum(6) - fmt.Printf("random: %d\n", rnd) + log.Printf("Random: %d\n", rnd) bdoc := bson.M{} bdoc["tempcode"] = rnd expired := int32(time.Now().Unix()) + 60 bdoc["tempcodeexp"] = expired - //fmt.Printf("op json: %s\n", update) + //log.Printf("op json: %s\n", update) dbobj.store.UpdateRecord(storage.TblName.Users, "token", userTOKEN, &bdoc) return rnd } func (dbobj dbcon) generateDemoLoginCode(userTOKEN string) int32 { rnd := int32(4444) - fmt.Printf("random: %d\n", rnd) + log.Printf("Demo random: %d\n", rnd) bdoc := bson.M{} bdoc["tempcode"] = 4444 expired := int32(time.Now().Unix()) + 60 bdoc["tempcodeexp"] = expired - //fmt.Printf("op json: %s\n", update) + //log.Printf("op json: %s\n", update) dbobj.store.UpdateRecord(storage.TblName.Users, "token", userTOKEN, &bdoc) return rnd } func (dbobj dbcon) validateUserRecordChange(oldUserJSON []byte, jsonDataPatch []byte, userTOKEN string, authResult string) (bool, error) { // prepare merge - //fmt.Printf("old json: %s\n", oldUserJSON) - //fmt.Printf("json patch: %s\n", jsonDataPatch) + //log.Printf("old json: %s\n", oldUserJSON) + //log.Printf("json patch: %s\n", jsonDataPatch) var newJSON []byte var err error if jsonDataPatch[0] == '{' { @@ -133,7 +134,7 @@ func (dbobj dbcon) validateUserRecordChange(oldUserJSON []byte, jsonDataPatch [] if err != nil { return false, err } - //fmt.Printf("result: %s\n", newJSON) + //log.Printf("result: %s\n", newJSON) return validateUserRecordChange(oldUserJSON, newJSON, authResult) } @@ -187,8 +188,8 @@ func (dbobj dbcon) updateUserRecordDo(jsonDataPatch []byte, userTOKEN string, ol oldEmail = normalizeEmail(raw2["email"].(string)) } // merge - //fmt.Printf("old json: %s\n", decrypted) - //fmt.Printf("json patch: %s\n", jsonDataPatch) + //log.Printf("old json: %s\n", decrypted) + //log.Printf("json patch: %s\n", jsonDataPatch) var newJSON []byte if jsonDataPatch[0] == '{' { newJSON, err = jsonpatch.MergePatch(decrypted, jsonDataPatch) @@ -202,7 +203,7 @@ func (dbobj dbcon) updateUserRecordDo(jsonDataPatch []byte, userTOKEN string, ol if err != nil { return nil, nil, false, err } - //fmt.Printf("result: %s\n", newJSON) + //log.Printf("result: %s\n", newJSON) var raw map[string]interface{} err = json.Unmarshal(newJSON, &raw) @@ -216,12 +217,12 @@ func (dbobj dbcon) updateUserRecordDo(jsonDataPatch []byte, userTOKEN string, ol keys := []string{"login", "email", "phone", "custom"} newEmail := "" for _, idx := range keys { - //fmt.Printf("Checking %s\n", idx) + //log.Printf("Checking %s\n", idx) actionCode := 1 newIdxFinalValue := "" if newIdxValue, ok3 := raw[idx]; ok3 { newIdxFinalValue = getIndexString(newIdxValue) - //fmt.Println("newIdxFinalValue0", newIdxFinalValue) + //log.Println("newIdxFinalValue0", newIdxFinalValue) if len(newIdxFinalValue) > 0 { if idx == "email" { newIdxFinalValue = normalizeEmail(newIdxFinalValue) @@ -230,30 +231,30 @@ func (dbobj dbcon) updateUserRecordDo(jsonDataPatch []byte, userTOKEN string, ol newIdxFinalValue = normalizePhone(newIdxFinalValue, conf.Sms.DefaultCountry) } } - //fmt.Println("newIdxFinalValue", newIdxFinalValue) + //log.Println("newIdxFinalValue", newIdxFinalValue) } if idxOldValue, ok := oldUserBson[idx+"idx"]; ok { if len(newIdxFinalValue) > 0 && len(idxOldValue.(string)) >= 0 { idxStringHashHex := hashString(dbobj.hash, newIdxFinalValue) if idxStringHashHex == idxOldValue.(string) { - //fmt.Println("index value NOT changed!") + //log.Println("Index value NOT changed!") actionCode = 0 } else { - //fmt.Println("index value changed!") + //log.Println("Index value changed!") } //} else { - // fmt.Println("old or new is empty") + // log.Println("Old or new is empty") } } if len(newIdxFinalValue) > 0 && actionCode == 1 { // check if new value is created - //fmt.Printf("adding index? %s\n", raw[idx]) + //log.Printf("Adding index? %s\n", raw[idx]) otherUserBson, _ := dbobj.lookupUserRecordByIndex(idx, newIdxFinalValue, conf) if otherUserBson != nil { // already exist user with same index value return nil, nil, true, fmt.Errorf("duplicate %s index", idx) } - //fmt.Printf("adding index3? %s\n", raw[idx]) + //log.Printf("Adding index3? %s\n", raw[idx]) bdoc[idx+"idx"] = hashString(dbobj.hash, newIdxFinalValue) } else if len(newIdxFinalValue) == 0 { bdel = append(bdel, idx+"idx") @@ -273,7 +274,7 @@ func (dbobj dbcon) updateUserRecordDo(jsonDataPatch []byte, userTOKEN string, ol // to make sure this record was not change by other thread //filter2 := bson.D{{"token", userTOKEN}, {"md5", sig}} - //fmt.Printf("op json: %s\n", update) + //log.Printf("op json: %s\n", update) result, err := dbobj.store.UpdateRecord2(storage.TblName.Users, "token", userTOKEN, "md5", sig, &bdoc, bdel) if err != nil { return nil, nil, false, err @@ -311,7 +312,7 @@ func (dbobj dbcon) lookupUserRecordByIndex(indexName string, indexValue string, return dbobj.store.GetRecord(storage.TblName.Users, "exptoken", indexValue) } idxStringHashHex := hashString(dbobj.hash, indexValue) - //fmt.Printf("loading by %s, value: %s\n", indexName, indexValue) + //log.Printf("Loading by %s, value: %s\n", indexName, indexValue) return dbobj.store.GetRecord(storage.TblName.Users, indexName+"idx", idxStringHashHex) } @@ -532,19 +533,19 @@ func (dbobj dbcon) deleteUserRecord(userJSON []byte, userTOKEN string, conf Conf bdoc := bson.M{} if _, ok := record["email"]; ok { - fmt.Printf("Preservice email idx\n") + log.Printf("Preservice email idx\n") bdoc["emailidx"] = oldUserBson["emailidx"].(string) } else { bdel = append(bdel, "emailidx") } if _, ok := record["phone"]; ok { - fmt.Printf("Preservice phone idx\n") + log.Printf("Preservice phone idx\n") bdoc["phoneidx"] = oldUserBson["phoneidx"].(string) } else { bdel = append(bdel, "phoneidx") } if _, ok := record["login"]; ok { - fmt.Printf("Preservice login idx\n") + log.Printf("Preservice login idx\n") bdoc["loginidx"] = oldUserBson["loginidx"].(string) } else { bdel = append(bdel, "loginidx") diff --git a/src/users_test.go b/src/users_test.go index 332d98fc..8220219b 100644 --- a/src/users_test.go +++ b/src/users_test.go @@ -1,7 +1,7 @@ package main import ( - "fmt" + "log" "encoding/json" "net/http/httptest" "strings" @@ -91,8 +91,8 @@ func TestCreateUpdateUser(t *testing.T) { } raw, _ = helpGetUser("phone", "775566998822") userRecord, _ := json.Marshal(raw["data"].(map[string]interface{})) - //fmt.Printf("get user %v\n", raw) - //fmt.Printf("user %s\n", string(userRecord)) + //log.Printf("get user %v\n", raw) + //log.Printf("user %s\n", string(userRecord)) afterUpdate := []byte(`{"devices":[{"name":"dev3"},{"name":"dev1","val":1},{"name":"updated"}],"name":"tom","phone":"775566998822"}`) if !jsonpatch.Equal(userRecord, afterUpdate) { t.Fatalf("Records are different") @@ -136,7 +136,7 @@ func TestCreateUpdateUser(t *testing.T) { if len(atoken) == 0 { t.Fatalf("Failed to extract atoken\n") } - fmt.Printf("Audit record: %s\n", atoken) + log.Printf("Audit record: %s\n", atoken) raw, _ = helpGetUserAuditEvent(atoken) if _, ok := raw["status"]; !ok || raw["status"].(string) != "ok" { t.Fatalf("Failed to get specific audit event\n") diff --git a/src/utils.go b/src/utils.go index 3b11736a..6ee5dd5c 100644 --- a/src/utils.go +++ b/src/utils.go @@ -46,14 +46,14 @@ func getMeta(r *http.Request) string { headers := bson.M{} for idx, val := range r.Header { idx0 := strings.ToLower(idx) - fmt.Printf("checking header: %s\n", idx0) + log.Printf("Checking header: %s\n", idx0) if contains(interestingHeaders, idx0) { headers[idx] = val[0] } } headersStr, _ := json.Marshal(headers) meta := fmt.Sprintf(`{"clientip":"%s","headers":%s}`, r.RemoteAddr, headersStr) - fmt.Printf("Meta: %s\n", meta) + log.Printf("Meta: %s\n", meta) return meta } */ @@ -126,7 +126,7 @@ func normalizeEmail(email0 string) string { email = strings.ToLower(email) email = strings.TrimSpace(email) if email0 != email { - fmt.Printf("email before: %s, after: %s\n", email0, email) + log.Printf("email before: %s, after: %s\n", email0, email) } return email } @@ -146,7 +146,7 @@ func normalizePhone(phone string, defaultCountry string) string { } res, err := libphonenumber.Parse(phone, defaultCountry) if err != nil { - fmt.Printf("failed to parse phone number: %s", phone) + log.Printf("Failed to parse phone number: %s", phone) return "" } phone = "+" + strconv.Itoa(int(*res.CountryCode)) + strconv.FormatUint(*res.NationalNumber, 10) @@ -350,7 +350,7 @@ func stringPatternMatch(pattern string, value string) bool { } func returnError(w http.ResponseWriter, r *http.Request, message string, code int, err error, event *auditEvent) { - fmt.Printf("%d %s %s\n", code, r.Method, r.URL.Path) + log.Printf("Return error: %d %s %s\n", code, r.Method, r.URL.Path) w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(code) fmt.Fprintf(w, `{"status":"error","message":%q}`, message) @@ -402,7 +402,7 @@ func (e mainEnv) enforceAuth(w http.ResponseWriter, r *http.Request, event *audi } */ } - fmt.Printf("403 Access denied\n") + log.Printf("403 Access denied\n") w.WriteHeader(http.StatusForbidden) w.Write([]byte("Access denied")) if event != nil { @@ -422,7 +422,7 @@ func (e mainEnv) enforceAdmin(w http.ResponseWriter, r *http.Request) string { } } } - fmt.Printf("403 Access denied\n") + log.Printf("403 Access denied\n") w.WriteHeader(http.StatusForbidden) w.Write([]byte("Access denied")) return ""