all repos — flounder @ 858ec21770c0e2d0b25fc302688fbde9bb24d9f1

A small site builder for the Gemini protocol

db.go (view raw)

  1package main
  2
  3import (
  4	"crypto/rand"
  5	"database/sql"
  6	"io"
  7	"io/ioutil"
  8	"log"
  9	"os"
 10	"path"
 11	"path/filepath"
 12	"sort"
 13	"time"
 14)
 15
 16var DB *sql.DB
 17
 18func initializeDB() {
 19	var err error
 20	DB, err = sql.Open("sqlite3", c.DBFile)
 21	if err != nil {
 22		log.Fatal(err)
 23	}
 24	createTablesIfDNE()
 25}
 26
 27func getAnalyticsDB() *sql.DB {
 28	db, err := sql.Open("sqlite3", c.AnalyticsDBFile)
 29	_, err = db.Exec(`CREATE TABLE IF NOT EXISTS log (
 30  id INTEGER PRIMARY KEY NOT NULL,
 31  timestamp TEXT NOT NULL,
 32  protocol TEXT NOT NULL,
 33  request_ip TEXT,
 34  request_user TEXT,
 35  status INTEGER,
 36  destination_host TEXT,
 37  path TEXT,
 38  method TEXT,
 39  referer TEXT
 40);`)
 41	if err != nil {
 42		log.Fatal(err)
 43	}
 44	return db
 45}
 46
 47type File struct { // also folders
 48	Creator     string
 49	Name        string // includes folder
 50	UpdatedTime time.Time
 51	TimeAgo     string
 52	IsText      bool
 53	Children    []File
 54	Host        string
 55}
 56
 57func fileFromPath(fullPath string) File {
 58	info, _ := os.Stat(fullPath)
 59	creatorFolder := getCreator(fullPath)
 60	isText := isTextFile(fullPath)
 61	updatedTime := info.ModTime()
 62	return File{
 63		Name:        getLocalPath(fullPath),
 64		Creator:     path.Base(creatorFolder),
 65		UpdatedTime: updatedTime,
 66		IsText:      isText,
 67		TimeAgo:     timeago(&updatedTime),
 68		Host:        c.Host,
 69	}
 70
 71}
 72
 73type User struct {
 74	Username      string
 75	Email         string
 76	Active        bool
 77	Admin         bool
 78	CreatedAt     int // timestamp
 79	Reference     string
 80	Domain        string
 81	DomainEnabled bool
 82}
 83
 84func getActiveUserNames() ([]string, error) {
 85	rows, err := DB.Query(`SELECT username from user WHERE active is true order by username`)
 86	if err != nil {
 87		return nil, err
 88	}
 89	var users []string
 90	for rows.Next() {
 91		var user string
 92		err = rows.Scan(&user)
 93		if err != nil {
 94			return nil, err
 95		}
 96		users = append(users, user)
 97	}
 98
 99	return users, nil
100}
101
102func getUserByName(username string) (*User, error) {
103	var user User
104	row := DB.QueryRow(`SELECT username, email, active, admin, created_at, reference, domain, domain_enabled from user WHERE username = ?`, username)
105	err := row.Scan(&user.Username, &user.Email, &user.Active, &user.Admin, &user.CreatedAt, &user.Reference, &user.Domain, &user.DomainEnabled)
106	if err != nil {
107		return nil, err
108	}
109	return &user, nil
110}
111
112func getUsers() ([]User, error) {
113	rows, err := DB.Query(`SELECT username, email, active, admin, created_at, reference from user ORDER BY created_at DESC`)
114	if err != nil {
115		return nil, err
116	}
117	var users []User
118	for rows.Next() {
119		var user User
120		err = rows.Scan(&user.Username, &user.Email, &user.Active, &user.Admin, &user.CreatedAt, &user.Reference)
121		if err != nil {
122			return nil, err
123		}
124		users = append(users, user)
125	}
126	return users, nil
127}
128
129func getIndexFiles(admin bool) ([]*File, error) { // cache this function
130	result := []*File{}
131	err := filepath.Walk(c.FilesDirectory, func(thepath string, info os.FileInfo, err error) error {
132		if err != nil {
133			log.Printf("Failure accessing a path %q: %v\n", thepath, err)
134			return err // think about
135		}
136		if !admin && info.IsDir() && info.Name() == HiddenFolder {
137			return filepath.SkipDir
138		}
139		// make this do what it should
140		if !info.IsDir() {
141			res := fileFromPath(thepath)
142			result = append(result, &res)
143		}
144		return nil
145	})
146	if err != nil {
147		return nil, err
148	}
149	sort.Slice(result, func(i, j int) bool {
150		return result[i].UpdatedTime.After(result[j].UpdatedTime)
151	})
152	if len(result) > 35 {
153		result = result[:35]
154	}
155	return result, nil
156} // todo clean up paths
157
158func getMyFilesRecursive(p string, creator string) ([]File, error) {
159	result := []File{}
160	files, err := ioutil.ReadDir(p)
161	if err != nil {
162		return nil, err
163	}
164	for _, file := range files {
165		fullPath := path.Join(p, file.Name())
166		f := fileFromPath(fullPath)
167		if file.IsDir() {
168			f.Children, err = getMyFilesRecursive(path.Join(p, file.Name()), creator)
169		}
170		result = append(result, f)
171	}
172	return result, nil
173}
174
175func createTablesIfDNE() {
176	_, err := DB.Exec(`CREATE TABLE IF NOT EXISTS user (
177  id INTEGER PRIMARY KEY NOT NULL,
178  username TEXT NOT NULL UNIQUE,
179  email TEXT NOT NULL UNIQUE,
180  password_hash TEXT NOT NULL,
181  reference TEXT NOT NULL default "",
182  active boolean NOT NULL DEFAULT false,
183  admin boolean NOT NULL DEFAULT false,
184  created_at INTEGER DEFAULT (strftime('%s', 'now')),
185  domain TEXT NOT NULL default "",
186  domain_enabled BOOLEAN NOT NULL DEFAULT false
187);
188
189CREATE TABLE IF NOT EXISTS cookie_key (
190  value TEXT NOT NULL
191);`)
192	if err != nil {
193		log.Fatal(err)
194	}
195}
196
197// Generate a cryptographically secure key for the cookie store
198func generateCookieKeyIfDNE() []byte {
199	rows, err := DB.Query("SELECT value FROM cookie_key LIMIT 1")
200	defer rows.Close()
201	if err != nil {
202		log.Fatal(err)
203	}
204	if rows.Next() {
205		var cookie []byte
206		err := rows.Scan(&cookie)
207		if err != nil {
208			log.Fatal(err)
209		}
210		return cookie
211	} else {
212		k := make([]byte, 32)
213		_, err := io.ReadFull(rand.Reader, k)
214		if err != nil {
215			log.Fatal(err)
216		}
217		_, err = DB.Exec("insert into cookie_key values (?)", k)
218		if err != nil {
219			log.Fatal(err)
220		}
221		return k
222	}
223}