Simplify initialization
alex wennerberg alex@alexwennerberg.com
Sun, 25 Oct 2020 20:15:00 -0700
3 files changed,
51 insertions(+),
5 deletions(-)
M
flounder.toml
→
flounder.toml
@@ -7,9 +7,6 @@
# Folder containing subfolders for each user's files FilesDirectory="./files" -# Secure key for Cookie Store TODO remove -CookieStoreKey="12345678123456781234567812345678" - # A wildcard TLS cert TLSCertFile="./server.crt" TLSKeyFile="./server.key"
M
main.go
→
main.go
@@ -1,9 +1,11 @@
package main import ( + "crypto/rand" "database/sql" "flag" "github.com/gorilla/sessions" + "io" "io/ioutil" "log" "os"@@ -90,6 +92,51 @@ }
return result, nil } +func createTablesIfDNE() { + _, err := DB.Exec(`CREATE TABLE IF NOT EXISTS user ( + id INTEGER PRIMARY KEY NOT NULL, + username TEXT NOT NULL UNIQUE, + email TEXT NOT NULL UNIQUE, + password_hash TEXT NOT NULL, + approved boolean NOT NULL DEFAULT false, + created_at INTEGER DEFAULT (strftime('%s', 'now')) +); + +CREATE TABLE IF NOT EXISTS cookie_key ( + value TEXT NOT NULL +);`) + if err != nil { + log.Fatal(err) + } +} + +// Generate a cryptographically secure key for the cookie store +func generateCookieKeyIfDNE() []byte { + rows, err := DB.Query("SELECT value FROM cookie_key LIMIT 1") + if err != nil { + log.Fatal(err) + } + if rows.Next() { + var cookie []byte + err := rows.Scan(&cookie) + if err != nil { + log.Fatal(err) + } + return cookie + } else { + k := make([]byte, 32) + _, err := io.ReadFull(rand.Reader, k) + if err != nil { + log.Fatal(err) + } + _, err = DB.Exec("insert into cookie_key values ($1)", k) + if err != nil { + log.Fatal(err) + } + return k + } +} + func main() { configPath := flag.String("c", "flounder.toml", "path to config file") var err error@@ -106,13 +153,14 @@ log.Println("Keyfile or certfile does not exist.")
} // Generate session cookie key if does not exist - - SessionStore = sessions.NewCookieStore([]byte(c.CookieStoreKey)) DB, err = sql.Open("sqlite3", c.DBFile) if err != nil { log.Fatal(err) } + createTablesIfDNE() + cookie := generateCookieKeyIfDNE() + SessionStore = sessions.NewCookieStore(cookie) wg := new(sync.WaitGroup) wg.Add(2) go func() {