src/app/init.go (view raw)
1package app
2
3import (
4 "log"
5 "net/http"
6 "os"
7 "path/filepath"
8 "strings"
9 "time"
10
11 "github.com/birabittoh/auth-boilerplate/src/auth"
12 "github.com/birabittoh/auth-boilerplate/src/email"
13 "github.com/birabittoh/myks"
14 "github.com/glebarez/sqlite"
15 "github.com/joho/godotenv"
16 "github.com/utking/extemplate"
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 xt *extemplate.Extemplate
40
41 baseUrl string
42 port string
43 registrationEnabled = true
44
45 ks = myks.New[uint](0)
46 durationDay = 24 * time.Hour
47 durationWeek = 7 * durationDay
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 // Init template engine
90 xt = extemplate.New()
91 err = xt.ParseDir("templates", []string{".tmpl"})
92 if err != nil {
93 log.Fatal(err)
94 }
95
96 // Handle routes
97 http.HandleFunc("GET /", loginRequired(examplePage))
98 http.HandleFunc("GET /register", getRegisterHandler)
99 http.HandleFunc("GET /login", getLoginHandler)
100 http.HandleFunc("GET /reset-password", getResetPasswordHandler)
101 http.HandleFunc("GET /reset-password-confirm", getResetPasswordConfirmHandler)
102 http.HandleFunc("GET /logout", logoutHandler)
103
104 http.HandleFunc("POST /login", postLoginHandler)
105 http.HandleFunc("POST /register", postRegisterHandler)
106 http.HandleFunc("POST /reset-password", postResetPasswordHandler)
107 http.HandleFunc("POST /reset-password-confirm", postResetPasswordConfirmHandler)
108
109 http.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
110
111 // Start serving
112 log.Println("Port: " + port)
113 log.Println("Server started: " + baseUrl)
114 log.Fatal(http.ListenAndServe(":"+port, nil))
115}