summaryrefslogtreecommitdiff
path: root/main.go
blob: 6657d4628f1f9234a39285999f8c278111159685 (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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package main

import (
	"bufio"
	_ "embed"
	"fmt"
	"io"
	"net/http"
	"os"
	"path"
	"time"
	"tinygram/internal/secrets"

	"github.com/BurntSushi/toml"
	"github.com/google/uuid"
	"github.com/gorilla/sessions"
	"github.com/labstack/echo-contrib/session"
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
	"github.com/labstack/gommon/log"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

type Post struct {
	CreatedAt   time.Time
	Description string
	ImageID     string
}

type Config struct {
	SessionSecret    string
	DbPath           string
	AssetPath        string
	PasswordFilepath string
}

//go:embed prod.toml.agebox
var prodenv string

//go:embed dev.toml.agebox
var devenv string

var config Config

func main() {
	secret, err := secrets.DecryptSecret(prodenv)
	if err != nil {
		log.Errorf("could not decrypt a secret", err)
		os.Exit(1)
	}

	_, err = toml.Decode(secret, &config)
	if err != nil {
		fmt.Printf("could not parse config %v\n", err)
		os.Exit(1)
	}

	dbPath := config.DbPath
	if dbPath == "" {
		dbPath = "tinygram.db"
	}

	sessionSecret := config.SessionSecret
	if sessionSecret == "" {
		fmt.Println("NEED TO PROVIDE A SECRET")
		os.Exit(1)
	}

	passwordFilePath := config.PasswordFilepath
	if passwordFilePath == "" {
		passwordFilePath = "password.txt"
	}

	assetsPath := config.AssetPath
	if assetsPath == "" {
		assetsPath = "assets"
	}

	swedenTime, _ := time.LoadLocation("Europe/Stockholm")

	e := echo.New()
	e.Use(middleware.Logger())
	e.Use(middleware.Recover())
	e.Use(middleware.Secure())

	e.Use(middleware.CSRFWithConfig(middleware.CSRFConfig{
		TokenLookup: "form:_csrf",
	}))

	e.Use(session.Middleware(sessions.NewCookieStore([]byte(sessionSecret))))

	db, err := gorm.Open(sqlite.Open(dbPath), &gorm.Config{})
	db.Exec("PRAGMA journal_mode=WAL; PRAGMA busy_timeout = 5000;")

	db.AutoMigrate(Post{})

	if err != nil {
		fmt.Printf("opening db: %v", err)
		return
	}

	e.Static("/static", assetsPath)

	e.GET("/", func(c echo.Context) error {
		var posts []Post
		db.Order("created_at DESC").Limit(5).Find(&posts)
		component := index(posts, swedenTime)
		err := component.Render(c.Request().Context(), c.Response().Writer)
		if err != nil {
			return err
		}
		return nil
	})

	e.GET("/login", func(c echo.Context) error {
		component := loginPage(c.Get(middleware.DefaultCSRFConfig.ContextKey).(string))
		err := component.Render(c.Request().Context(), c.Response().Writer)
		if err != nil {
			return err
		}
		return nil
	})

	e.POST("/login", func(c echo.Context) error {
		// read password file, check content, add session if correct
		file, err := os.Open(passwordFilePath)
		if err != nil {
			c.Response().Header().Set("HX-Redirect", "/")
			return c.NoContent(http.StatusUnauthorized)
		}

		// check provided password against file
		s := bufio.NewScanner(file)
		s.Scan()
		expected := s.Text()
		formPass := c.FormValue("password")

		if expected != formPass {
			c.Response().Header().Set("HX-Redirect", "/")
			return c.NoContent(http.StatusUnauthorized)
		}

		sess, _ := session.Get("session", c)
		sess.Options = &sessions.Options{
			Path:     "/",
			MaxAge:   86400 * 7,
			HttpOnly: true,
		}
		sess.Values["user"] = "admin"
		sess.Save(c.Request(), c.Response())

		c.Response().Header().Set("HX-Redirect", "/upload")
		return c.NoContent(http.StatusOK)
	})

	e.GET("/upload", func(c echo.Context) error {
		sess, _ := session.Get("session", c)
		if sess.Values["user"] != "admin" {
			return c.Redirect(http.StatusSeeOther, "/login")
		}
		component := uploadPage(c.Get(middleware.DefaultCSRFConfig.ContextKey).(string))
		err := component.Render(c.Request().Context(), c.Response().Writer)
		if err != nil {
			return err
		}
		return nil
	})

	e.POST("/upload", func(c echo.Context) error {
		sess, _ := session.Get("session", c)
		if sess.Values["user"] != "admin" {
			return c.Redirect(http.StatusSeeOther, "/login")
		}
		file, err := c.FormFile("file")
		if err != nil {
			return err
		}
		src, err := file.Open()
		if err != nil {
			return err
		}
		defer src.Close()

		filename, err := uuid.NewRandom()
		if err != nil {
			return err
		}

		dst, err := os.Create(path.Join(assetsPath, filename.String())) //RANDOMIZE
		if err != nil {
			return err
		}
		defer dst.Close()

		// Copy
		if _, err = io.Copy(dst, src); err != nil {
			return err
		}

		description := c.FormValue("description")

		post := Post{
			Description: description,
			ImageID:     "/static/" + filename.String(),
		}
		db.Create(&post)

		c.Response().Header().Set("HX-Redirect", "/")
		return c.NoContent(http.StatusOK)
	})

	e.GET("/posts", func(c echo.Context) error {
		after, err := time.Parse(time.RFC3339, c.QueryParam("after"))

		if err != nil {
			return err
		}

		var ps []Post
		db.Order("created_at DESC").Limit(5).Where("created_at < ?", after).Find(&ps)
		component := posts(ps, swedenTime)
		err = component.Render(c.Request().Context(), c.Response().Writer)
		if err != nil {
			return err
		}
		return nil
	})

	e.Logger.Fatal(e.Start(":8080"))
}