From 593cb7327616a0ee0362bccb6c0d5f2d92045a59 Mon Sep 17 00:00:00 2001 From: Fbulkaya Date: Sun, 23 Feb 2025 21:38:08 +0300 Subject: [PATCH 1/3] Update .gitignore, Dockerfile, config, and other files --- .gitignore | 2 ++ Dockerfile | 2 +- config/db.go | 59 +++++++++++++++++++++++----------------------- db/db.go | 16 +++++++++---- docker-compose.yml | 34 ++++++++++++++++++++++++++ go.mod | 1 - go.sum | 3 +-- model/iban.go | 47 +++++++++++++++++------------------- model/user.go | 19 +++++++-------- 9 files changed, 109 insertions(+), 74 deletions(-) create mode 100644 docker-compose.yml diff --git a/.gitignore b/.gitignore index 48dbc30..6e141ba 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,7 @@ .env .docker_build/ +docker-compose.override.yml +tmp/ .theia/ vendor/ config/database.yml diff --git a/Dockerfile b/Dockerfile index 272a536..94c9c73 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.12 as builder +FROM golang:1.20 as builder WORKDIR /usr/app diff --git a/config/db.go b/config/db.go index 3712338..444aa20 100644 --- a/config/db.go +++ b/config/db.go @@ -3,63 +3,62 @@ package config import ( "errors" "fmt" + "log" + "os" + "time" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" _ "github.com/jinzhu/gorm/dialects/postgres" - _ "github.com/mattn/go-sqlite3" "github.com/monopayments/iban.im/model" "github.com/qor/validations" - - // _ "github.com/jinzhu/gorm/dialects/sqlite" TODO - disabled for compile time issue - "os" - "time" ) -// global DB variable => TODO repository pattern var DB *gorm.DB -func init() { +func InitDB() { var err error - if Config.App.Env == "gitpod" && Config.Db.Adapter == "postgres" { - if err = os.Unsetenv("PGHOSTADDR"); err != nil { - panic(err) - } + + // Config yerine doğrudan ENV değişkenlerini alıyoruz + adapter := os.Getenv("DB_ADAPTER") // "postgres" veya "mysql" + if adapter == "" { + adapter = "postgres" // Varsayılan olarak PostgreSQL kullan } var connStr string - adapter := Config.Db.Adapter if adapter == "mysql" { - connStr = fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?parseTime=True&loc=Local", Config.Db.User, Config.Db.Password, Config.Db.Host, Config.Db.Port, Config.Db.Name) + connStr = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=True&loc=Local", + os.Getenv("DB_USER"), + os.Getenv("DB_PASSWORD"), + os.Getenv("DB_HOST"), + os.Getenv("DB_PORT"), + os.Getenv("DB_NAME"), + ) } else if adapter == "postgres" { - connStr = fmt.Sprintf("postgres://%v:%v@%v/%v?sslmode=disable", Config.Db.User, Config.Db.Password, Config.Db.Host, Config.Db.Name) - } else if adapter == "sqlite3" || adapter == "sqlite" { - connStr = Config.Db.Name + connStr = fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=disable", + os.Getenv("DB_USER"), + os.Getenv("DB_PASSWORD"), + os.Getenv("DB_HOST"), + os.Getenv("DB_PORT"), + os.Getenv("DB_NAME"), + ) } else { - panic(errors.New("your database is not supported")) + panic(errors.New("unsupported database adapter")) } DB, err = gorm.Open(adapter, connStr) if err != nil { - panic(err) + log.Fatal("Database connection failed:", err) } + validations.RegisterCallbacks(DB) - DB.LogMode(Config.App.Debug) + DB.LogMode(true) DB.DB().SetMaxIdleConns(10) DB.DB().SetMaxOpenConns(30) DB.DB().SetConnMaxLifetime(time.Second * 60) + // Otomatik migration DB.AutoMigrate(&model.User{}, &model.Iban{}, &model.Group{}) - // TODO ping control for mysql - if adapter == "mysql" { - go checkPing() - } -} - -func checkPing() { - for { - time.Sleep(time.Second * 15) - DB.DB().Ping() - } + log.Println("Database connected successfully!") } diff --git a/db/db.go b/db/db.go index 1e544ac..ca025ec 100644 --- a/db/db.go +++ b/db/db.go @@ -1,6 +1,7 @@ package db import ( + "fmt" "os" "github.com/jinzhu/gorm" @@ -13,10 +14,10 @@ type DB struct { *gorm.DB } -var connStrMap = map[string]string { - "localhost" : "host=localhost port=5432 user=ibanim dbname=ibanim password=ibanim sslmode=disable", - "docker" : "host=host.docker.internal port=5432 user=ibanim dbname=ibanim password=ibanim sslmode=disable", - "gitpod" : "host=localhost port=5432 user=gitpod dbname=ibanim sslmode=disable", +var connStrMap = map[string]string{ + "localhost": "host=localhost port=5432 user=ibanim dbname=ibanim password=ibanim sslmode=disable", + "docker": "host=host.docker.internal port=5432 user=ibanim dbname=ibanim password=ibanim sslmode=disable", + "gitpod": "host=localhost port=5432 user=gitpod dbname=ibanim sslmode=disable", } // ConnectDB : connecting DB @@ -30,6 +31,13 @@ func ConnectDB(env string) (*DB, error) { if err != nil { panic(err) } + //Check database connection + err = db.DB().Ping() + if err != nil { + panic("Database connection failed!" + err.Error()) + } else { + fmt.Println("database connection successful!") + } return &DB{db}, nil } diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..59c1144 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,34 @@ +version: '3.8' + +services: + db: + image: postgres:15 + restart: always + container_name: postgres_db + environment: + POSTGRES_USER: myuser + POSTGRES_PASSWORD: mypassword + POSTGRES_DB: mydb + ports: + - "5432:5432" + volumes: + - postgres_data:/var/lib/postgresql/data + + app: + build: . + restart: always + container_name: go_app + environment: + - DB_ADAPTER=postgres + - DB_HOST=db + - DB_PORT=5432 + - DB_USER=myuser + - DB_PASSWORD=mypassword + - DB_NAME=mydb + depends_on: + - db + ports: + - "8080:8080" + +volumes: + postgres_data: diff --git a/go.mod b/go.mod index 070a1ea..b1a79dd 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,6 @@ require ( github.com/lib/pq v1.10.3 // indirect github.com/mattdamon108/gqlmerge v0.2.3 github.com/mattn/go-isatty v0.0.14 // indirect - github.com/mattn/go-sqlite3 v1.14.24 github.com/opentracing/opentracing-go v1.2.0 // indirect github.com/qor/qor v1.2.0 // indirect github.com/qor/validations v0.0.0-20171228122639-f364bca61b46 diff --git a/go.sum b/go.sum index 438d7dd..6ca57fb 100644 --- a/go.sum +++ b/go.sum @@ -100,9 +100,8 @@ github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOA github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y= github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= +github.com/mattn/go-sqlite3 v1.14.0 h1:mLyGNKR8+Vv9CAU7PphKa2hkEqxxhn8i32J6FPj1/QA= github.com/mattn/go-sqlite3 v1.14.0/go.mod h1:JIl7NbARA7phWnGvh0LKTyg7S9BA+6gx71ShQilpsus= -github.com/mattn/go-sqlite3 v1.14.24 h1:tpSp2G2KyMnnQu99ngJ47EIkWVmliIizyZBfPrBWDRM= -github.com/mattn/go-sqlite3 v1.14.24/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/microcosm-cc/bluemonday v1.0.3/go.mod h1:8iwZnFn2CDDNZ0r6UXhF4xawGvzaqzCRa1n3/lO3W2w= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= diff --git a/model/iban.go b/model/iban.go index e110134..b1cb73e 100644 --- a/model/iban.go +++ b/model/iban.go @@ -2,26 +2,27 @@ package model import ( "fmt" - "github.com/jinzhu/gorm" - "golang.org/x/crypto/bcrypt" "strings" "time" + + "github.com/jinzhu/gorm" + "golang.org/x/crypto/bcrypt" ) // Iban : Model with injected fields `ID`, `CreatedAt`, `UpdatedAt` type Iban struct { - IbanID uint `gorm:"primary_key"` - CreatedAt time.Time - UpdatedAt time.Time - DeletedAt *time.Time `sql:"index"` - Text string `gorm:"type:varchar(100);not null"` - Description string - Password string - Handle string `gorm:"type:varchar(20);not null"` - Active bool - IsPrivate bool - OwnerID uint - OwnerType string + IbanID uint `gorm:"primary_key"` + CreatedAt time.Time + UpdatedAt time.Time + DeletedAt *time.Time `sql:"index"` + Text string `gorm:"type:varchar(100);not null"` + Description string + Password string + Handle string `gorm:"type:varchar(20);not null"` + Active bool + IsPrivate bool + OwnerID uint + OwnerType string } // HashPassword : hashing the password @@ -39,17 +40,13 @@ func (iban *Iban) HashPassword() { func (iban *Iban) ComparePassword(password string) bool { err := bcrypt.CompareHashAndPassword([]byte(iban.Password), []byte(password)) - if err != nil { - return false - } - - return true + return err == nil } // Check Handle before create or update = must be add as index to db func (iban *Iban) CheckHandle(tx *gorm.DB) (exist bool) { var ibans []Iban - tx.Where("owner_id = ? AND handle = ?",iban.OwnerID,iban.Handle).Find(&ibans) + tx.Where("owner_id = ? AND handle = ?", iban.OwnerID, iban.Handle).Find(&ibans) for _, tmp := range ibans { if iban.Handle == tmp.Handle && iban.IbanID != tmp.IbanID { exist = true @@ -59,19 +56,19 @@ func (iban *Iban) CheckHandle(tx *gorm.DB) (exist bool) { } // BeforeSave Callback -func (iban *Iban) BeforeSave(tx *gorm.DB) (err error) { +func (iban *Iban) BeforeSave(tx *gorm.DB) (err error) { if iban.CheckHandle(tx) { err = fmt.Errorf("handle already exist") } return } -func (iban *Iban) Validate(db *gorm.DB) { +func (iban *Iban) Validate(db *gorm.DB) { if strings.TrimSpace(iban.Text) == "" { db.AddError(fmt.Errorf("you have to provide IBAN")) - }else if strings.TrimSpace(iban.Handle) == "" { + } else if strings.TrimSpace(iban.Handle) == "" { db.AddError(fmt.Errorf("you have to provide handle")) - }else if iban.IsPrivate && strings.TrimSpace(iban.Password) == "" { + } else if iban.IsPrivate && strings.TrimSpace(iban.Password) == "" { db.AddError(fmt.Errorf("you have to provide password")) } -} \ No newline at end of file +} diff --git a/model/user.go b/model/user.go index accc3b8..6b4d8ac 100644 --- a/model/user.go +++ b/model/user.go @@ -15,13 +15,13 @@ type User struct { CreatedAt time.Time UpdatedAt time.Time DeletedAt *time.Time `sql:"index"` - Email string `gorm:"type:varchar(100);not null"` - Password string `gorm:"not null"` - Handle string `gorm:"not null;unique"` - FirstName string `gorm:"type:varchar(50);not null"` - LastName string `gorm:"type:varchar(50);not null"` - Bio string `gorm:"type:text"` - Visible bool // visible email address + Email string `gorm:"type:varchar(100);not null"` + Password string `gorm:"not null"` + Handle string `gorm:"not null;unique"` + FirstName string `gorm:"type:varchar(50);not null"` + LastName string `gorm:"type:varchar(50);not null"` + Bio string `gorm:"type:text"` + Visible bool // visible email address Avatar string Verified bool Active bool @@ -44,9 +44,6 @@ func (user *User) HashPassword() { func (user *User) ComparePassword(password string) bool { err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)) - if err != nil { - return false - } + return err == nil - return true } From 30d3328c78cc5e23000ddce22b618a1d17b5b68c Mon Sep 17 00:00:00 2001 From: Fbulkaya Date: Tue, 25 Feb 2025 11:40:52 +0300 Subject: [PATCH 2/3] Fix DB connection and update Docker setup --- .DS_Store | Bin 10244 -> 10244 bytes Dockerfile | 21 ++++++++++++++++++--- config/application.example.yml | 4 ---- config/database.example.yml | 5 ----- config/db.go | 15 +++++++++------ config/smtp.example.yml | 5 ----- docker-compose.yml | 7 ++++--- main.go | 12 ++++++++++-- 8 files changed, 41 insertions(+), 28 deletions(-) delete mode 100644 config/application.example.yml delete mode 100644 config/database.example.yml delete mode 100644 config/smtp.example.yml diff --git a/.DS_Store b/.DS_Store index 0c4401cdc5a522c8f4043cccadeb994ba2b46bb3..28bdaf6ae3a5990a3ff525b223b7f75c818339df 100644 GIT binary patch delta 356 zcmZn(XbG6$pKU^hRb{$w73UUz1OWQJUZ6wjRex;cpq+znDI1Qg2$x;dL6m7$117wr06h612i zF@tIroSQx^%nO)%*%jAbb Ld7EE}Ol1N9hyPl_ delta 63 zcmZn(XbG6$jIU^hRb_GBJ`-pQ{8OeWiipA}?cNMT4S3ogpb$>> New request:", c.Request.Method, c.Request.URL.Path) + c.Next() + }) router.Use(gin.Logger()) router.LoadHTMLGlob("templates/*.tmpl.html") @@ -42,7 +46,11 @@ func main() { log.Fatal("JWT Error:" + err.Error()) } - router.POST("/api/login", authMiddleware.LoginHandler) + router.POST("/api/login", func(c *gin.Context) { + fmt.Println(">>> /api/login endpoint called") // Log ekleyelim + authMiddleware.LoginHandler(c) + }) + auth := router.Group("/auth") auth.GET("/refresh_token", authMiddleware.RefreshHandler) From 9ea4eff1cd8aef30cc3790e7d8ec24f3759fa825 Mon Sep 17 00:00:00 2001 From: Fbulkaya Date: Fri, 7 Mar 2025 11:32:29 +0300 Subject: [PATCH 3/3] Updated Go version to 1.23 in Dockerfile --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 120abd1..c281e40 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,5 @@ # Builder Stage -FROM golang:1.20 as builder +FROM golang:1.23 as builder WORKDIR /usr/app