package main
import (
"encoding/gob"
"log"
"net/http"
"tixe/api"
"tixe/auth"
"tixe/config"
"tixe/db"
"tixe/handlers"
"tixe/middlewares"
"tixe/template"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
)
func ping(c *gin.Context) {
c.String(http.StatusOK, "pong")
}
func root(c *gin.Context) {
session := sessions.Default(c)
profile := session.Get("profile")
html := template.TmplEngine.Render("index.tmpl", map[string]interface{}{"title": "tixë", "profile": profile})
c.Data(http.StatusOK, "text/html", html)
}
func handleNoRoute(c *gin.Context) {
session := sessions.Default(c)
profile := session.Get("profile")
html := template.TmplEngine.Render("404.tmpl", map[string]interface{}{"profile": profile})
c.Data(http.StatusNotFound, "text/html", html)
}
func setupRouter(auth *auth.Auth) *gin.Engine {
r := gin.Default()
r.Static("/static", "./static")
gob.Register(map[string]interface{}{})
store := cookie.NewStore([]byte(config.TixeConfig.CookieSecret))
r.Use(sessions.Sessions("auth-session", store))
r.NoRoute(handleNoRoute)
r.GET("/login", middlewares.CanLogin, handlers.Login)
authRoute := r.Group("/auth")
{
authRoute.GET("/login", handlers.AuthLogin(auth))
authRoute.GET("/", handlers.AuthCallback(auth))
authRoute.GET("/logout", handlers.AuthLogout)
}
reqAuth := r.Group("/")
reqAuth.Use(middlewares.IsAuthenticated)
{
reqAuth.GET("/", root)
apiRoute := reqAuth.Group("/api")
{
apiRoute.GET("/", api.Root)
apiRoute.GET("/ping", ping)
// internal auth route
iauth := apiRoute.Group("/iauth")
{
iauth.POST("/login", api.PostInternalLogin)
}
}
}
return r
}
func main() {
log.Print("[tixe] Starting up...")
config.ParseConfig()
db.NewPgPool()
defer db.PgPool.Close()
db.RunMigrations()
err := template.NewTemplateEngine()
if err != nil {
log.Fatalf("[tixe] Creating a new TemplateEngine failed, '%s'", err)
}
auth, err := auth.NewAuth()
if err != nil {
log.Fatalf("[tixe] Creating a new authenticator failed, '%s'", err)
}
r := setupRouter(auth)
r.Run(":8080")
}