Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions backend/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
GOOGLE_CLIENT_ID=your_google_client_id_here
GOOGLE_CLIENT_SECRET=your_google_client_secret_here
GITHUB_CLIENT_ID=your_github_client_id_here
GITHUB_CLIENT_SECRET=your_github_client_secret_here
jwtSecretKey=your_jwtsecretkey_here
DB_HOST=your_db_host_here
DB_USER=your_db_user_here
DB_PASSWORD=your_db_password_here
DB_NAME=your_db_name_here
DB_PORT=your_db_port_here
FRONTEND_URL=your_frontend_url_here
# FRONTEND_URL : http://cashwise.com
FRONTEND_URL=your_frontend_url_here
1 change: 1 addition & 0 deletions backend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.vercel
51 changes: 51 additions & 0 deletions backend/api/index.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package handler

import (
"net/http"

// "os"

"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/adaptor"

// jwtware "github.com/gofiber/jwt/v3"

"github.com/long104/SenZen/config"
"github.com/long104/SenZen/middleware"
"github.com/long104/SenZen/routes"
)

// Handler is the main entry point of the application.
func Handler(w http.ResponseWriter, r *http.Request) {
// Set the proper request path in `*fiber.Ctx`
r.RequestURI = r.URL.String()
handler().ServeHTTP(w, r)
}
func handler() http.HandlerFunc {
config.ConnectDatabase()
app := fiber.New()

app.Use(middleware.CORSMiddleware())

app.Get("api/health", func(c *fiber.Ctx) error {
return c.SendString("health check ok")
})

routes.SetupOAuthRoutes(app)
routes.SetupAuthRoutes(app)

// app.Use(jwtware.New(jwtware.Config{
// SigningKey: []byte(os.Getenv("jwtSecretKey")),
// }))

// app.Use("/admin", middleware.checkMiddleware)
// app.Use("/books", AuthRequired)
app.Get("api/validate-token", middleware.ValidateToken)

routes.SetupRoutes(app)

// setupRoutes(app)

// app.Listen(":8080")
return adaptor.FiberApp(app)
}
25 changes: 8 additions & 17 deletions backend/config/config.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
package config

import (
"log"
"fmt"
"os"

// "fmt"
"github.com/joho/godotenv"
// "fmt"
"golang.org/x/oauth2"
"golang.org/x/oauth2/github"
"golang.org/x/oauth2/google"
Expand All @@ -19,14 +18,10 @@ type Config struct {
var AppConfig Config

func GoogleConfig() oauth2.Config {
err := godotenv.Load(".env")
if err != nil {
log.Fatalf("Some error occured. Err: %s", err)
}

AppConfig.GoogleLoginConfig = oauth2.Config{
RedirectURL: "http://localhost:8080/google_callback",
// RedirectURL: "http://localhost:3000/",
// RedirectURL: "http://localhost:8080/google_callback",
// RedirectURL: "https://senzen-backend.vercel.app/google_callback",
RedirectURL: fmt.Sprintf("%s/google_callback", os.Getenv("BACKEND_URL")),
ClientID: os.Getenv("GOOGLE_CLIENT_ID"),
ClientSecret: os.Getenv("GOOGLE_CLIENT_SECRET"),
Scopes: []string{
Expand All @@ -40,14 +35,10 @@ func GoogleConfig() oauth2.Config {
}

func GithubConfig() oauth2.Config {
err := godotenv.Load(".env")
if err != nil {
log.Fatalf("Some error occured. Err: %s", err)
}

AppConfig.GitHubLoginConfig = oauth2.Config{
RedirectURL: "http://localhost:8080/github_callback",
// RedirectURL: "http://localhost:3000/",
// RedirectURL: "http://localhost:8080/github_callback",
// RedirectURL: "https://senzen-backend.vercel.app/google_callback",
RedirectURL: fmt.Sprintf("%s/github_callback", os.Getenv("BACKEND_URL")),
ClientID: os.Getenv("GITHUB_CLIENT_ID"),
// RedirectURL: fmt.Sprintf(
// "https://github.com/login/oauth/authorize?scope=user:repo&client_id=%s&redirect_uri=%s", os.Getenv("GITHUB_CLIENT_ID"), "http://localhost:8080/github_callback"),
Expand Down
15 changes: 7 additions & 8 deletions backend/config/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import (
"os"
"time"

"github.com/long104/CashWise/models" // Adjust this import path to match your project structure
"github.com/long104/SenZen/models" // Adjust this import path to match your project structure
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
Expand All @@ -17,12 +17,11 @@ var DB *gorm.DB

// ConnectDatabase initializes the database connection.
func ConnectDatabase() {

// Set up the DSN and GORM logger
dsn := fmt.Sprintf(
"host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=Asia/Bangkok",
os.Getenv("DB_HOST"), os.Getenv("DB_USER"), os.Getenv("DB_PASSWORD"), os.Getenv("DB_NAME"), os.Getenv("DB_PORT"),
)
// dsn := fmt.Sprintf(
// "host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=Asia/Bangkok",
// os.Getenv("DB_HOST"), os.Getenv("DB_USER"), os.Getenv("DB_PASSWORD"), os.Getenv("DB_NAME"), os.Getenv("DB_PORT"),
// )

newLogger := logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags),
Expand All @@ -33,10 +32,10 @@ func ConnectDatabase() {
},
)

var err error
var err error

// Connect to the database
DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: newLogger})
DB, err = gorm.Open(postgres.Open(os.Getenv("DATABASE_URL")), &gorm.Config{Logger: newLogger})
if err != nil {
log.Fatalf("failed to connect to database: %v", err)
}
Expand Down
34 changes: 22 additions & 12 deletions backend/controllers/auth_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@ import (

"github.com/gofiber/fiber/v2"
"github.com/golang-jwt/jwt/v4"
"github.com/long104/CashWise/config"
"github.com/long104/CashWise/models"
"github.com/long104/SenZen/config"
"github.com/long104/SenZen/models"
"golang.org/x/crypto/bcrypt"
)


func CreateUser(c *fiber.Ctx) error {
user := new(models.User)
if err := c.BodyParser(user); err != nil {
Expand Down Expand Up @@ -71,23 +72,32 @@ func LoginUser(c *fiber.Ctx) error {

// Set cookie
c.Cookie(&fiber.Cookie{
Name: "jwt",
Value: t,
Path: "/",
// Domain: "cashwise.com",
Name: "jwt",
Value: t,
Path: "/",
Expires: time.Now().Add(time.Hour * 72),
// HTTPOnly: true,
// Secure: false,
HTTPOnly: false,
SameSite: "Lax",
// SameSite: "None",
Secure: true,
})

return c.JSON(fiber.Map{"token": t, "message": "success"})
}

// func LogoutUser(c *fiber.Ctx) error {
// // Clear the JWT cookie
// c.ClearCookie("jwt")
// return c.JSON(fiber.Map{"message": "Successfully logged out"})
// }

func LogoutUser(c *fiber.Ctx) error {
// Clear the JWT cookie
c.ClearCookie("jwt")
return c.JSON(fiber.Map{"message": "Successfully logged out"})
c.Cookie(&fiber.Cookie{
Name: "jwt",
Value: "",
Path: "/",
Expires: time.Now().Add(-1 * time.Hour), // Set expiration in the past
HTTPOnly: false,
Secure: true,
})
return c.JSON(fiber.Map{"message": "Successfully logged out"})
}
33 changes: 21 additions & 12 deletions backend/controllers/github.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import (

"github.com/gofiber/fiber/v2"
"github.com/golang-jwt/jwt/v4"
"github.com/long104/CashWise/config"
"github.com/long104/CashWise/models"
"github.com/long104/SenZen/config"
"github.com/long104/SenZen/models"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
Expand All @@ -36,8 +36,7 @@ func GithubCallback(c *fiber.Ctx) error {
Colorful: true, // Enable color
},
)
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=Asia/Bangkok", os.Getenv("DB_HOST"), os.Getenv("DB_USER"), os.Getenv("DB_PASSWORD"), os.Getenv("DB_NAME"), os.Getenv("DB_PORT"))
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: newLogger})
db, err := gorm.Open(postgres.Open(os.Getenv("DATABASE_URL")), &gorm.Config{Logger: newLogger})
if err != nil {
panic("failed to connect to database")
}
Expand Down Expand Up @@ -125,19 +124,29 @@ func GithubCallback(c *fiber.Ctx) error {

// Set cookie
c.Cookie(&fiber.Cookie{
Name: "jwt",
Value: t,
Path: "/",
Domain: "cashwise.com",
Expires: time.Now().Add(time.Hour * 72),
Secure: false,
// HTTPOnly: true,
// Name: "jwt",
// Value: t,
// Path: "/",
// // Domain: "cashwise.com",
// Domain: "https://senzen-frontend.vercel.app",
// Expires: time.Now().Add(time.Hour * 72),
// // Secure: false,
// // HTTPOnly: true,
// HTTPOnly: false,
// SameSite: "Lax",

Name: "jwt",
Value: t,
Path: "/",
Expires: time.Now().Add(time.Hour * 72),
HTTPOnly: false,
SameSite: "Lax",
Secure: true,
})

// return c.SendString(string(userData))
// return c.Redirect("http://localhost:3000/")
// return c.Redirect("http://localhost:3000/home")
return c.Redirect(os.Getenv("FRONEND_URL") + "/home")
// Redirect with token as URL parameter since cookie won't work cross-origin
return c.Redirect(os.Getenv("FRONTEND_URL") + "/home?token=" + t)
}
60 changes: 49 additions & 11 deletions backend/controllers/google.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ import (

"github.com/gofiber/fiber/v2"
"github.com/golang-jwt/jwt/v4"
"github.com/long104/CashWise/config"
"github.com/long104/CashWise/models"
"github.com/long104/SenZen/config"
"github.com/long104/SenZen/models"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
Expand All @@ -36,8 +36,7 @@ func GoogleCallback(c *fiber.Ctx) error {
Colorful: true, // Enable color
},
)
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable TimeZone=Asia/Bangkok", os.Getenv("DB_HOST"), os.Getenv("DB_USER"), os.Getenv("DB_PASSWORD"), os.Getenv("DB_NAME"), os.Getenv("DB_PORT"))
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: newLogger})
db, err := gorm.Open(postgres.Open(os.Getenv("DATABASE_URL")), &gorm.Config{Logger: newLogger})
if err != nil {
panic("failed to connect to database")
}
Expand All @@ -46,7 +45,6 @@ func GoogleCallback(c *fiber.Ctx) error {
if state != "randomstate" {
return c.SendString("States don't Match!!")
}

code := c.Query("code")

googlecon := config.GoogleConfig()
Expand Down Expand Up @@ -102,13 +100,27 @@ func GoogleCallback(c *fiber.Ctx) error {

// Create a new user
db.Create(&models.User{Name: userName, Email: userEmail})
// result := db.Create(&models.User{Name: userName, Email: userEmail})
// if result.Error != nil {
// return c.JSON(map[string]any{
// "Status": http.StatusInternalServerError,
// "Error": result.Error,
// })
// }

var userDatabase models.User

res := db.Where("email = ?", userEmail).First(&userDatabase)

if res.RowsAffected == 0 {
// result := db.Create(&models.User{Name: userName, Email: userEmail})
db.Create(&models.User{Name: userName, Email: userEmail})
// if result.Error != nil {
// return c.JSON(map[string]any{
// "Status": http.StatusInternalServerError,
// "Error": result.Error,
// })
// }
}

appToken := jwt.New(jwt.SigningMethodHS256)
Expand All @@ -119,7 +131,6 @@ func GoogleCallback(c *fiber.Ctx) error {
claims["role"] = "admin"
claims["name"] = userName
claims["email"] = userEmail

// claims["role"] = "memeber"

t, err := appToken.SignedString([]byte(os.Getenv("jwtSecretKey")))
Expand All @@ -129,14 +140,41 @@ func GoogleCallback(c *fiber.Ctx) error {

// Set cookie
c.Cookie(&fiber.Cookie{
Name: "jwt",
Value: t,
Expires: time.Now().Add(time.Hour * 72),
// HTTPOnly: true,
Name: "jwt",
Value: t,
Path: "/",
Expires: time.Now().Add(time.Hour * 72),
HTTPOnly: false,
SameSite: "Lax",
Secure: true, // required for HTTPS
})

// return c.SendString(string(userData))
// return c.Redirect("http://localhost:3000/home")
return c.Redirect(os.Getenv("FRONTEND_URL") + "/home")

fmt.Print("ip is dddddddddddddddddddddddddddddd", c.IP())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if you are not using debugger. At least use a proper log message.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sorry bro

// log.Print("ip is dddddddddddddddddddddddddddddd", c.IP())
// return c.JSON(fiber.Map{
// "message": "Cookie set",
// "token": t,
// })

// Redirect with token as URL parameter since cookie won't work cross-origin
return c.Redirect(os.Getenv("FRONTEND_URL") + "/home?token=" + t)
// return c.Redirect(os.Getenv("FRONTEND_URL") + "/sign-in")
// return c.Type("html").SendString(`
// <!DOCTYPE html>
// <html lang="en">
// <head>
// <meta charset="UTF-8">
// <title>Redirecting...</title>
// </head>
// <body>
// <p>Redirecting to frontend...</p>
// <script>
// window.location.href = "https://frontend.pantorn.me/home";
// </script>
// </body>
// </html>
// `)
}
Loading