all repos — auth-boilerplate @ 52392195bbed8dbcca7e080b528a7b8c798682af

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	g = auth.NewAuth(os.Getenv("APP_PEPPER"))
 75	m = loadEmailConfig()
 76
 77	os.MkdirAll(dataDir, os.ModePerm)
 78	dbPath := filepath.Join(dataDir, dbName) + "?_pragma=foreign_keys(1)"
 79	db, err = gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
 80	if err != nil {
 81		log.Fatal(err)
 82	}
 83
 84	db.AutoMigrate(&User{})
 85
 86	// Handle routes
 87	http.HandleFunc("GET /", loginRequired(examplePage))
 88	http.HandleFunc("GET /register", getRegisterHandler)
 89	http.HandleFunc("GET /login", getLoginHandler)
 90	http.HandleFunc("GET /reset-password", getResetPasswordHandler)
 91	http.HandleFunc("GET /reset-password-confirm", getResetPasswordConfirmHandler)
 92	http.HandleFunc("GET /logout", logoutHandler)
 93
 94	http.HandleFunc("POST /login", postLoginHandler)
 95	http.HandleFunc("POST /register", postRegisterHandler)
 96	http.HandleFunc("POST /reset-password", postResetPasswordHandler)
 97	http.HandleFunc("POST /reset-password-confirm", postResetPasswordConfirmHandler)
 98
 99	http.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
100
101	// Start serving
102	log.Println("Port: " + port)
103	log.Println("Server started: " + baseUrl)
104	log.Fatal(http.ListenAndServe(":"+port, nil))
105}