diff --git a/auth/auth.go b/auth/auth.go index e41c959f6..7f9086453 100644 --- a/auth/auth.go +++ b/auth/auth.go @@ -16,6 +16,7 @@ import ( "github.com/btcsuite/btcd/chaincfg/chainhash" "github.com/form3tech-oss/jwt-go" "github.com/stakwork/sphinx-tribes/config" + "github.com/stakwork/sphinx-tribes/logger" ) var ( @@ -41,7 +42,7 @@ func PubKeyContext(next http.Handler) http.Handler { } if token == "" { - fmt.Println("[auth] no token") + logger.Log.Info("[auth] no token") http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return } @@ -52,13 +53,13 @@ func PubKeyContext(next http.Handler) http.Handler { claims, err := DecodeJwt(token) if err != nil { - fmt.Println("Failed to parse JWT") + logger.Log.Info("Failed to parse JWT") http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return } if claims.VerifyExpiresAt(time.Now().UnixNano(), true) { - fmt.Println("Token has expired") + logger.Log.Info("Token has expired") http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return } @@ -69,9 +70,9 @@ func PubKeyContext(next http.Handler) http.Handler { pubkey, err := VerifyTribeUUID(token, true) if pubkey == "" || err != nil { - fmt.Println("[auth] no pubkey || err != nil") + logger.Log.Info("[auth] no pubkey || err != nil") if err != nil { - fmt.Println(err) + logger.Log.Error("%v", err) } http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return @@ -98,7 +99,7 @@ func PubKeyContextSuperAdmin(next http.Handler) http.Handler { } if token == "" { - fmt.Println("[auth] no token") + logger.Log.Info("[auth] no token") http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return } @@ -108,20 +109,20 @@ func PubKeyContextSuperAdmin(next http.Handler) http.Handler { claims, err := DecodeJwt(token) if err != nil { - fmt.Println("Failed to parse JWT") + logger.Log.Info("Failed to parse JWT") http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return } if claims.VerifyExpiresAt(time.Now().UnixNano(), true) { - fmt.Println("Token has expired") + logger.Log.Info("Token has expired") http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return } pubkey := fmt.Sprintf("%v", claims["pubkey"]) if !IsFreePass() && !AdminCheck(pubkey) { - fmt.Println("Not a super admin") + logger.Log.Info("Not a super admin") http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return } @@ -132,16 +133,16 @@ func PubKeyContextSuperAdmin(next http.Handler) http.Handler { pubkey, err := VerifyTribeUUID(token, true) if pubkey == "" || err != nil { - fmt.Println("[auth] no pubkey || err != nil") + logger.Log.Info("[auth] no pubkey || err != nil") if err != nil { - fmt.Println(err) + logger.Log.Error("%v", err) } http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return } if !IsFreePass() && !AdminCheck(pubkey) { - fmt.Println("Not a super admin : auth") + logger.Log.Info("Not a super admin : auth") http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return } @@ -164,13 +165,13 @@ func ConnectionCodeContext(next http.Handler) http.Handler { token := r.Header.Get("token") if token == "" { - fmt.Println("[auth] no token") + logger.Log.Info("[auth] no token") http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return } if token != config.Connection_Auth { - fmt.Println("Not a super admin : auth") + logger.Log.Info("Not a super admin : auth") http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return } @@ -186,7 +187,7 @@ func CypressContext(next http.Handler) http.Handler { ctx := context.WithValue(r.Context(), ContextKey, "") next.ServeHTTP(w, r.WithContext(ctx)) } else { - fmt.Println("Endpoint is for testing only : test endpoint") + logger.Log.Info("Endpoint is for testing only : test endpoint") http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized) return } @@ -226,12 +227,12 @@ func VerifyTribeUUID(uuid string, checkTimestamp bool) (string, error) { // 5 MINUTE MAX now := time.Now().Unix() if int64(ts) < now-300 { - fmt.Println("TOO LATE!") + logger.Log.Info("TOO LATE!") return "", errors.New("too late") } if int64(ts) > now { - fmt.Println("TOO EARLY!") + logger.Log.Info("TOO EARLY!") return "", errors.New("too early") } } @@ -263,7 +264,7 @@ func VerifyAndExtract(msg, sig []byte) (string, bool, error) { // RecoverCompact both recovers the pubkey and validates the signature. pubKey, valid, err := btcecdsa.RecoverCompact(sig, digest) if err != nil { - fmt.Printf("ERR: %+v\n", err) + logger.Log.Error("ERR: %+v", err) return "", false, err } pubKeyHex := hex.EncodeToString(pubKey.SerializeCompressed()) diff --git a/db/alerts.go b/db/alerts.go index 99e260de1..c3646f6f8 100644 --- a/db/alerts.go +++ b/db/alerts.go @@ -10,7 +10,7 @@ import ( "os" "strconv" - "github.com/stakwork/sphinx-tribes/utils" + "github.com/stakwork/sphinx-tribes/logger" ) type Action struct { @@ -37,7 +37,7 @@ func (db database) ProcessAlerts(p Person) { alertTribeUuid := os.Getenv("ALERT_TRIBE_UUID") botId := os.Getenv("ALERT_BOT_ID") if relayUrl == "" || alertSecret == "" || alertTribeUuid == "" || botId == "" { - utils.Log.Info("Ticket alerts: ENV information not found") + logger.Log.Info("Ticket alerts: ENV information not found") return } @@ -51,14 +51,14 @@ func (db database) ProcessAlerts(p Person) { // Check that new ticket time exists if p.NewTicketTime == 0 { - utils.Log.Info("Ticket alerts: New ticket time not found") + logger.Log.Info("Ticket alerts: New ticket time not found") return } var issue PropertyMap = nil wanteds, ok := p.Extras["wanted"].([]interface{}) if !ok { - utils.Log.Info("Ticket alerts: No tickets found for person") + logger.Log.Info("Ticket alerts: No tickets found for person") } for _, wanted := range wanteds { w, ok2 := wanted.(map[string]interface{}) @@ -77,19 +77,19 @@ func (db database) ProcessAlerts(p Person) { } if issue == nil { - utils.Log.Info("Ticket alerts: No ticket identified with the correct timestamp") + logger.Log.Info("Ticket alerts: No ticket identified with the correct timestamp") } languages, ok4 := issue["codingLanguage"].([]interface{}) if !ok4 { - utils.Log.Info("Ticket alerts: No languages found in ticket") + logger.Log.Info("Ticket alerts: No languages found in ticket") return } var err error people, err := db.GetPeopleForNewTicket(languages) if err != nil { - utils.Log.Error("Ticket alerts: DB query to get interested people failed: %v", err) + logger.Log.Error("Ticket alerts: DB query to get interested people failed: %v", err) return } @@ -99,12 +99,12 @@ func (db database) ProcessAlerts(p Person) { action.Pubkey = per.OwnerPubKey buf, err := json.Marshal(action) if err != nil { - utils.Log.Error("Ticket alerts: Unable to parse message into byte buffer: %v", err) + logger.Log.Error("Ticket alerts: Unable to parse message into byte buffer: %v", err) return } request, err := http.NewRequest("POST", relayUrl, bytes.NewReader(buf)) if err != nil { - utils.Log.Error("Ticket alerts: Unable to create a request to send to relay: %v", err) + logger.Log.Error("Ticket alerts: Unable to create a request to send to relay: %v", err) return } @@ -116,7 +116,7 @@ func (db database) ProcessAlerts(p Person) { request.Header.Set("Content-Type", "application/json") _, err = client.Do(request) if err != nil { - utils.Log.Error("Ticket alerts: Unable to communicate request to relay: %v", err) + logger.Log.Error("Ticket alerts: Unable to communicate request to relay: %v", err) } } diff --git a/db/config.go b/db/config.go index df53d3f13..35ee80c55 100644 --- a/db/config.go +++ b/db/config.go @@ -6,7 +6,7 @@ import ( "os" "github.com/rs/xid" - "github.com/stakwork/sphinx-tribes/utils" + "github.com/stakwork/sphinx-tribes/logger" "gopkg.in/go-playground/validator.v9" "gorm.io/driver/postgres" "gorm.io/gorm" @@ -41,7 +41,7 @@ var DB database func InitDB() { dbURL := os.Getenv("DATABASE_URL") - utils.Log.Info("db url : %v", dbURL) + logger.Log.Info("db url : %v", dbURL) if dbURL == "" { rdsHost := os.Getenv("RDS_HOSTNAME") @@ -68,7 +68,7 @@ func InitDB() { } DB.db = db - utils.Log.Info("db connected") + logger.Log.Info("db connected") // migrate table changes db.AutoMigrate(&Tribe{}) @@ -472,7 +472,7 @@ func (db database) ProcessUpdateTicketsWithoutGroup() { // update each ticket with group uuid for _, ticket := range tickets { - utils.Log.Info("ticket from process: %v", ticket) + logger.Log.Info("ticket from process: %v", ticket) err := db.UpdateTicketsWithoutGroup(ticket) if err != nil { log.Printf("Error updating ticket: %v", err) diff --git a/db/config_test.go b/db/config_test.go index 8bd556a1b..d8c4982c0 100644 --- a/db/config_test.go +++ b/db/config_test.go @@ -3,9 +3,10 @@ package db import ( "testing" "time" + "fmt" "github.com/google/uuid" - "github.com/stakwork/sphinx-tribes/utils" + "github.com/stakwork/sphinx-tribes/logger" "github.com/stretchr/testify/assert" "gorm.io/gorm" ) @@ -237,7 +238,7 @@ func TestProcessUpdateTicketsWithoutGroup(t *testing.T) { // get ticket and assert that the ticket group is the same as the ticket uuid ticket, err = TestDB.GetTicket(ticket.UUID.String()) - utils.Log.Info("tickets: %v", tickets) + logger.Log.Info("tickets: %v", tickets) ticketUuid := ticket.UUID ticketAuthorID := "12345" diff --git a/db/metrics.go b/db/metrics.go index 90e46f466..52c390080 100644 --- a/db/metrics.go +++ b/db/metrics.go @@ -7,6 +7,7 @@ import ( "strings" "time" + "github.com/stakwork/sphinx-tribes/logger" "github.com/stakwork/sphinx-tribes/utils" ) @@ -24,7 +25,7 @@ func (db database) TotalPeopleByPeriod(r PaymentDateRange) int64 { // convert timestamp string to int64 timestamp, err := utils.ConvertStringToInt(r.StartDate) if err != nil { - utils.Log.Error("Error parsing date: %v", err) + logger.Log.Error("Error parsing date: %v", err) } // Convert the timestamp to a time.Time object diff --git a/db/redis.go b/db/redis.go index 4f5ca0e40..791881086 100644 --- a/db/redis.go +++ b/db/redis.go @@ -6,6 +6,7 @@ import ( "time" "github.com/redis/go-redis/v9" + "github.com/stakwork/sphinx-tribes/logger" "github.com/stakwork/sphinx-tribes/utils" ) @@ -29,27 +30,27 @@ func InitRedis() { opt, err := redis.ParseURL(redisURL) if err != nil { RedisError = err - utils.Log.Error("REDIS URL CONNECTION ERROR === %v", err) + logger.Log.Error("REDIS URL CONNECTION ERROR === %v", err) } RedisClient = redis.NewClient(opt) } if err := RedisClient.Ping(ctx).Err(); err != nil { RedisError = err - utils.Log.Error("Could Not Connect To Redis: %v", err) + logger.Log.Error("Could Not Connect To Redis: %v", err) } } func SetValue(key string, value interface{}) { err := RedisClient.Set(ctx, key, value, expireTime).Err() if err != nil { - utils.Log.Error("REDIS SET ERROR: %v", err) + logger.Log.Error("REDIS SET ERROR: %v", err) } } func GetValue(key string) string { val, err := RedisClient.Get(ctx, key).Result() if err != nil { - utils.Log.Error("REDIS GET ERROR: %v", err) + logger.Log.Error("REDIS GET ERROR: %v", err) } return val @@ -59,7 +60,7 @@ func SetMap(key string, values map[string]interface{}) { for k, v := range values { err := RedisClient.HSet(ctx, key, k, v).Err() if err != nil { - utils.Log.Error("REDIS SET MAP ERROR: %v", err) + logger.Log.Error("REDIS SET MAP ERROR: %v", err) } } RedisClient.Expire(ctx, key, expireTime) diff --git a/db/store.go b/db/store.go index 116d235ee..0e8f50e19 100644 --- a/db/store.go +++ b/db/store.go @@ -14,7 +14,7 @@ import ( "github.com/rs/xid" "github.com/stakwork/sphinx-tribes/auth" "github.com/stakwork/sphinx-tribes/config" - "github.com/stakwork/sphinx-tribes/utils" + "github.com/stakwork/sphinx-tribes/logger" ) type StoreData struct { @@ -172,7 +172,7 @@ func Verify(w http.ResponseWriter, r *http.Request) { challenge := chi.URLParam(r, "challenge") _, err := Store.GetChallengeCache(challenge) if err != nil { - utils.Log.Error("challenge not found: %v", err) + logger.Log.Error("challenge not found: %v", err) w.WriteHeader(http.StatusUnauthorized) return } @@ -182,7 +182,7 @@ func Verify(w http.ResponseWriter, r *http.Request) { r.Body.Close() err = json.Unmarshal(body, &payload) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusNotAcceptable) return } @@ -190,7 +190,7 @@ func Verify(w http.ResponseWriter, r *http.Request) { payload.Pubkey = pubKeyFromAuth marshalled, err := json.Marshal(payload) if err != nil { - utils.Log.Error("payload unparseable: %v", err) + logger.Log.Error("payload unparseable: %v", err) w.WriteHeader(http.StatusUnauthorized) return } @@ -270,14 +270,14 @@ func PostSave(w http.ResponseWriter, r *http.Request) { r.Body.Close() err = json.Unmarshal(body, &save) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusNotAcceptable) return } s, err := json.Marshal(save) if err != nil { - utils.Log.Error("save payload unparseable: %v", err) + logger.Log.Error("save payload unparseable: %v", err) w.WriteHeader(http.StatusUnauthorized) return } diff --git a/db/test_config.go b/db/test_config.go index 1e13cc200..fa877c54e 100644 --- a/db/test_config.go +++ b/db/test_config.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/rs/xid" - "github.com/stakwork/sphinx-tribes/utils" + "github.com/stakwork/sphinx-tribes/logger" "gorm.io/driver/postgres" "gorm.io/gorm" ) @@ -36,7 +36,7 @@ func InitTestDB() { TestDB.db = db - utils.Log.Info("DB CONNECTED") + logger.Log.Info("DB CONNECTED") // migrate table changes db.AutoMigrate(&Tribe{}) diff --git a/db/tickets.go b/db/tickets.go index 5c1fd5b98..4f05b35df 100644 --- a/db/tickets.go +++ b/db/tickets.go @@ -6,7 +6,7 @@ import ( "time" "github.com/google/uuid" - "github.com/stakwork/sphinx-tribes/utils" + "github.com/stakwork/sphinx-tribes/logger" "gorm.io/gorm" ) @@ -182,7 +182,7 @@ func (db database) UpdateTicketsWithoutGroup(ticket Tickets) error { data["author"] = "HUMAN" } - utils.Log.Info("data === %v", data) + logger.Log.Info("data === %v", data) result := db.db.Model(&Tickets{}).Where("uuid = ?", ticket.UUID).Updates(data) diff --git a/handlers/auth.go b/handlers/auth.go index 490272801..debfe956e 100644 --- a/handlers/auth.go +++ b/handlers/auth.go @@ -12,6 +12,7 @@ import ( "github.com/stakwork/sphinx-tribes/auth" "github.com/stakwork/sphinx-tribes/config" "github.com/stakwork/sphinx-tribes/db" + "github.com/stakwork/sphinx-tribes/logger" "github.com/stakwork/sphinx-tribes/utils" ) @@ -63,7 +64,7 @@ func (ah *authHandler) CreateConnectionCode(w http.ResponseWriter, r *http.Reque body, err := io.ReadAll(r.Body) if err != nil { - utils.Log.Error("ReadAll Error: %v", err) + logger.Log.Error("ReadAll Error: %v", err) w.WriteHeader(http.StatusBadRequest) return } @@ -72,7 +73,7 @@ func (ah *authHandler) CreateConnectionCode(w http.ResponseWriter, r *http.Reque err = json.Unmarshal(body, &codeBody) if err != nil { - utils.Log.Error("Could not unmarshal connection code body") + logger.Log.Error("Could not unmarshal connection code body") w.WriteHeader(http.StatusNotAcceptable) return } @@ -110,7 +111,7 @@ func (ah *authHandler) CreateConnectionCode(w http.ResponseWriter, r *http.Reque _, err = ah.db.CreateConnectionCode(codeArr) if err != nil { - utils.Log.Error("[auth] => ERR create connection code: %v", err) + logger.Log.Error("[auth] => ERR create connection code: %v", err) w.WriteHeader(http.StatusBadRequest) return } @@ -149,7 +150,7 @@ func MakeConnectionCodeRequest(inviter_pubkey string, inviter_route_hint string, err = json.Unmarshal(body, &inviteReponse) if err != nil { - utils.Log.Error("Could not get connection code") + logger.Log.Error("Could not get connection code") return "" } @@ -202,7 +203,7 @@ func ReceiveLnAuthData(w http.ResponseWriter, r *http.Request) { exVerify, err := auth.VerifyDerSig(sig, k1, userKey) if err != nil || !exVerify { - utils.Log.Error("[auth] Error signing signature") + logger.Log.Error("[auth] Error signing signature") w.WriteHeader(http.StatusUnauthorized) json.NewEncoder(w).Encode(err.Error()) return @@ -221,7 +222,7 @@ func ReceiveLnAuthData(w http.ResponseWriter, r *http.Request) { tokenString, err := auth.EncodeJwt(userKey) if err != nil { - utils.Log.Error("[auth] error creating LNAUTH JWT") + logger.Log.Error("[auth] error creating LNAUTH JWT") w.WriteHeader(http.StatusNotAcceptable) json.NewEncoder(w).Encode(err.Error()) return @@ -245,7 +246,7 @@ func ReceiveLnAuthData(w http.ResponseWriter, r *http.Request) { socket.Conn.WriteJSON(socketMsg) db.Store.DeleteCache(k1[0:20]) } else { - utils.Log.Error("[auth] Socket Error: %v", err) + logger.Log.Error("[auth] Socket Error: %v", err) } responseMsg["status"] = "OK" @@ -265,7 +266,7 @@ func (ah *authHandler) RefreshToken(w http.ResponseWriter, r *http.Request) { claims, err := ah.decodeJwt(token) if err != nil { - utils.Log.Error("[auth] Failed to parse JWT") + logger.Log.Error("[auth] Failed to parse JWT") w.WriteHeader(http.StatusUnauthorized) json.NewEncoder(w).Encode(err.Error()) return @@ -280,7 +281,7 @@ func (ah *authHandler) RefreshToken(w http.ResponseWriter, r *http.Request) { tokenString, err := ah.encodeJwt(pubkey) if err != nil { - utils.Log.Error("[auth] error creating refresh JWT") + logger.Log.Error("[auth] error creating refresh JWT") w.WriteHeader(http.StatusNotAcceptable) json.NewEncoder(w).Encode(err.Error()) return diff --git a/handlers/bots.go b/handlers/bots.go index 90ae2b623..0079c037f 100644 --- a/handlers/bots.go +++ b/handlers/bots.go @@ -12,7 +12,7 @@ import ( "github.com/go-chi/chi" "github.com/stakwork/sphinx-tribes/auth" "github.com/stakwork/sphinx-tribes/db" - "github.com/stakwork/sphinx-tribes/utils" + "github.com/stakwork/sphinx-tribes/logger" ) type botHandler struct { @@ -36,7 +36,7 @@ func (bt *botHandler) CreateOrEditBot(w http.ResponseWriter, r *http.Request) { r.Body.Close() err = json.Unmarshal(body, &bot) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusNotAcceptable) return } @@ -50,7 +50,7 @@ func (bt *botHandler) CreateOrEditBot(w http.ResponseWriter, r *http.Request) { extractedPubkey, err := bt.verifyTribeUUID(bot.UUID, false) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusUnauthorized) return } @@ -70,7 +70,7 @@ func (bt *botHandler) CreateOrEditBot(w http.ResponseWriter, r *http.Request) { _, err = bt.db.CreateOrEditBot(bot) if err != nil { - utils.Log.Error("=> ERR createOrEditBot: %v", err) + logger.Log.Error("=> ERR createOrEditBot: %v", err) w.WriteHeader(http.StatusBadRequest) return } @@ -127,7 +127,7 @@ func (bt *botHandler) DeleteBot(w http.ResponseWriter, r *http.Request) { uuid := chi.URLParam(r, "uuid") - utils.Log.Info("uuid: %s", uuid) + logger.Log.Info("uuid: %s", uuid) if uuid == "" { w.WriteHeader(http.StatusUnauthorized) @@ -136,7 +136,7 @@ func (bt *botHandler) DeleteBot(w http.ResponseWriter, r *http.Request) { extractedPubkey, err := bt.verifyTribeUUID(uuid, false) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusUnauthorized) return } diff --git a/handlers/bounties.go b/handlers/bounties.go index 3b56dd547..d1e245f02 100644 --- a/handlers/bounties.go +++ b/handlers/bounties.go @@ -10,7 +10,7 @@ import ( "github.com/lib/pq" "github.com/stakwork/sphinx-tribes/db" - "github.com/stakwork/sphinx-tribes/utils" + "github.com/stakwork/sphinx-tribes/logger" ) func GetWantedsHeader(w http.ResponseWriter, r *http.Request) { @@ -54,7 +54,7 @@ func DeleteBountyAssignee(w http.ResponseWriter, r *http.Request) { err = json.Unmarshal(body, &invoice) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusNotAcceptable) return } @@ -91,17 +91,17 @@ func MigrateBounties(w http.ResponseWriter, r *http.Request) { peeps := db.DB.GetAllPeople() for indexPeep, peep := range peeps { - utils.Log.Info("peep: %d", indexPeep) + logger.Log.Info("peep: %d", indexPeep) bounties, ok := peep.Extras["wanted"].([]interface{}) if !ok { - utils.Log.Info("Wanted not there") + logger.Log.Info("Wanted not there") continue } for index, bounty := range bounties { - utils.Log.Info("looping bounties: %d", index) + logger.Log.Info("looping bounties: %d", index) migrateBounty := bounty.(map[string]interface{}) migrateBountyFinal := db.Bounty{} @@ -156,8 +156,8 @@ func MigrateBounties(w http.ResponseWriter, r *http.Request) { if !ok7 { migrateBountyFinal.Created = 0 } else { - utils.Log.Info("Type: %v", reflect.TypeOf(CreatedInt64)) - utils.Log.Info("Timestamp: %d", CreatedInt64) + logger.Log.Info("Type: %v", reflect.TypeOf(CreatedInt64)) + logger.Log.Info("Timestamp: %d", CreatedInt64) migrateBountyFinal.Created = CreatedInt64 } @@ -237,7 +237,7 @@ func MigrateBounties(w http.ResponseWriter, r *http.Request) { } else { migrateBountyFinal.EstimatedCompletionDate = EstimatedCompletionDate } - utils.Log.Info("Bounty about to be added ") + logger.Log.Info("Bounty about to be added ") db.DB.AddBounty(migrateBountyFinal) //Migrate the bounties here } diff --git a/handlers/bounty.go b/handlers/bounty.go index ab0317bcb..8ef6e3dec 100644 --- a/handlers/bounty.go +++ b/handlers/bounty.go @@ -16,6 +16,7 @@ import ( "github.com/stakwork/sphinx-tribes/auth" "github.com/stakwork/sphinx-tribes/config" "github.com/stakwork/sphinx-tribes/db" + "github.com/stakwork/sphinx-tribes/logger" "github.com/stakwork/sphinx-tribes/utils" "gorm.io/gorm" ) @@ -61,7 +62,7 @@ func (h *bountyHandler) GetBountyById(w http.ResponseWriter, r *http.Request) { bounties, err := h.db.GetBountyById(bountyId) if err != nil { w.WriteHeader(http.StatusBadRequest) - utils.Log.Error("[bounty] Error: %v", err) + logger.Log.Error("[bounty] Error: %v", err) } else { var bountyResponse []db.BountyResponse = h.GenerateBountyResponse(bounties) w.WriteHeader(http.StatusOK) @@ -73,7 +74,7 @@ func (h *bountyHandler) GetNextBountyByCreated(w http.ResponseWriter, r *http.Re bounties, err := h.db.GetNextBountyByCreated(r) if err != nil { w.WriteHeader(http.StatusBadRequest) - utils.Log.Error("[bounty] Error: %v", err) + logger.Log.Error("[bounty] Error: %v", err) } else { w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(bounties) @@ -84,7 +85,7 @@ func (h *bountyHandler) GetPreviousBountyByCreated(w http.ResponseWriter, r *htt bounties, err := h.db.GetPreviousBountyByCreated(r) if err != nil { w.WriteHeader(http.StatusBadRequest) - utils.Log.Error("[bounty] Error: %v", err) + logger.Log.Error("[bounty] Error: %v", err) } else { w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(bounties) @@ -95,7 +96,7 @@ func (h *bountyHandler) GetWorkspaceNextBountyByCreated(w http.ResponseWriter, r bounties, err := h.db.GetNextWorkspaceBountyByCreated(r) if err != nil { w.WriteHeader(http.StatusBadRequest) - utils.Log.Error("[bounty] Error: %v", err) + logger.Log.Error("[bounty] Error: %v", err) } else { w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(bounties) @@ -106,7 +107,7 @@ func (h *bountyHandler) GetWorkspacePreviousBountyByCreated(w http.ResponseWrite bounties, err := h.db.GetPreviousWorkspaceBountyByCreated(r) if err != nil { w.WriteHeader(http.StatusBadRequest) - utils.Log.Error("[bounty] Error: %v", err) + logger.Log.Error("[bounty] Error: %v", err) } else { w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(bounties) @@ -132,7 +133,7 @@ func (h *bountyHandler) GetBountyByCreated(w http.ResponseWriter, r *http.Reques bounties, err := h.db.GetBountyDataByCreated(created) if err != nil { w.WriteHeader(http.StatusBadRequest) - utils.Log.Error("[bounty] Error: %v", err) + logger.Log.Error("[bounty] Error: %v", err) } else { var bountyResponse []db.BountyResponse = h.GenerateBountyResponse(bounties) @@ -164,7 +165,7 @@ func (h *bountyHandler) GetPersonCreatedBounties(w http.ResponseWriter, r *http. bounties, err := h.db.GetCreatedBounties(r) if err != nil { w.WriteHeader(http.StatusBadRequest) - utils.Log.Error("[bounty] Error: %v", err) + logger.Log.Error("[bounty] Error: %v", err) } else { var bountyResponse []db.BountyResponse = h.GenerateBountyResponse(bounties) w.WriteHeader(http.StatusOK) @@ -176,7 +177,7 @@ func (h *bountyHandler) GetPersonAssignedBounties(w http.ResponseWriter, r *http bounties, err := h.db.GetAssignedBounties(r) if err != nil { w.WriteHeader(http.StatusBadRequest) - utils.Log.Error("[bounty] Error: %v", err) + logger.Log.Error("[bounty] Error: %v", err) } else { var bountyResponse []db.BountyResponse = h.GenerateBountyResponse(bounties) w.WriteHeader(http.StatusOK) @@ -193,14 +194,14 @@ func (h *bountyHandler) CreateOrEditBounty(w http.ResponseWriter, r *http.Reques r.Body.Close() if err != nil { - utils.Log.Error("[bounty] Read error: %v", err) + logger.Log.Error("[bounty] Read error: %v", err) w.WriteHeader(http.StatusNotAcceptable) return } err = json.Unmarshal(body, &bounty) if err != nil { - utils.Log.Error("[bounty] Unmarshal error: %v", err) + logger.Log.Error("[bounty] Unmarshal error: %v", err) w.WriteHeader(http.StatusNotAcceptable) return } @@ -260,7 +261,7 @@ func (h *bountyHandler) CreateOrEditBounty(w http.ResponseWriter, r *http.Reques // check if the bounty has a pending payment if dbBounty.PaymentPending { msg := "You cannot update a bounty with a pending payment" - utils.Log.Info("[bounty]: %v", msg) + logger.Log.Info("[bounty]: %v", msg) w.WriteHeader(http.StatusBadRequest) json.NewEncoder(w).Encode(msg) return @@ -273,14 +274,14 @@ func (h *bountyHandler) CreateOrEditBounty(w http.ResponseWriter, r *http.Reques hasBountyRoles := h.userHasManageBountyRoles(pubKeyFromAuth, bounty.WorkspaceUuid) if !hasBountyRoles { msg := "You don't have the right permission ton update bounty" - utils.Log.Info("[bounty]: %v", msg) + logger.Log.Info("[bounty]: %v", msg) w.WriteHeader(http.StatusBadRequest) json.NewEncoder(w).Encode(msg) return } } else { msg := "Cannot edit another user's bounty" - utils.Log.Info("[bounty]: %v", msg) + logger.Log.Info("[bounty]: %v", msg) w.WriteHeader(http.StatusBadRequest) json.NewEncoder(w).Encode(msg) return @@ -304,7 +305,7 @@ func (h *bountyHandler) CreateOrEditBounty(w http.ResponseWriter, r *http.Reques b, err := h.db.CreateOrEditBounty(bounty) if err != nil { - utils.Log.Error("[bounty] Error: %v", err) + logger.Log.Error("[bounty] Error: %v", err) w.WriteHeader(http.StatusBadRequest) return } @@ -318,7 +319,7 @@ func (h *bountyHandler) DeleteBounty(w http.ResponseWriter, r *http.Request) { pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Error("[bounty] no pubkey from auth") + logger.Log.Error("[bounty] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -327,12 +328,12 @@ func (h *bountyHandler) DeleteBounty(w http.ResponseWriter, r *http.Request) { pubkey := chi.URLParam(r, "pubkey") if pubkey == "" { - utils.Log.Error("[bounty] no pubkey from route") + logger.Log.Error("[bounty] no pubkey from route") w.WriteHeader(http.StatusUnauthorized) return } if created == "" { - utils.Log.Error("[bounty] no created timestamp from route") + logger.Log.Error("[bounty] no created timestamp from route") w.WriteHeader(http.StatusUnauthorized) return } @@ -341,14 +342,14 @@ func (h *bountyHandler) DeleteBounty(w http.ResponseWriter, r *http.Request) { createdUint, _ := utils.ConvertStringToUint(created) createdBounty, err := h.db.GetBountyByCreated(createdUint) if err != nil { - utils.Log.Error("[bounty] failed to delete bounty: %v", err) + logger.Log.Error("[bounty] failed to delete bounty: %v", err) w.WriteHeader(http.StatusInternalServerError) json.NewEncoder(w).Encode("failed to delete bounty") return } if createdBounty.ID == 0 { - utils.Log.Error("[bounty] failed to delete bounty") + logger.Log.Error("[bounty] failed to delete bounty") w.WriteHeader(http.StatusInternalServerError) json.NewEncoder(w).Encode("failed to delete bounty") return @@ -356,7 +357,7 @@ func (h *bountyHandler) DeleteBounty(w http.ResponseWriter, r *http.Request) { b, err := h.db.DeleteBounty(pubkey, created) if err != nil { - utils.Log.Error("[bounty] failed to delete bounty: %v", err) + logger.Log.Error("[bounty] failed to delete bounty: %v", err) w.WriteHeader(http.StatusInternalServerError) json.NewEncoder(w).Encode("failed to delete bounty") return @@ -533,14 +534,14 @@ func (h *bountyHandler) MakeBountyPayment(w http.ResponseWriter, r *http.Request id, err := utils.ConvertStringToUint(idParam) if err != nil { - utils.Log.Error("[bounty] could not parse id") + logger.Log.Error("[bounty] could not parse id") w.WriteHeader(http.StatusForbidden) h.m.Unlock() return } if pubKeyFromAuth == "" { - utils.Log.Error("[bounty] no pubkey from auth") + logger.Log.Error("[bounty] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) h.m.Unlock() return @@ -598,7 +599,7 @@ func (h *bountyHandler) MakeBountyPayment(w http.ResponseWriter, r *http.Request body, err := io.ReadAll(r.Body) r.Body.Close() if err != nil { - utils.Log.Error("[bounty] Read body error: %v", err) + logger.Log.Error("[bounty] Read body error: %v", err) w.WriteHeader(http.StatusNotAcceptable) h.m.Unlock() return @@ -606,7 +607,7 @@ func (h *bountyHandler) MakeBountyPayment(w http.ResponseWriter, r *http.Request err = json.Unmarshal(body, &request) if err != nil { - utils.Log.Error("[bounty] Unmarshal error: %v", err) + logger.Log.Error("[bounty] Unmarshal error: %v", err) w.WriteHeader(http.StatusNotAcceptable) h.m.Unlock() return @@ -623,7 +624,7 @@ func (h *bountyHandler) MakeBountyPayment(w http.ResponseWriter, r *http.Request if config.IsV2Payment { url := fmt.Sprintf("%s/pay", config.V2BotUrl) - utils.Log.Info("IS V2 PAYMENT ====") + logger.Log.Info("IS V2 PAYMENT ====") // Build v2 keysend payment data bodyData := utils.BuildV2KeysendBodyData(amount, assignee.OwnerPubKey, assignee.OwnerRouteHint, memoText) @@ -681,7 +682,7 @@ func (h *bountyHandler) MakeBountyPayment(w http.ResponseWriter, r *http.Request err = json.Unmarshal(body, &v2KeysendRes) if err != nil { - utils.Log.Error("[Unmarshal failed]: %v", err) + logger.Log.Error("[Unmarshal failed]: %v", err) w.WriteHeader(http.StatusNotAcceptable) h.m.Unlock() return @@ -826,7 +827,7 @@ func (h *bountyHandler) MakeBountyPayment(w http.ResponseWriter, r *http.Request defer res.Body.Close() body, err = io.ReadAll(res.Body) if err != nil { - utils.Log.Error("[bounty] Read body error: %v", err) + logger.Log.Error("[bounty] Read body error: %v", err) w.WriteHeader(http.StatusNotAcceptable) h.m.Unlock() return @@ -842,7 +843,7 @@ func (h *bountyHandler) MakeBountyPayment(w http.ResponseWriter, r *http.Request err = json.Unmarshal(body, &keysendRes) if err != nil { - utils.Log.Error("[bounty] Unmarshal error: %v", err) + logger.Log.Error("[bounty] Unmarshal error: %v", err) w.WriteHeader(http.StatusNotAcceptable) h.m.Unlock() return @@ -900,13 +901,13 @@ func (h *bountyHandler) GetBountyPaymentStatus(w http.ResponseWriter, r *http.Re id, err := utils.ConvertStringToUint(idParam) if err != nil { - utils.Log.Error("[bounty] could not parse id") + logger.Log.Error("[bounty] could not parse id") w.WriteHeader(http.StatusForbidden) return } if pubKeyFromAuth == "" { - utils.Log.Error("[bounty] no pubkey from auth") + logger.Log.Error("[bounty] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -943,13 +944,13 @@ func (h *bountyHandler) UpdateBountyPaymentStatus(w http.ResponseWriter, r *http id, err := utils.ConvertStringToUint(idParam) if err != nil { - utils.Log.Error("[bounty] could not parse id") + logger.Log.Error("[bounty] could not parse id") w.WriteHeader(http.StatusForbidden) return } if pubKeyFromAuth == "" { - utils.Log.Error("[bounty] no pubkey from auth") + logger.Log.Error("[bounty] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -1055,7 +1056,7 @@ func (h *bountyHandler) BountyBudgetWithdraw(w http.ResponseWriter, r *http.Requ pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Error("[bounty] no pubkey from auth") + logger.Log.Error("[bounty] no pubkey from auth") h.m.Unlock() w.WriteHeader(http.StatusUnauthorized) @@ -1447,7 +1448,7 @@ func (h *bountyHandler) PollInvoice(w http.ResponseWriter, r *http.Request) { paymentRequest := chi.URLParam(r, "paymentRequest") if pubKeyFromAuth == "" { - utils.Log.Error("[bounty] no pubkey from auth") + logger.Log.Error("[bounty] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } diff --git a/handlers/bounty_test.go b/handlers/bounty_test.go index 02cb94af5..d66290101 100644 --- a/handlers/bounty_test.go +++ b/handlers/bounty_test.go @@ -19,6 +19,7 @@ import ( "time" "github.com/gorilla/websocket" + "github.com/stakwork/sphinx-tribes/logger" "github.com/stakwork/sphinx-tribes/utils" "github.com/go-chi/chi" @@ -235,7 +236,7 @@ func TestCreateOrEditBounty(t *testing.T) { json, err := json.Marshal(updatedBounty) if err != nil { - utils.Log.Error("Could not marshal json data") + logger.Log.Error("Could not marshal json data") } req, err := http.NewRequestWithContext(ctx, http.MethodPost, "/", bytes.NewReader(json)) @@ -1242,7 +1243,7 @@ func MockNewWSServer(t *testing.T) (*httptest.Server, *websocket.Conn) { upgrader.CheckOrigin = func(r *http.Request) bool { return true } ws, err := upgrader.Upgrade(w, r, nil) if err != nil { - utils.Log.Error("upgrade error: %v", err) + logger.Log.Error("upgrade error: %v", err) return } defer ws.Close() diff --git a/handlers/channel.go b/handlers/channel.go index ec6f12c42..81ac150a1 100644 --- a/handlers/channel.go +++ b/handlers/channel.go @@ -9,7 +9,7 @@ import ( "github.com/go-chi/chi" "github.com/stakwork/sphinx-tribes/auth" "github.com/stakwork/sphinx-tribes/db" - "github.com/stakwork/sphinx-tribes/utils" + "github.com/stakwork/sphinx-tribes/logger" ) type channelHandler struct { @@ -29,13 +29,13 @@ func (ch *channelHandler) DeleteChannel(w http.ResponseWriter, r *http.Request) idString := chi.URLParam(r, "id") id, err := strconv.Atoi(idString) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusUnauthorized) return } if id == 0 { - utils.Log.Info("id is 0") + logger.Log.Info("id is 0") w.WriteHeader(http.StatusUnauthorized) return } @@ -43,12 +43,12 @@ func (ch *channelHandler) DeleteChannel(w http.ResponseWriter, r *http.Request) existing := ch.db.GetChannel(uint(id)) existingTribe := ch.db.GetTribe(existing.TribeUUID) if existing.ID == 0 { - utils.Log.Info("existing id is 0") + logger.Log.Info("existing id is 0") w.WriteHeader(http.StatusUnauthorized) return } if existingTribe.OwnerPubKey != pubKeyFromAuth { - utils.Log.Info("keys dont match") + logger.Log.Info("keys dont match") w.WriteHeader(http.StatusUnauthorized) return } @@ -70,7 +70,7 @@ func (ch *channelHandler) CreateChannel(w http.ResponseWriter, r *http.Request) r.Body.Close() err = json.Unmarshal(body, &channel) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusNotAcceptable) return } @@ -78,7 +78,7 @@ func (ch *channelHandler) CreateChannel(w http.ResponseWriter, r *http.Request) //check that the tribe has the same pubKeyFromAuth tribe := ch.db.GetTribe(channel.TribeUUID) if tribe.OwnerPubKey != pubKeyFromAuth { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusUnauthorized) return } @@ -86,7 +86,7 @@ func (ch *channelHandler) CreateChannel(w http.ResponseWriter, r *http.Request) tribeChannels := ch.db.GetChannelsByTribe(channel.TribeUUID) for _, tribeChannel := range tribeChannels { if tribeChannel.Name == channel.Name { - utils.Log.Info("Channel name already in use") + logger.Log.Info("Channel name already in use") w.WriteHeader(http.StatusNotAcceptable) return @@ -95,7 +95,7 @@ func (ch *channelHandler) CreateChannel(w http.ResponseWriter, r *http.Request) channel, err = ch.db.CreateChannel(channel) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusNotAcceptable) return } diff --git a/handlers/features.go b/handlers/features.go index 9e2dc2016..c5cb2c22e 100644 --- a/handlers/features.go +++ b/handlers/features.go @@ -15,7 +15,7 @@ import ( "github.com/rs/xid" "github.com/stakwork/sphinx-tribes/auth" "github.com/stakwork/sphinx-tribes/db" - "github.com/stakwork/sphinx-tribes/utils" + "github.com/stakwork/sphinx-tribes/logger" ) type PostData struct { @@ -58,7 +58,7 @@ func (oh *featureHandler) CreateOrEditFeatures(w http.ResponseWriter, r *http.Re ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -69,7 +69,7 @@ func (oh *featureHandler) CreateOrEditFeatures(w http.ResponseWriter, r *http.Re err := json.Unmarshal(body, &features) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusNotAcceptable) return } @@ -113,7 +113,7 @@ func (oh *featureHandler) DeleteFeature(w http.ResponseWriter, r *http.Request) ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -135,7 +135,7 @@ func (oh *featureHandler) GetFeaturesByWorkspaceUuid(w http.ResponseWriter, r *h ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -151,7 +151,7 @@ func (oh *featureHandler) GetWorkspaceFeaturesCount(w http.ResponseWriter, r *ht ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -167,7 +167,7 @@ func (oh *featureHandler) GetFeatureByUuid(w http.ResponseWriter, r *http.Reques ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -241,7 +241,7 @@ func (oh *featureHandler) CreateOrEditFeaturePhase(w http.ResponseWriter, r *htt ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -290,7 +290,7 @@ func (oh *featureHandler) GetFeaturePhases(w http.ResponseWriter, r *http.Reques ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -306,7 +306,7 @@ func (oh *featureHandler) GetFeaturePhaseByUUID(w http.ResponseWriter, r *http.R ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -328,7 +328,7 @@ func (oh *featureHandler) DeleteFeaturePhase(w http.ResponseWriter, r *http.Requ ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -351,7 +351,7 @@ func (oh *featureHandler) CreateOrEditStory(w http.ResponseWriter, r *http.Reque ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -392,7 +392,7 @@ func (oh *featureHandler) GetStoriesByFeatureUuid(w http.ResponseWriter, r *http ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -415,7 +415,7 @@ func (oh *featureHandler) GetStoryByUuid(w http.ResponseWriter, r *http.Request) ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -433,7 +433,7 @@ func (oh *featureHandler) DeleteStory(w http.ResponseWriter, r *http.Request) { ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -459,7 +459,7 @@ func (oh *featureHandler) GetBountiesByFeatureAndPhaseUuid(w http.ResponseWriter ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -483,7 +483,7 @@ func (oh *featureHandler) GetBountiesCountByFeatureAndPhaseUuid(w http.ResponseW ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -556,7 +556,7 @@ func (oh *featureHandler) StoriesSend(w http.ResponseWriter, r *http.Request) { var postData PostData err = json.Unmarshal(body, &postData) if err != nil { - utils.Log.Error("[StoriesSend] JSON Unmarshal error: %v", err) + logger.Log.Error("[StoriesSend] JSON Unmarshal error: %v", err) http.Error(w, "Invalid JSON format", http.StatusNotAcceptable) return } @@ -615,7 +615,7 @@ func (oh *featureHandler) BriefSend(w http.ResponseWriter, r *http.Request) { ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -630,7 +630,7 @@ func (oh *featureHandler) BriefSend(w http.ResponseWriter, r *http.Request) { var postData AudioBriefPostData err = json.Unmarshal(body, &postData) if err != nil { - utils.Log.Error("[BriefSend] JSON Unmarshal error: %v", err) + logger.Log.Error("[BriefSend] JSON Unmarshal error: %v", err) http.Error(w, "Invalid JSON format", http.StatusNotAcceptable) return } diff --git a/handlers/feed.go b/handlers/feed.go index 9695f9214..89b4a41fd 100644 --- a/handlers/feed.go +++ b/handlers/feed.go @@ -13,7 +13,7 @@ import ( "github.com/stakwork/sphinx-tribes/db" "github.com/stakwork/sphinx-tribes/feeds" - "github.com/stakwork/sphinx-tribes/utils" + "github.com/stakwork/sphinx-tribes/logger" "google.golang.org/api/option" "google.golang.org/api/youtube/v3" ) @@ -59,7 +59,7 @@ func DownloadYoutubeFeed(w http.ResponseWriter, r *http.Request) { r.Body.Close() err = json.Unmarshal(body, &youtube_download) if err != nil { - utils.Log.Error("[feed] %v", err) + logger.Log.Error("[feed] %v", err) w.WriteHeader(http.StatusNotAcceptable) return } @@ -95,7 +95,7 @@ func DownloadYoutubeFeed(w http.ResponseWriter, r *http.Request) { func processYoutubeDownload(data []string) { stakworkKey := fmt.Sprintf("Token token=%s", os.Getenv("STAKWORK_KEY")) if stakworkKey == "" { - utils.Log.Error("[feed] Youtube Download Error: Stakwork key not found") + logger.Log.Error("[feed] Youtube Download Error: Stakwork key not found") } else { type Vars struct { YoutubeContent []string `json:"youtube_content"` @@ -129,7 +129,7 @@ func processYoutubeDownload(data []string) { buf, err := json.Marshal(body) if err != nil { - utils.Log.Error("[feed] Youtube error: Unable to parse message into byte buffer: %v", err) + logger.Log.Error("[feed] Youtube error: Unable to parse message into byte buffer: %v", err) return } @@ -141,14 +141,14 @@ func processYoutubeDownload(data []string) { client := &http.Client{} response, err := client.Do(request) if err != nil { - utils.Log.Error("[feed] Youtube Download Request Error: %v", err) + logger.Log.Error("[feed] Youtube Download Request Error: %v", err) } defer response.Body.Close() res, err := io.ReadAll(response.Body) if err != nil { - utils.Log.Error("[feed] Youtube Download Request Error: %v", err) + logger.Log.Error("[feed] Youtube Download Request Error: %v", err) } - utils.Log.Info("[feed] Youtube Download Success: %s", string(res)) + logger.Log.Info("[feed] Youtube Download Success: %s", string(res)) } } @@ -159,7 +159,7 @@ func GetPodcast(w http.ResponseWriter, r *http.Request) { episodes, err := getEpisodes(url, feedid) if err != nil { - utils.Log.Error("[feed] %v", err) + logger.Log.Error("[feed] %v", err) w.WriteHeader(http.StatusNotFound) return } @@ -168,7 +168,7 @@ func GetPodcast(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) err = json.NewEncoder(w).Encode(podcast) if err != nil { - utils.Log.Error("[feed] %v", err) + logger.Log.Error("[feed] %v", err) } } @@ -268,7 +268,7 @@ func getFeed(feedURL string, feedID string) (*feeds.Podcast, error) { resp, err := client.Do(req) if err != nil { - utils.Log.Error("[feed] GET error: %v", err) + logger.Log.Error("[feed] GET error: %v", err) return nil, err } defer resp.Body.Close() @@ -277,7 +277,7 @@ func getFeed(feedURL string, feedID string) (*feeds.Podcast, error) { body, err := io.ReadAll(resp.Body) err = json.Unmarshal(body, &r) if err != nil { - utils.Log.Error("[feed] json unmarshall error: %v", err) + logger.Log.Error("[feed] json unmarshall error: %v", err) return nil, err } @@ -310,7 +310,7 @@ func getEpisodes(feedURL string, feedID string) ([]feeds.Episode, error) { resp, err := client.Do(req) if err != nil { - utils.Log.Error("[feed] GET error: %v", err) + logger.Log.Error("[feed] GET error: %v", err) return nil, err } defer resp.Body.Close() @@ -319,7 +319,7 @@ func getEpisodes(feedURL string, feedID string) ([]feeds.Episode, error) { body, err := io.ReadAll(resp.Body) err = json.Unmarshal(body, &r) if err != nil { - utils.Log.Error("[feed] json unmarshall error: %v", err) + logger.Log.Error("[feed] json unmarshall error: %v", err) return nil, err } @@ -344,7 +344,7 @@ func searchPodcastIndex(term string) ([]feeds.Podcast, error) { resp, err := client.Do(req) if err != nil { - utils.Log.Error("[feed] GET error: %v", err) + logger.Log.Error("[feed] GET error: %v", err) return nil, err } defer resp.Body.Close() @@ -353,7 +353,7 @@ func searchPodcastIndex(term string) ([]feeds.Podcast, error) { body, err := io.ReadAll(resp.Body) err = json.Unmarshal(body, &r) if err != nil { - utils.Log.Error("[feed] json unmarshall error: %v", err) + logger.Log.Error("[feed] json unmarshall error: %v", err) return nil, err } diff --git a/handlers/github.go b/handlers/github.go index 2907a946e..fb7d61703 100644 --- a/handlers/github.go +++ b/handlers/github.go @@ -13,7 +13,7 @@ import ( "github.com/google/go-github/v39/github" "github.com/stakwork/sphinx-tribes/auth" "github.com/stakwork/sphinx-tribes/db" - "github.com/stakwork/sphinx-tribes/utils" + "github.com/stakwork/sphinx-tribes/logger" "golang.org/x/oauth2" ) @@ -28,7 +28,7 @@ func GetGithubIssue(w http.ResponseWriter, r *http.Request) { } issue, err := GetIssue(owner, repo, issueNum) if err != nil { - utils.Log.Error("Github error: %v", err) + logger.Log.Error("Github error: %v", err) w.WriteHeader(http.StatusNotFound) return } diff --git a/handlers/meme.go b/handlers/meme.go index 8265c17cb..62de47e38 100644 --- a/handlers/meme.go +++ b/handlers/meme.go @@ -16,7 +16,7 @@ import ( "github.com/stakwork/sphinx-tribes/auth" "github.com/stakwork/sphinx-tribes/config" "github.com/stakwork/sphinx-tribes/db" - "github.com/stakwork/sphinx-tribes/utils" + "github.com/stakwork/sphinx-tribes/logger" ) func MemeImageUpload(w http.ResponseWriter, r *http.Request) { @@ -24,7 +24,7 @@ func MemeImageUpload(w http.ResponseWriter, r *http.Request) { pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -62,7 +62,7 @@ func MemeImageUpload(w http.ResponseWriter, r *http.Request) { if mErr != "" { msg := "Could not get meme token" - utils.Log.Error("%s: %s", msg, mErr) + logger.Log.Error("%s: %s", msg, mErr) w.WriteHeader(http.StatusNoContent) json.NewEncoder(w).Encode(msg) } else { @@ -74,7 +74,7 @@ func MemeImageUpload(w http.ResponseWriter, r *http.Request) { } msg := "Could not get meme image" - utils.Log.Error("%s", msg) + logger.Log.Error("%s", msg) w.WriteHeader(http.StatusNoContent) json.NewEncoder(w).Encode(msg) } @@ -205,7 +205,7 @@ func UploadMemeImage(file multipart.File, token string, fileName string) (error, DeleteFileFromUploadsFolder(filePath) if err != nil { - utils.Log.Error("meme request Error: %v", err) + logger.Log.Error("meme request Error: %v", err) return err, "" } @@ -235,7 +235,7 @@ func DeleteFileFromUploadsFolder(filePath string) { func CreateUploadsDirectory(dirName string) { if _, err := os.Open(dirName); os.IsNotExist(err) { - utils.Log.Info("The directory named %s does not exist", dirName) + logger.Log.Info("The directory named %s does not exist", dirName) os.Mkdir(dirName, 0755) } } diff --git a/handlers/metrics.go b/handlers/metrics.go index 62f82cca7..17cead2f4 100644 --- a/handlers/metrics.go +++ b/handlers/metrics.go @@ -19,7 +19,7 @@ import ( "github.com/stakwork/sphinx-tribes/auth" "github.com/stakwork/sphinx-tribes/config" "github.com/stakwork/sphinx-tribes/db" - "github.com/stakwork/sphinx-tribes/utils" + "github.com/stakwork/sphinx-tribes/logger" "github.com/tuan78/jsonconv" ) @@ -38,7 +38,7 @@ func PaymentMetrics(w http.ResponseWriter, r *http.Request) { workspace := keys.Get("workspace") if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -65,7 +65,7 @@ func WorkspacetMetrics(w http.ResponseWriter, r *http.Request) { pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -92,7 +92,7 @@ func PeopleMetrics(w http.ResponseWriter, r *http.Request) { pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -128,7 +128,7 @@ func (mh *metricHandler) BountyMetrics(w http.ResponseWriter, r *http.Request) { workspace := keys.Get("workspace") if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -164,7 +164,7 @@ func (mh *metricHandler) BountyMetrics(w http.ResponseWriter, r *http.Request) { return } } else { - utils.Log.Info("Redis client is not initialized or there is an error with Redis") + logger.Log.Info("Redis client is not initialized or there is an error with Redis") } totalBountiesPosted := mh.db.TotalBountiesPosted(request, workspace) @@ -201,7 +201,7 @@ func (mh *metricHandler) BountyMetrics(w http.ResponseWriter, r *http.Request) { metricsMap := structs.Map(bountyMetrics) db.SetMap(metricsKey, metricsMap) } else { - utils.Log.Info("Redis client is not initialized or there is an error with Redis") + logger.Log.Info("Redis client is not initialized or there is an error with Redis") } w.WriteHeader(http.StatusOK) @@ -213,7 +213,7 @@ func (mh *metricHandler) MetricsBounties(w http.ResponseWriter, r *http.Request) pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -241,7 +241,7 @@ func (mh *metricHandler) MetricsBountiesCount(w http.ResponseWriter, r *http.Req pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -267,7 +267,7 @@ func (mh *metricHandler) MetricsBountiesProviders(w http.ResponseWriter, r *http pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -293,7 +293,7 @@ func MetricsCsv(w http.ResponseWriter, r *http.Request) { pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -319,7 +319,7 @@ func MetricsCsv(w http.ResponseWriter, r *http.Request) { err, url := UploadMetricsCsv(result, request) if err != nil { - utils.Log.Error("Error uploading csv: %v", err) + logger.Log.Error("Error uploading csv: %v", err) } w.WriteHeader(http.StatusOK) @@ -334,7 +334,7 @@ func GetAdminWorkspaces(w http.ResponseWriter, r *http.Request) { pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -458,19 +458,19 @@ func UploadMetricsCsv(data [][]string, request db.PaymentDateRange) (error, stri err, postPresignedUrl := createPresignedUrl(path) if err != nil { - utils.Log.Error("Presigned Error: %v", err) + logger.Log.Error("Presigned Error: %v", err) } r, err := http.NewRequest(http.MethodPut, postPresignedUrl, bytes.NewReader(fileBuffer)) if err != nil { - utils.Log.Error("Posting presign s3 error: %v", err) + logger.Log.Error("Posting presign s3 error: %v", err) } r.Header.Set("Content-Type", "multipart/form-data") client := &http.Client{} _, err = client.Do(r) if err != nil { - utils.Log.Error("Error occurred while posting presigned URL: %v", err) + logger.Log.Error("Error occurred while posting presigned URL: %v", err) } // Delete image from uploads folder diff --git a/handlers/people.go b/handlers/people.go index 4fc209ad0..2359252df 100644 --- a/handlers/people.go +++ b/handlers/people.go @@ -16,6 +16,7 @@ import ( "github.com/rs/xid" "github.com/stakwork/sphinx-tribes/auth" "github.com/stakwork/sphinx-tribes/db" + "github.com/stakwork/sphinx-tribes/logger" "github.com/stakwork/sphinx-tribes/utils" ) @@ -158,7 +159,7 @@ func (ph *peopleHandler) UpdatePerson(w http.ResponseWriter, r *http.Request) { } else { if person.OwnerPubKey != existing.OwnerPubKey && person.OwnerAlias != existing.OwnerAlias { // can't edit someone else's - utils.Log.Info("cant edit someone else") + logger.Log.Info("cant edit someone else") w.WriteHeader(http.StatusUnauthorized) return } @@ -200,7 +201,7 @@ func (ph *peopleHandler) UpsertLogin(w http.ResponseWriter, r *http.Request) { r.Body.Close() err = json.Unmarshal(body, &person) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusNotAcceptable) return } @@ -213,7 +214,7 @@ func (ph *peopleHandler) UpsertLogin(w http.ResponseWriter, r *http.Request) { if existing.ID == 0 { if person.ID != 0 { // cant try to "edit" if not exists already - utils.Log.Info("cant edit non existing") + logger.Log.Info("cant edit non existing") w.WriteHeader(http.StatusUnauthorized) return } @@ -223,7 +224,7 @@ func (ph *peopleHandler) UpsertLogin(w http.ResponseWriter, r *http.Request) { } else { // editing! needs ID if person.ID != 0 && person.ID != existing.ID { // can't edit someone else's - utils.Log.Info("cant edit someone else") + logger.Log.Info("cant edit someone else") w.WriteHeader(http.StatusUnauthorized) return } @@ -255,7 +256,7 @@ func (ph *peopleHandler) UpsertLogin(w http.ResponseWriter, r *http.Request) { tokenString, err := auth.EncodeJwt(person.OwnerPubKey) if err != nil { - utils.Log.Info("Cannot generate jwt token") + logger.Log.Info("Cannot generate jwt token") } responseData["jwt"] = tokenString @@ -285,41 +286,41 @@ func DeleteTicketByAdmin(w http.ResponseWriter, r *http.Request) { createdStr := chi.URLParam(r, "created") created, err := strconv.ParseInt(createdStr, 10, 64) if err != nil { - utils.Log.Info("Unable to convert created to int64") + logger.Log.Info("Unable to convert created to int64") w.WriteHeader(http.StatusInternalServerError) return } if created == 0 || pubKey == "" { - utils.Log.Info("Insufficient details to delete ticket") + logger.Log.Info("Insufficient details to delete ticket") w.WriteHeader(http.StatusBadRequest) return } if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } existing := db.DB.GetPersonByPubkey(pubKeyFromAuth) if existing.ID == 0 { - utils.Log.Info("Could not fetch admin details from db") + logger.Log.Info("Could not fetch admin details from db") w.WriteHeader(http.StatusUnauthorized) return } else if PersonIsAdmin(existing.OwnerPubKey) == false { - utils.Log.Info("Only admin is allowed to delete tickets") + logger.Log.Info("Only admin is allowed to delete tickets") w.WriteHeader(http.StatusUnauthorized) return } person := db.DB.GetPersonByPubkey(pubKey) if person.ID == 0 { - utils.Log.Info("Could not fetch person from db") + logger.Log.Info("Could not fetch person from db") w.WriteHeader(http.StatusUnauthorized) return } wanteds, ok := person.Extras["wanted"].([]interface{}) if !ok { - utils.Log.Info("No tickets found for person") + logger.Log.Info("No tickets found for person") w.WriteHeader(http.StatusBadRequest) return } @@ -341,7 +342,7 @@ func DeleteTicketByAdmin(w http.ResponseWriter, r *http.Request) { } if index == -1 { - utils.Log.Info("Ticket to delete not found") + logger.Log.Info("Ticket to delete not found") w.WriteHeader(http.StatusBadRequest) return } else { @@ -525,7 +526,7 @@ func (ph *peopleHandler) GetPersonByUuid(w http.ResponseWriter, r *http.Request) personResponse["twitter_confirmed"] = person.TwitterConfirmed personResponse["github_issues"] = person.GithubIssues if err != nil { - utils.Log.Error("==> error: %v", err) + logger.Log.Error("==> error: %v", err) } else { var badgeSlice []uint for i := 0; i < len(assetBalanceData); i++ { @@ -533,7 +534,7 @@ func (ph *peopleHandler) GetPersonByUuid(w http.ResponseWriter, r *http.Request) } personResponse["badges"] = badgeSlice } - utils.Log.Info("") + logger.Log.Info("") // FIXME use http to hit sphinx-element server for badges // Todo: response should include no pubKey // FIXME also filter by the tribe "profile_filters" @@ -546,11 +547,11 @@ func GetPersonAssetsByUuid(w http.ResponseWriter, r *http.Request) { person := db.DB.GetPersonByUuid(uuid) assetList, err := GetAssetList(person.OwnerPubKey) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusServiceUnavailable) return } - utils.Log.Info("") + logger.Log.Info("") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(assetList) } @@ -569,25 +570,25 @@ func (ph *peopleHandler) DeletePerson(w http.ResponseWriter, r *http.Request) { idString := chi.URLParam(r, "id") id, err := strconv.Atoi(idString) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusUnauthorized) return } if id == 0 { - utils.Log.Info("id is 0") + logger.Log.Info("id is 0") w.WriteHeader(http.StatusUnauthorized) return } existing := ph.db.GetPerson(uint(id)) if existing.ID == 0 { - utils.Log.Info("existing id is 0") + logger.Log.Info("existing id is 0") w.WriteHeader(http.StatusUnauthorized) return } if existing.OwnerPubKey != pubKeyFromAuth { - utils.Log.Info("keys dont match") + logger.Log.Info("keys dont match") w.WriteHeader(http.StatusUnauthorized) return } @@ -619,7 +620,7 @@ func GetAssetByPubkey(pubkey string) ([]db.AssetBalanceData, error) { resp, err := client.Do(req) if err != nil { - utils.Log.Error("GET error: %v", err) + logger.Log.Error("GET error: %v", err) return nil, err } defer resp.Body.Close() @@ -628,7 +629,7 @@ func GetAssetByPubkey(pubkey string) ([]db.AssetBalanceData, error) { body, err := io.ReadAll(resp.Body) err = json.Unmarshal(body, &r) if err != nil { - utils.Log.Error("json unmarshall error: %v", err) + logger.Log.Error("json unmarshall error: %v", err) return nil, err } @@ -652,7 +653,7 @@ func GetAssetList(pubkey string) ([]db.AssetListData, error) { resp, err := client.Do(req) if err != nil { - utils.Log.Error("GET error: %v", err) + logger.Log.Error("GET error: %v", err) return nil, err } defer resp.Body.Close() @@ -662,7 +663,7 @@ func GetAssetList(pubkey string) ([]db.AssetListData, error) { err = json.Unmarshal(body, &r) if err != nil { - utils.Log.Error("json unmarshall error: %v", err) + logger.Log.Error("json unmarshall error: %v", err) return nil, err } @@ -678,44 +679,44 @@ func AddOrRemoveBadge(w http.ResponseWriter, r *http.Request) { r.Body.Close() err = json.Unmarshal(body, &badgeCreationData) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusNotAcceptable) return } if badgeCreationData.Badge == "" { - utils.Log.Info("Badge cannot be Empty") + logger.Log.Info("Badge cannot be Empty") w.WriteHeader(http.StatusBadRequest) return } if badgeCreationData.Action == "" { - utils.Log.Info("Action cannot be Empty") + logger.Log.Info("Action cannot be Empty") w.WriteHeader(http.StatusBadRequest) return } if !(badgeCreationData.Action == "add" || badgeCreationData.Action == "remove") { - utils.Log.Info("Invalid action in Request") + logger.Log.Info("Invalid action in Request") w.WriteHeader(http.StatusBadRequest) return } if badgeCreationData.TribeUUID == "" { - utils.Log.Info("tribeId cannot be Empty") + logger.Log.Info("tribeId cannot be Empty") w.WriteHeader(http.StatusBadRequest) return } extractedPubkey, err := auth.VerifyTribeUUID(badgeCreationData.TribeUUID, false) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusUnauthorized) return } if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusBadRequest) return } @@ -723,8 +724,8 @@ func AddOrRemoveBadge(w http.ResponseWriter, r *http.Request) { tribe := db.DB.GetTribeByIdAndPubkey(badgeCreationData.TribeUUID, extractedPubkey) if pubKeyFromAuth != tribe.OwnerPubKey { - utils.Log.Info("%s", pubKeyFromAuth) - utils.Log.Info("mismatched pubkey") + logger.Log.Info("%s", pubKeyFromAuth) + logger.Log.Info("mismatched pubkey") w.WriteHeader(http.StatusUnauthorized) return } diff --git a/handlers/ticket.go b/handlers/ticket.go index d8a705ed8..ef482ea92 100644 --- a/handlers/ticket.go +++ b/handlers/ticket.go @@ -14,6 +14,7 @@ import ( "github.com/google/uuid" "github.com/stakwork/sphinx-tribes/auth" "github.com/stakwork/sphinx-tribes/db" + "github.com/stakwork/sphinx-tribes/logger" "github.com/stakwork/sphinx-tribes/utils" "github.com/stakwork/sphinx-tribes/websocket" ) @@ -81,7 +82,7 @@ func (th *ticketHandler) UpdateTicket(w http.ResponseWriter, r *http.Request) { pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("[ticket] no pubkey from auth") + logger.Log.Info("[ticket] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) json.NewEncoder(w).Encode(map[string]string{"error": "Unauthorized"}) return @@ -206,7 +207,7 @@ func (th *ticketHandler) DeleteTicket(w http.ResponseWriter, r *http.Request) { pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("[ticket] no pubkey from auth") + logger.Log.Info("[ticket] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) json.NewEncoder(w).Encode(map[string]string{"error": "Unauthorized"}) return @@ -240,7 +241,7 @@ func (th *ticketHandler) PostTicketDataToStakwork(w http.ResponseWriter, r *http pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("[ticket] no pubkey from auth") + logger.Log.Info("[ticket] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) json.NewEncoder(w).Encode(map[string]string{"error": "Unauthorized"}) return @@ -624,7 +625,7 @@ func (th *ticketHandler) GetTicketsByPhaseUUID(w http.ResponseWriter, r *http.Re ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } diff --git a/handlers/tribes.go b/handlers/tribes.go index e3344e303..eb9a00cb6 100644 --- a/handlers/tribes.go +++ b/handlers/tribes.go @@ -14,6 +14,7 @@ import ( "github.com/stakwork/sphinx-tribes/auth" "github.com/stakwork/sphinx-tribes/config" "github.com/stakwork/sphinx-tribes/db" + "github.com/stakwork/sphinx-tribes/logger" "github.com/stakwork/sphinx-tribes/utils" ) @@ -91,7 +92,7 @@ func PutTribeStats(w http.ResponseWriter, r *http.Request) { r.Body.Close() err = json.Unmarshal(body, &tribe) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusNotAcceptable) return } @@ -103,7 +104,7 @@ func PutTribeStats(w http.ResponseWriter, r *http.Request) { extractedPubkey, err := auth.VerifyTribeUUID(tribe.UUID, false) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusUnauthorized) return } @@ -139,7 +140,7 @@ func (th *tribeHandler) DeleteTribe(w http.ResponseWriter, r *http.Request) { extractedPubkey, err := th.verifyTribeUUID(uuid, false) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusUnauthorized) return } @@ -214,13 +215,13 @@ func (th *tribeHandler) CreateOrEditTribe(w http.ResponseWriter, r *http.Request r.Body.Close() err = json.Unmarshal(body, &tribe) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusNotAcceptable) return } if tribe.UUID == "" { - utils.Log.Info("createOrEditTribe no uuid") + logger.Log.Info("createOrEditTribe no uuid") w.WriteHeader(http.StatusUnauthorized) return } @@ -229,7 +230,7 @@ func (th *tribeHandler) CreateOrEditTribe(w http.ResponseWriter, r *http.Request extractedPubkey, err := th.verifyTribeUUID(tribe.UUID, false) if err != nil { - utils.Log.Error("extract UUID error: %v", err) + logger.Log.Error("extract UUID error: %v", err) w.WriteHeader(http.StatusUnauthorized) return } @@ -238,7 +239,7 @@ func (th *tribeHandler) CreateOrEditTribe(w http.ResponseWriter, r *http.Request tribe.Created = &now } else { // IF PUBKEY IN CONTEXT, MUST AUTH! if pubKeyFromAuth != extractedPubkey { - utils.Log.Info("createOrEditTribe pubkeys dont match") + logger.Log.Info("createOrEditTribe pubkeys dont match") w.WriteHeader(http.StatusUnauthorized) return } @@ -249,9 +250,9 @@ func (th *tribeHandler) CreateOrEditTribe(w http.ResponseWriter, r *http.Request tribe.UniqueName, _ = th.tribeUniqueNameFromName(tribe.Name) } else { // already exists! make sure it's owned if existing.OwnerPubKey != extractedPubkey { - utils.Log.Info("createOrEditTribe tribe.ownerPubKey not match") - utils.Log.Info("existing owner: %s", existing.OwnerPubKey) - utils.Log.Info("extracted pubkey: %s", extractedPubkey) + logger.Log.Info("createOrEditTribe tribe.ownerPubKey not match") + logger.Log.Info("existing owner: %s", existing.OwnerPubKey) + logger.Log.Info("extracted pubkey: %s", extractedPubkey) w.WriteHeader(http.StatusUnauthorized) return } @@ -263,7 +264,7 @@ func (th *tribeHandler) CreateOrEditTribe(w http.ResponseWriter, r *http.Request _, err = th.db.CreateOrEditTribe(tribe) if err != nil { - utils.Log.Error("=> ERR createOrEditTribe: %v", err) + logger.Log.Error("=> ERR createOrEditTribe: %v", err) w.WriteHeader(http.StatusBadRequest) return } @@ -284,7 +285,7 @@ func PutTribeActivity(w http.ResponseWriter, r *http.Request) { extractedPubkey, err := auth.VerifyTribeUUID(uuid, false) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusUnauthorized) return } @@ -316,7 +317,7 @@ func (th *tribeHandler) SetTribePreview(w http.ResponseWriter, r *http.Request) extractedPubkey, err := th.verifyTribeUUID(uuid, false) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusUnauthorized) return } @@ -350,7 +351,7 @@ func CreateLeaderBoard(w http.ResponseWriter, r *http.Request) { extractedPubkey, err := auth.VerifyTribeUUID(uuid, false) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusUnauthorized) return } @@ -365,7 +366,7 @@ func CreateLeaderBoard(w http.ResponseWriter, r *http.Request) { r.Body.Close() err = json.Unmarshal(body, &leaderBoard) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusNotAcceptable) return } @@ -373,7 +374,7 @@ func CreateLeaderBoard(w http.ResponseWriter, r *http.Request) { _, err = db.DB.CreateLeaderBoard(uuid, leaderBoard) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusNotAcceptable) return } @@ -421,7 +422,7 @@ func UpdateLeaderBoard(w http.ResponseWriter, r *http.Request) { extractedPubkey, err := auth.VerifyTribeUUID(uuid, false) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusUnauthorized) return } @@ -438,7 +439,7 @@ func UpdateLeaderBoard(w http.ResponseWriter, r *http.Request) { r.Body.Close() err = json.Unmarshal(body, &leaderBoard) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusNotAcceptable) return } @@ -469,7 +470,7 @@ func GenerateInvoice(w http.ResponseWriter, r *http.Request) { r.Body.Close() if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusNotAcceptable) return } @@ -477,7 +478,7 @@ func GenerateInvoice(w http.ResponseWriter, r *http.Request) { err = json.Unmarshal(body, &invoice) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusNotAcceptable) return } @@ -570,7 +571,7 @@ func (th *tribeHandler) GenerateV1BudgetInvoice(w http.ResponseWriter, r *http.R r.Body.Close() if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusNotAcceptable) return } @@ -578,7 +579,7 @@ func (th *tribeHandler) GenerateV1BudgetInvoice(w http.ResponseWriter, r *http.R err = json.Unmarshal(body, &invoice) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusNotAcceptable) return } @@ -662,7 +663,7 @@ func (th *tribeHandler) GenerateV2BudgetInvoice(w http.ResponseWriter, r *http.R r.Body.Close() if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusNotAcceptable) return } @@ -670,7 +671,7 @@ func (th *tribeHandler) GenerateV2BudgetInvoice(w http.ResponseWriter, r *http.R err = json.Unmarshal(body, &invoice) if err != nil { - utils.Log.Error("%v", err) + logger.Log.Error("%v", err) w.WriteHeader(http.StatusNotAcceptable) return } diff --git a/handlers/workspaces.go b/handlers/workspaces.go index 2bb224af5..09ad22f04 100644 --- a/handlers/workspaces.go +++ b/handlers/workspaces.go @@ -13,6 +13,7 @@ import ( "github.com/rs/xid" "github.com/stakwork/sphinx-tribes/auth" "github.com/stakwork/sphinx-tribes/db" + "github.com/stakwork/sphinx-tribes/logger" "github.com/stakwork/sphinx-tribes/utils" "gorm.io/gorm" ) @@ -46,7 +47,7 @@ func (oh *workspaceHandler) CreateOrEditWorkspace(w http.ResponseWriter, r *http ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("[workspaces] no pubkey from auth") + logger.Log.Info("[workspaces] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -58,7 +59,7 @@ func (oh *workspaceHandler) CreateOrEditWorkspace(w http.ResponseWriter, r *http err := json.Unmarshal(body, &workspace) if err != nil { - utils.Log.Error("[workspaces] %v", err) + logger.Log.Error("[workspaces] %v", err) w.WriteHeader(http.StatusNotAcceptable) return } @@ -66,14 +67,14 @@ func (oh *workspaceHandler) CreateOrEditWorkspace(w http.ResponseWriter, r *http workspace.Name = strings.TrimSpace(workspace.Name) if len(workspace.Name) == 0 || len(workspace.Name) > 20 { - utils.Log.Info("[workspaces] invalid workspace name %s", workspace.Name) + logger.Log.Info("[workspaces] invalid workspace name %s", workspace.Name) w.WriteHeader(http.StatusBadRequest) json.NewEncoder(w).Encode("Error: workspace name must be present and should not exceed 20 character") return } if len(workspace.Description) > 120 { - utils.Log.Info("[workspaces] invalid workspace name %s", workspace.Description) + logger.Log.Info("[workspaces] invalid workspace name %s", workspace.Description) w.WriteHeader(http.StatusBadRequest) json.NewEncoder(w).Encode("Error: workspace description should not exceed 120 character") return @@ -82,9 +83,9 @@ func (oh *workspaceHandler) CreateOrEditWorkspace(w http.ResponseWriter, r *http if pubKeyFromAuth != workspace.OwnerPubKey { hasRole := db.UserHasAccess(pubKeyFromAuth, workspace.Uuid, db.EditOrg) if !hasRole { - utils.Log.Info("[workspaces] mismatched pubkey") - utils.Log.Info("[workspaces] Auth pubkey: %s", pubKeyFromAuth) - utils.Log.Info("[workspaces] OwnerPubKey: %s", workspace.OwnerPubKey) + logger.Log.Info("[workspaces] mismatched pubkey") + logger.Log.Info("[workspaces] Auth pubkey: %s", pubKeyFromAuth) + logger.Log.Info("[workspaces] OwnerPubKey: %s", workspace.OwnerPubKey) w.WriteHeader(http.StatusUnauthorized) json.NewEncoder(w).Encode("Don't have access to Edit workspace") return @@ -110,7 +111,7 @@ func (oh *workspaceHandler) CreateOrEditWorkspace(w http.ResponseWriter, r *http existing := oh.db.GetWorkspaceByUuid(workspace.Uuid) if existing.ID == 0 { // new! if workspace.ID != 0 { // can't try to "edit" if it does not exist already - utils.Log.Info("[workspaces] cant edit non existing") + logger.Log.Info("[workspaces] cant edit non existing") w.WriteHeader(http.StatusUnauthorized) return } @@ -177,7 +178,7 @@ func (oh *workspaceHandler) CreateWorkspaceUser(w http.ResponseWriter, r *http.R r.Body.Close() if err != nil { - utils.Log.Error("[body] %v", err) + logger.Log.Error("[body] %v", err) w.WriteHeader(http.StatusNotAcceptable) return } @@ -192,13 +193,13 @@ func (oh *workspaceHandler) CreateWorkspaceUser(w http.ResponseWriter, r *http.R workspace := oh.db.GetWorkspaceByUuid(workspaceUser.WorkspaceUuid) if err != nil { - utils.Log.Error("[workspaces] %v", err) + logger.Log.Error("[workspaces] %v", err) w.WriteHeader(http.StatusNotAcceptable) return } if pubKeyFromAuth == "" { - utils.Log.Info("[workspaces] no pubkey from auth") + logger.Log.Info("[workspaces] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -264,7 +265,7 @@ func GetWorkspaceUser(w http.ResponseWriter, r *http.Request) { pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("[workspaces] no pubkey from auth") + logger.Log.Info("[workspaces] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -293,7 +294,7 @@ func DeleteWorkspaceUser(w http.ResponseWriter, r *http.Request) { r.Body.Close() if err != nil { - utils.Log.Error("[body] %v", err) + logger.Log.Error("[body] %v", err) w.WriteHeader(http.StatusNotAcceptable) return } @@ -305,13 +306,13 @@ func DeleteWorkspaceUser(w http.ResponseWriter, r *http.Request) { } if err != nil { - utils.Log.Error("[workspaces] %v", err) + logger.Log.Error("[workspaces] %v", err) w.WriteHeader(http.StatusNotAcceptable) return } if pubKeyFromAuth == "" { - utils.Log.Info("[workspaces] no pubkey from auth") + logger.Log.Info("[workspaces] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -362,7 +363,7 @@ func (oh *workspaceHandler) AddUserRoles(w http.ResponseWriter, r *http.Request) r.Body.Close() if err != nil { - utils.Log.Error("[body] %v", err) + logger.Log.Error("[body] %v", err) w.WriteHeader(http.StatusNotAcceptable) return } @@ -370,7 +371,7 @@ func (oh *workspaceHandler) AddUserRoles(w http.ResponseWriter, r *http.Request) err = json.Unmarshal(body, &roles) if err != nil { - utils.Log.Error("[workspaces]: %v", err) + logger.Log.Error("[workspaces]: %v", err) w.WriteHeader(http.StatusNotAcceptable) return } @@ -465,7 +466,7 @@ func GetUserWorkspaces(w http.ResponseWriter, r *http.Request) { userId, _ := utils.ConvertStringToUint(userIdParam) if userId == 0 { - utils.Log.Info("[workspaces] provide user id") + logger.Log.Info("[workspaces] provide user id") w.WriteHeader(http.StatusNotAcceptable) return } @@ -483,7 +484,7 @@ func (oh *workspaceHandler) GetUserDropdownWorkspaces(w http.ResponseWriter, r * userId, _ := utils.ConvertStringToUint(userIdParam) if userId == 0 { - utils.Log.Info("[workspaces] provide user id") + logger.Log.Info("[workspaces] provide user id") w.WriteHeader(http.StatusNotAcceptable) return } @@ -582,7 +583,7 @@ func (oh *workspaceHandler) GetWorkspaceBudget(w http.ResponseWriter, r *http.Re uuid := chi.URLParam(r, "uuid") if pubKeyFromAuth == "" { - utils.Log.Info("[workspaces] no pubkey from auth") + logger.Log.Info("[workspaces] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -628,7 +629,7 @@ func GetPaymentHistory(w http.ResponseWriter, r *http.Request) { uuid := chi.URLParam(r, "uuid") if pubKeyFromAuth == "" { - utils.Log.Info("[workspaces] no pubkey from auth") + logger.Log.Info("[workspaces] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -668,7 +669,7 @@ func UpdateWorkspacePendingPayments(w http.ResponseWriter, r *http.Request) { workspace_uuid := chi.URLParam(r, "workspace_uuid") if pubKeyFromAuth == "" { - utils.Log.Info("no pubkey from auth") + logger.Log.Info("no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -722,7 +723,7 @@ func (oh *workspaceHandler) PollBudgetInvoices(w http.ResponseWriter, r *http.Re uuid := chi.URLParam(r, "uuid") if pubKeyFromAuth == "" { - utils.Log.Info("[workspaces] no pubkey from auth") + logger.Log.Info("[workspaces] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -760,7 +761,7 @@ func (oh *workspaceHandler) PollUserWorkspacesBudget(w http.ResponseWriter, r *h pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("[workspaces] no pubkey from auth") + logger.Log.Info("[workspaces] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -807,7 +808,7 @@ func GetInvoicesCount(w http.ResponseWriter, r *http.Request) { uuid := chi.URLParam(r, "uuid") if pubKeyFromAuth == "" { - utils.Log.Info("[workspaces] no pubkey from auth") + logger.Log.Info("[workspaces] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -822,7 +823,7 @@ func GetAllUserInvoicesCount(w http.ResponseWriter, r *http.Request) { pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("[workspaces] no pubkey from auth") + logger.Log.Info("[workspaces] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -843,7 +844,7 @@ func (oh *workspaceHandler) DeleteWorkspace(w http.ResponseWriter, r *http.Reque uuid := chi.URLParam(r, "uuid") if pubKeyFromAuth == "" { - utils.Log.Info("[workspaces] no pubkey from auth") + logger.Log.Info("[workspaces] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -851,7 +852,7 @@ func (oh *workspaceHandler) DeleteWorkspace(w http.ResponseWriter, r *http.Reque workspace := oh.db.GetWorkspaceByUuid(uuid) if pubKeyFromAuth != workspace.OwnerPubKey { msg := "only workspace admin can delete an workspace" - utils.Log.Info("[workspaces] %s", msg) + logger.Log.Info("[workspaces] %s", msg) w.WriteHeader(http.StatusUnauthorized) json.NewEncoder(w).Encode(msg) return @@ -860,7 +861,7 @@ func (oh *workspaceHandler) DeleteWorkspace(w http.ResponseWriter, r *http.Reque // Soft delete Workspace and delete user data if err := oh.db.ProcessDeleteWorkspace(uuid); err != nil { msg := "Error removing users from workspace" - utils.Log.Error("%s: %v", msg, err) + logger.Log.Error("%s: %v", msg, err) w.WriteHeader(http.StatusInternalServerError) json.NewEncoder(w).Encode(msg) return @@ -874,7 +875,7 @@ func (oh *workspaceHandler) UpdateWorkspace(w http.ResponseWriter, r *http.Reque ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("[workspaces] no pubkey from auth") + logger.Log.Info("[workspaces] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -885,7 +886,7 @@ func (oh *workspaceHandler) UpdateWorkspace(w http.ResponseWriter, r *http.Reque err := json.Unmarshal(body, &workspace) if err != nil { - utils.Log.Error("[workspaces] %v", err) + logger.Log.Error("[workspaces] %v", err) w.WriteHeader(http.StatusNotAcceptable) return } @@ -893,9 +894,9 @@ func (oh *workspaceHandler) UpdateWorkspace(w http.ResponseWriter, r *http.Reque if pubKeyFromAuth != workspace.OwnerPubKey { hasRole := db.UserHasAccess(pubKeyFromAuth, workspace.Uuid, db.EditOrg) if !hasRole { - utils.Log.Info("[workspaces] mismatched pubkey") - utils.Log.Info("Auth Pubkey: %s", pubKeyFromAuth) - utils.Log.Info("OwnerPubKey: %s", workspace.OwnerPubKey) + logger.Log.Info("[workspaces] mismatched pubkey") + logger.Log.Info("Auth Pubkey: %s", pubKeyFromAuth) + logger.Log.Info("OwnerPubKey: %s", workspace.OwnerPubKey) w.WriteHeader(http.StatusUnauthorized) json.NewEncoder(w).Encode("Don't have access to Edit workspace") return @@ -925,7 +926,7 @@ func (oh *workspaceHandler) CreateOrEditWorkspaceRepository(w http.ResponseWrite ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("[workspaces] no pubkey from auth") + logger.Log.Info("[workspaces] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -936,7 +937,7 @@ func (oh *workspaceHandler) CreateOrEditWorkspaceRepository(w http.ResponseWrite err := json.Unmarshal(body, &workspaceRepo) if err != nil { - utils.Log.Error("[workspaces] %v", err) + logger.Log.Error("[workspaces] %v", err) w.WriteHeader(http.StatusNotAcceptable) return } @@ -985,7 +986,7 @@ func (oh *workspaceHandler) GetWorkspaceRepositorByWorkspaceUuid(w http.Response ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("[workspaces] no pubkey from auth") + logger.Log.Info("[workspaces] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -1001,7 +1002,7 @@ func (oh *workspaceHandler) GetWorkspaceRepoByWorkspaceUuidAndRepoUuid(w http.Re ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("[workspaces] no pubkey from auth") + logger.Log.Info("[workspaces] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -1010,7 +1011,7 @@ func (oh *workspaceHandler) GetWorkspaceRepoByWorkspaceUuidAndRepoUuid(w http.Re uuid := chi.URLParam(r, "uuid") WorkspaceRepository, err := oh.db.GetWorkspaceRepoByWorkspaceUuidAndRepoUuid(workspace_uuid, uuid) if err != nil { - utils.Log.Error("[workspaces] workspace repository not found: %v", err) + logger.Log.Error("[workspaces] workspace repository not found: %v", err) w.WriteHeader(http.StatusNotFound) json.NewEncoder(w).Encode(map[string]string{"error": "Repository not found"}) return @@ -1026,7 +1027,7 @@ func (oh *workspaceHandler) DeleteWorkspaceRepository(w http.ResponseWriter, r * pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("[workspaces] no pubkey from auth") + logger.Log.Info("[workspaces] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -1044,7 +1045,7 @@ func (oh *workspaceHandler) GetFeaturesByWorkspaceUuid(w http.ResponseWriter, r ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("[workspaces] no pubkey from auth") + logger.Log.Info("[workspaces] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -1079,7 +1080,7 @@ func (oh *workspaceHandler) GetLastWithdrawal(w http.ResponseWriter, r *http.Req ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("[workspaces] no pubkey from auth") + logger.Log.Info("[workspaces] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -1135,7 +1136,7 @@ func (oh *workspaceHandler) CreateOrEditWorkspaceCodeGraph(w http.ResponseWriter ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("[workspaces] no pubkey from auth") + logger.Log.Info("[workspaces] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -1146,7 +1147,7 @@ func (oh *workspaceHandler) CreateOrEditWorkspaceCodeGraph(w http.ResponseWriter err := json.Unmarshal(body, &codeGraph) if err != nil { - utils.Log.Error("[workspaces] %v", err) + logger.Log.Error("[workspaces] %v", err) w.WriteHeader(http.StatusNotAcceptable) return } @@ -1186,7 +1187,7 @@ func (oh *workspaceHandler) GetWorkspaceCodeGraphByUUID(w http.ResponseWriter, r ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("[workspaces] no pubkey from auth") + logger.Log.Info("[workspaces] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -1194,7 +1195,7 @@ func (oh *workspaceHandler) GetWorkspaceCodeGraphByUUID(w http.ResponseWriter, r uuid := chi.URLParam(r, "uuid") codeGraph, err := oh.db.GetCodeGraphByUUID(uuid) if err != nil { - utils.Log.Error("[workspaces] code graph not found: %v", err) + logger.Log.Error("[workspaces] code graph not found: %v", err) w.WriteHeader(http.StatusNotFound) json.NewEncoder(w).Encode(map[string]string{"error": "Code graph not found"}) return @@ -1209,7 +1210,7 @@ func (oh *workspaceHandler) GetCodeGraphsByWorkspaceUuid(w http.ResponseWriter, ctx := r.Context() pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("[workspaces] no pubkey from auth") + logger.Log.Info("[workspaces] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } @@ -1231,7 +1232,7 @@ func (oh *workspaceHandler) DeleteWorkspaceCodeGraph(w http.ResponseWriter, r *h pubKeyFromAuth, _ := ctx.Value(auth.ContextKey).(string) if pubKeyFromAuth == "" { - utils.Log.Info("[workspaces] no pubkey from auth") + logger.Log.Info("[workspaces] no pubkey from auth") w.WriteHeader(http.StatusUnauthorized) return } diff --git a/utils/logger.go b/logger/logger.go similarity index 99% rename from utils/logger.go rename to logger/logger.go index a0ba76c0a..8c49bd4de 100644 --- a/utils/logger.go +++ b/logger/logger.go @@ -1,4 +1,4 @@ -package utils +package logger import ( "github.com/google/uuid" diff --git a/routes/index.go b/routes/index.go index 9f17d1a73..2347dcca9 100644 --- a/routes/index.go +++ b/routes/index.go @@ -19,6 +19,7 @@ import ( "github.com/stakwork/sphinx-tribes/config" "github.com/stakwork/sphinx-tribes/db" "github.com/stakwork/sphinx-tribes/handlers" + "github.com/stakwork/sphinx-tribes/logger" "github.com/stakwork/sphinx-tribes/utils" ) @@ -107,9 +108,9 @@ func NewRouter() *http.Server { server := &http.Server{Addr: ":" + PORT, Handler: r} go func() { - utils.Log.Info("Listening on port %s", PORT) + logger.Log.Info("Listening on port %s", PORT) if err := server.ListenAndServe(); err != nil { - utils.Log.Error("server err: %s", err.Error()) + logger.Log.Error("server err: %s", err.Error()) } }() return server @@ -148,7 +149,7 @@ func getFromAuth(path string) (*extractResponse, error) { func sendEdgeListToJarvis(edgeList utils.EdgeList) error { if config.JarvisUrl == "" || config.JarvisToken == "" { - utils.Log.Info("Jarvis configuration not found, skipping error reporting") + logger.Log.Info("Jarvis configuration not found, skipping error reporting") return nil } @@ -156,13 +157,13 @@ func sendEdgeListToJarvis(edgeList utils.EdgeList) error { jsonData, err := json.Marshal(edgeList) if err != nil { - utils.Log.Error("Failed to marshal edge list: %v", err) + logger.Log.Error("Failed to marshal edge list: %v", err) return nil } req, err := http.NewRequest("POST", jarvisURL, bytes.NewBuffer(jsonData)) if err != nil { - utils.Log.Error("Failed to create Jarvis request: %v", err) + logger.Log.Error("Failed to create Jarvis request: %v", err) return nil } @@ -175,13 +176,13 @@ func sendEdgeListToJarvis(edgeList utils.EdgeList) error { resp, err := client.Do(req) if err != nil { - utils.Log.Error("Failed to send error to Jarvis: %v", err) + logger.Log.Error("Failed to send error to Jarvis: %v", err) return err } defer resp.Body.Close() if resp.StatusCode >= 200 && resp.StatusCode < 300 { - utils.Log.Info("Successfully sent error to Jarvis") + logger.Log.Info("Successfully sent error to Jarvis") return nil } @@ -204,7 +205,7 @@ func internalServerErrorHandler(next http.Handler) http.Handler { // Format stack trace to edge list edgeList := utils.FormatStacktraceToEdgeList(stackTrace, err) - utils.Log.Error("Internal Server Error: %s %s\nError: %v\nStack Trace:\n%s\nEdge List:\n%+v\n", + logger.Log.Error("Internal Server Error: %s %s\nError: %v\nStack Trace:\n%s\nEdge List:\n%+v\n", r.Method, r.URL.Path, err, @@ -214,7 +215,7 @@ func internalServerErrorHandler(next http.Handler) http.Handler { go func() { if err := sendEdgeListToJarvis(edgeList); err != nil { - utils.Log.Error("Error sending to Jarvis: %v\n", err) + logger.Log.Error("Error sending to Jarvis: %v\n", err) } }() @@ -231,7 +232,7 @@ func initChi() *chi.Mux { r.Use(middleware.RequestID) r.Use(middleware.Logger) r.Use(middleware.Recoverer) - r.Use(utils.RouteBasedUUIDMiddleware) + r.Use(logger.RouteBasedUUIDMiddleware) r.Use(internalServerErrorHandler) cors := cors.New(cors.Options{ AllowedOrigins: []string{"*"}, diff --git a/utils/helpers.go b/utils/helpers.go index 5785643e7..2bc9110e7 100644 --- a/utils/helpers.go +++ b/utils/helpers.go @@ -8,13 +8,14 @@ import ( "time" decodepay "github.com/nbd-wtf/ln-decodepay" + "github.com/stakwork/sphinx-tribes/logger" ) func GetRandomToken(length int) string { randomBytes := make([]byte, 32) _, err := rand.Read(randomBytes) if err != nil { - Log.Error("Random token error: %v", err) + logger.Log.Error("Random token error: %v", err) } return base32.StdEncoding.EncodeToString(randomBytes)[:length] } @@ -23,7 +24,7 @@ func ConvertStringToUint(number string) (uint, error) { numberParse, err := strconv.ParseUint(number, 10, 32) if err != nil { - Log.Error("could not parse string to uint: %v", err) + logger.Log.Error("could not parse string to uint: %v", err) return 0, err } @@ -34,7 +35,7 @@ func ConvertStringToInt(number string) (int, error) { numberParse, err := strconv.ParseInt(number, 10, 32) if err != nil { - Log.Error("could not parse string to int: %v", err) + logger.Log.Error("could not parse string to int: %v", err) return 0, err } @@ -45,7 +46,7 @@ func GetInvoiceAmount(paymentRequest string) uint { decodedInvoice, err := decodepay.Decodepay(paymentRequest) if err != nil { - Log.Error("Could not Decode Invoice: %v", err) + logger.Log.Error("Could not Decode Invoice: %v", err) return 0 } amountInt := decodedInvoice.MSatoshi / 1000 @@ -57,7 +58,7 @@ func GetInvoiceAmount(paymentRequest string) uint { func GetInvoiceExpired(paymentRequest string) bool { decodedInvoice, err := decodepay.Decodepay(paymentRequest) if err != nil { - Log.Error("Could not Decode Invoice: %v", err) + logger.Log.Error("Could not Decode Invoice: %v", err) return false } @@ -82,7 +83,7 @@ func ConvertTimeToTimestamp(date string) int { t, err := time.Parse(format, dateTouse) if err != nil { - Log.Error("Parse string to timestamp: %v", err) + logger.Log.Error("Parse string to timestamp: %v", err) } else { return int(t.Unix()) } diff --git a/utils/twitter.go b/utils/twitter.go index b74a0b641..e2e4ec2e5 100644 --- a/utils/twitter.go +++ b/utils/twitter.go @@ -9,6 +9,7 @@ import ( "github.com/imroc/req" "github.com/stakwork/sphinx-tribes/auth" + "github.com/stakwork/sphinx-tribes/logger" ) func ConfirmIdentityTweet(username string) (string, error) { @@ -20,7 +21,7 @@ func ConfirmIdentityTweet(username string) (string, error) { if err != nil { return "", err } - Log.Info("Twitter verification token: %s", token) + logger.Log.Info("Twitter verification token: %s", token) pubkey, err := auth.VerifyArbitrary(token, "Sphinx Verification") return pubkey, err } diff --git a/utils/workflow_processor.go b/utils/workflow_processor.go index e3da5bade..f6ed0e09a 100644 --- a/utils/workflow_processor.go +++ b/utils/workflow_processor.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/google/uuid" + "github.com/stakwork/sphinx-tribes/logger" ) type ProcessorConfig struct { @@ -33,6 +34,6 @@ func lookupProcessingConfig(source string) error { } func processWithHandler(requestID string) (string, error) { - Log.Info("Processing with default handler") + logger.Log.Info("Processing with default handler") return fmt.Sprintf("Processed with default handler, RequestID: %s", requestID), nil }