all repos — auth-boilerplate @ 16d9372b47e836a365f88331d564d1ac0cf8c25f

A simple Go web-app boilerplate.

src/app/init.go (view raw)

  1package app
  2
  3import (
  4	"html/template"
  5	"log"
  6	"net/http"
  7	"os"
  8	"path/filepath"
  9	"strings"
 10	"time"
 11
 12	"github.com/birabittoh/auth-boilerplate/src/auth"
 13	"github.com/birabittoh/auth-boilerplate/src/email"
 14	"github.com/birabittoh/myks"
 15	"github.com/glebarez/sqlite"
 16	"github.com/joho/godotenv"
 17	"gorm.io/gorm"
 18)
 19
 20type key int
 21
 22type User struct {
 23	gorm.Model
 24	Username     string `gorm:"unique"`
 25	Email        string `gorm:"unique"`
 26	PasswordHash string
 27	Salt         string
 28}
 29
 30const (
 31	dataDir = "data"
 32	dbName  = "app.db"
 33)
 34
 35var (
 36	db *gorm.DB
 37	g  *auth.Auth
 38	m  *email.Client
 39
 40	baseUrl             string
 41	port                string
 42	registrationEnabled = true
 43
 44	ks           = myks.New[uint](0)
 45	durationDay  = 24 * time.Hour
 46	durationWeek = 7 * durationDay
 47	templates    = template.Must(template.ParseGlob("templates/*.html"))
 48)
 49
 50const userContextKey key = 0
 51
 52func Main() {
 53	err := godotenv.Load()
 54	if err != nil {
 55		log.Println("Error loading .env file")
 56	}
 57
 58	port = os.Getenv("APP_PORT")
 59	if port == "" {
 60		port = "3000"
 61	}
 62
 63	baseUrl = os.Getenv("APP_BASE_URL")
 64	if baseUrl == "" {
 65		baseUrl = "http://localhost:" + port
 66	}
 67
 68	e := strings.ToLower(os.Getenv("APP_REGISTRATION_ENABLED"))
 69	if e == "false" || e == "0" {
 70		registrationEnabled = false
 71	}
 72
 73	// Init auth and email
 74	m = loadEmailConfig()
 75	g = auth.NewAuth(os.Getenv("APP_PEPPER"), auth.DefaultMaxPasswordLength)
 76	if g == nil {
 77		log.Fatal("Could not init authentication.")
 78	}
 79
 80	os.MkdirAll(dataDir, os.ModePerm)
 81	dbPath := filepath.Join(dataDir, dbName) + "?_pragma=foreign_keys(1)"
 82	db, err = gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
 83	if err != nil {
 84		log.Fatal(err)
 85	}
 86
 87	db.AutoMigrate(&User{})
 88
 89	// Handle routes
 90	http.HandleFunc("GET /", loginRequired(examplePage))
 91	http.HandleFunc("GET /register", getRegisterHandler)
 92	http.HandleFunc("GET /login", getLoginHandler)
 93	http.HandleFunc("GET /reset-password", getResetPasswordHandler)
 94	http.HandleFunc("GET /reset-password-confirm", getResetPasswordConfirmHandler)
 95	http.HandleFunc("GET /logout", logoutHandler)
 96
 97	http.HandleFunc("POST /login", postLoginHandler)
 98	http.HandleFunc("POST /register", postRegisterHandler)
 99	http.HandleFunc("POST /reset-password", postResetPasswordHandler)
100	http.HandleFunc("POST /reset-password-confirm", postResetPasswordConfirmHandler)
101
102	http.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
103
104	// Start serving
105	log.Println("Port: " + port)
106	log.Println("Server started: " + baseUrl)
107	log.Fatal(http.ListenAndServe(":"+port, nil))
108}