Files
qrank/src/main.go

115 lines
2.4 KiB
Go

package main
import (
"log"
"os"
"strconv"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
// ===================== Globals =====================
var (
db *gorm.DB
baseURL string
cookieDomain string
// Global logger for this package
lg = log.Default()
)
const (
// Default port if APP_PORT is not set
defaultPort = 18765
)
// ===================== Main =====================
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
var err error
err = godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
// Get the listening port
port := os.Getenv("APP_PORT")
if port == "" {
port = strconv.Itoa(defaultPort)
}
// Set the base URL
baseURL = os.Getenv("APP_BASE_URL")
if baseURL == "" {
baseURL = "http://localhost:" + port
}
// Open connection to SQLite
db, err = gorm.Open(sqlite.Open("qrank.db"), &gorm.Config{})
if err != nil {
lg.Fatal("sqlite connect:", err)
}
if err := db.AutoMigrate(&User{}, &Session{}, &LoginToken{}, &Table{}, &Game{}, &GameUser{}); err != nil {
lg.Fatal("migrate:", err)
}
if err := db.SetupJoinTable(&User{}, "Games", &GameUser{}); err != nil {
lg.Fatal("setup jointable:", err)
}
// Create engine
gin.SetMode(gin.ReleaseMode)
r := gin.Default()
store := cookie.NewStore([]byte("secret"))
r.Use(sessions.Sessions("mysession", store))
r.Use(SessionHandlerMiddleware())
// Serve static files from the current directory
r.Static("/assets", "./assets")
// Routes
r.GET("/", getIndex)
r.GET("/login", getLogin)
r.POST("/login", postLogin)
r.GET("/magic", getMagic)
r.GET("/qr/:qrSlug", getQr)
authorized := r.Group("/")
authorized.Use(RequireAuthMiddleware())
{
// Authenticated routes
authorized.GET("/enter", getEnter)
authorized.POST("/enter", postEnter)
// QR-prepped table routes
authorized.GET("/table/:tableSlug", getTable)
authorized.POST("/table/:tableSlug", postTable)
authorized.POST("/table/:tableSlug/reset", postTableReset)
authorized.GET("/history", getHistory)
authorized.GET("/leaderboard", getLeaderboard)
authorized.GET("/user/:userSlug", getUserView)
authorized.GET("/me", getMe)
authorized.POST("/me", postMe)
}
// Start application with port
bind := ":" + port
//lg.Println("Listening on", baseURL)
if err := r.Run(bind); err != nil {
lg.Fatal(err)
}
}