all repos — flounder @ a3f617a39458b331e2181c436e00e7f1c01d5506

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
102var domains map[string]string
103
104func refreshDomainMap() error {
105	rows, err := DB.Query(`SELECT domain, username from user WHERE domain != nil`)
106	if err != nil {
107		return err
108	}
109	for rows.Next() {
110		var domain string
111		var username string
112		err = rows.Scan(&domain, &username)
113		if err != nil {
114			return err
115		}
116		domains[domain] = username
117	}
118	return nil
119}
120
121func getUserByName(username string) (*User, error) {
122	var user User
123	row := DB.QueryRow(`SELECT username, email, active, admin, created_at, reference, domain, domain_enabled from user WHERE username = ?`, username)
124	err := row.Scan(&user.Username, &user.Email, &user.Active, &user.Admin, &user.CreatedAt, &user.Reference, &user.Domain, &user.DomainEnabled)
125	if err != nil {
126		return nil, err
127	}
128	return &user, nil
129}
130
131func getUsers() ([]User, error) {
132	rows, err := DB.Query(`SELECT username, email, active, admin, created_at, reference from user ORDER BY created_at DESC`)
133	if err != nil {
134		return nil, err
135	}
136	var users []User
137	for rows.Next() {
138		var user User
139		err = rows.Scan(&user.Username, &user.Email, &user.Active, &user.Admin, &user.CreatedAt, &user.Reference)
140		if err != nil {
141			return nil, err
142		}
143		users = append(users, user)
144	}
145	return users, nil
146}
147
148func getIndexFiles(admin bool) ([]*File, error) { // cache this function
149	result := []*File{}
150	err := filepath.Walk(c.FilesDirectory, func(thepath string, info os.FileInfo, err error) error {
151		if err != nil {
152			log.Printf("Failure accessing a path %q: %v\n", thepath, err)
153			return err // think about
154		}
155		if !admin && info.IsDir() && info.Name() == HiddenFolder {
156			return filepath.SkipDir
157		}
158		// make this do what it should
159		if !info.IsDir() {
160			res := fileFromPath(thepath)
161			result = append(result, &res)
162		}
163		return nil
164	})
165	if err != nil {
166		return nil, err
167	}
168	sort.Slice(result, func(i, j int) bool {
169		return result[i].UpdatedTime.After(result[j].UpdatedTime)
170	})
171	if len(result) > 35 {
172		result = result[:35]
173	}
174	return result, nil
175} // todo clean up paths
176
177func getMyFilesRecursive(p string, creator string) ([]File, error) {
178	result := []File{}
179	files, err := ioutil.ReadDir(p)
180	if err != nil {
181		return nil, err
182	}
183	for _, file := range files {
184		fullPath := path.Join(p, file.Name())
185		f := fileFromPath(fullPath)
186		if file.IsDir() {
187			f.Children, err = getMyFilesRecursive(path.Join(p, file.Name()), creator)
188		}
189		result = append(result, f)
190	}
191	return result, nil
192}
193
194func createTablesIfDNE() {
195	_, err := DB.Exec(`CREATE TABLE IF NOT EXISTS user (
196  id INTEGER PRIMARY KEY NOT NULL,
197  username TEXT NOT NULL UNIQUE,
198  email TEXT NOT NULL UNIQUE,
199  password_hash TEXT NOT NULL,
200  reference TEXT NOT NULL default "",
201  active boolean NOT NULL DEFAULT false,
202  admin boolean NOT NULL DEFAULT false,
203  created_at INTEGER DEFAULT (strftime('%s', 'now')),
204  domain TEXT NOT NULL default "",
205  domain_enabled BOOLEAN NOT NULL DEFAULT false
206);
207
208CREATE TABLE IF NOT EXISTS cookie_key (
209  value TEXT NOT NULL
210);`)
211	if err != nil {
212		log.Fatal(err)
213	}
214}
215
216// Generate a cryptographically secure key for the cookie store
217func generateCookieKeyIfDNE() []byte {
218	rows, err := DB.Query("SELECT value FROM cookie_key LIMIT 1")
219	defer rows.Close()
220	if err != nil {
221		log.Fatal(err)
222	}
223	if rows.Next() {
224		var cookie []byte
225		err := rows.Scan(&cookie)
226		if err != nil {
227			log.Fatal(err)
228		}
229		return cookie
230	} else {
231		k := make([]byte, 32)
232		_, err := io.ReadFull(rand.Reader, k)
233		if err != nil {
234			log.Fatal(err)
235		}
236		_, err = DB.Exec("insert into cookie_key values (?)", k)
237		if err != nil {
238			log.Fatal(err)
239		}
240		return k
241	}
242}