summaryrefslogtreecommitdiff
path: root/controller/app.go
blob: fa213063745a39b86d730e2e5f11e785bd932d74 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package controller

import (
	"embed"
	"html/template"
	"log"
	"net/http"
	"time"

	"drop.janw.name/config"
	"drop.janw.name/storage"
)

//go:embed template/*
var templateFs embed.FS

type App struct {
	storage *storage.Storage
	tmpl    *template.Template
	config  config.Configuration
}

func NewApp(configFilename string) *App {
	return &App{
		storage: storage.NewStorage(),
		tmpl:    template.Must(template.ParseFS(templateFs, "template/*.html")),
		config:  config.Must(config.Open(configFilename)),
	}
}

func (app App) Config() config.Configuration {
	return app.config
}

func (app App) requireAuth(res http.ResponseWriter, req *http.Request) bool {
	username, password, ok := req.BasicAuth()
	if ok && username == app.config.Authentication.Username && password == app.config.Authentication.Password {
		return true
	}

	res.Header().Add("WWW-Authenticate", "Basic realm=\"Authentication Required\", charset=\"UTF-8\"")
	res.WriteHeader(http.StatusUnauthorized)

	return false
}

func (app *App) StartScheduler() {
	log.Println("starting scheduler")

	go func() {
		for true {
			time.Sleep(time.Minute * 78)

			log.Println("running scheduled tasks")
			app.storage.GarbageCollect()
		}
	}()
}