Skip to content

Commit

Permalink
using log function
Browse files Browse the repository at this point in the history
  • Loading branch information
stremovsky committed Aug 6, 2024
1 parent 7cf2f3e commit 8b2cd99
Show file tree
Hide file tree
Showing 10 changed files with 57 additions and 55 deletions.
20 changes: 10 additions & 10 deletions src/agreements_db.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package main

import (
"encoding/json"
"fmt"
"log"
"time"

"github.com/securitybunker/databunker/src/storage"
Expand Down Expand Up @@ -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 {
Expand All @@ -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 {
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
}

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

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

Expand All @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion src/bunker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
1 change: 0 additions & 1 deletion src/expiration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
3 changes: 2 additions & 1 deletion src/lbasis_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"fmt"
"log"
"net/http"
"reflect"

Expand Down Expand Up @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion src/sessions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"fmt"
"log"
"net/http/httptest"
"strings"
"testing"
Expand Down Expand Up @@ -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"])
Expand Down
4 changes: 2 additions & 2 deletions src/sharedrecords_db.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package main

import (
"errors"
"fmt"
"log"
"strings"
"time"

Expand All @@ -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
Expand Down
4 changes: 2 additions & 2 deletions src/sharedrecords_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package main

import (
"fmt"
"log"
"net/http/httptest"
"strings"
"testing"
Expand Down Expand Up @@ -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"])
Expand Down
53 changes: 27 additions & 26 deletions src/users_db.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
"log"
"time"

jsonpatch "github.com/evanphx/json-patch"
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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] == '{' {
Expand All @@ -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)
}

Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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")
Expand All @@ -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
Expand Down Expand Up @@ -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)
}

Expand Down Expand Up @@ -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")
Expand Down
8 changes: 4 additions & 4 deletions src/users_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package main

import (
"fmt"
"log"
"encoding/json"
"net/http/httptest"
"strings"
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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")
Expand Down
Loading

0 comments on commit 8b2cd99

Please sign in to comment.