Skip to content

Commit

Permalink
refactor(auth): migrate from fmt.Print to structured logging (stakwor…
Browse files Browse the repository at this point in the history
…k#2279)

* refactor: migrate auth package from fmt to logger

* using logger for RouteBasedUUIDMiddleware

* readd fmt

---------

Co-authored-by: kevkevinpal <[email protected]>
  • Loading branch information
saithsab877 and kevkevinpal authored Dec 23, 2024
1 parent 11b820b commit 2db52f0
Show file tree
Hide file tree
Showing 29 changed files with 321 additions and 306 deletions.
37 changes: 19 additions & 18 deletions auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -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
}
Expand All @@ -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
}
Expand All @@ -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
Expand All @@ -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
}
Expand All @@ -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
}
Expand All @@ -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
}
Expand All @@ -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
}
Expand All @@ -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
}
Expand Down Expand Up @@ -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")
}
}
Expand Down Expand Up @@ -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())
Expand Down
20 changes: 10 additions & 10 deletions db/alerts.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"os"
"strconv"

"github.com/stakwork/sphinx-tribes/utils"
"github.com/stakwork/sphinx-tribes/logger"
)

type Action struct {
Expand All @@ -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
}

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

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

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

Expand Down
8 changes: 4 additions & 4 deletions db/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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")
Expand All @@ -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{})
Expand Down Expand Up @@ -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)
Expand Down
5 changes: 3 additions & 2 deletions db/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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"
Expand Down
3 changes: 2 additions & 1 deletion db/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"strings"
"time"

"github.com/stakwork/sphinx-tribes/logger"
"github.com/stakwork/sphinx-tribes/utils"
)

Expand All @@ -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
Expand Down
11 changes: 6 additions & 5 deletions db/redis.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"time"

"github.com/redis/go-redis/v9"
"github.com/stakwork/sphinx-tribes/logger"
"github.com/stakwork/sphinx-tribes/utils"
)

Expand All @@ -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
Expand All @@ -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)
Expand Down
Loading

0 comments on commit 2db52f0

Please sign in to comment.