all repos — flounder @ b93b3d7c26305da0995bff88c757eab8d34c2332

A small site builder for the Gemini protocol

http.go (view raw)

  1package main
  2
  3import (
  4	"bytes"
  5	"database/sql"
  6	"fmt"
  7	gmi "git.sr.ht/~adnano/go-gemini"
  8	"github.com/gorilla/handlers"
  9	"github.com/gorilla/sessions"
 10	_ "github.com/mattn/go-sqlite3"
 11	"golang.org/x/crypto/bcrypt"
 12	"html/template"
 13	"io"
 14	"io/ioutil"
 15	"log"
 16	"net/http"
 17	"os"
 18	"path"
 19	"path/filepath"
 20	"strings"
 21	"time"
 22)
 23
 24var t *template.Template
 25var DB *sql.DB
 26var SessionStore *sessions.CookieStore
 27
 28const InternalServerErrorMsg = "500: Internal Server Error"
 29
 30func renderError(w http.ResponseWriter, errorMsg string, statusCode int) {
 31	data := struct {
 32		PageTitle string
 33		ErrorMsg  string
 34	}{"Error!", errorMsg}
 35	err := t.ExecuteTemplate(w, "error.html", data)
 36	if err != nil { // shouldn't happen probably
 37		http.Error(w, errorMsg, statusCode)
 38	}
 39}
 40
 41func rootHandler(w http.ResponseWriter, r *http.Request) {
 42	// serve everything inside static directory
 43	if r.URL.Path != "/" {
 44		fileName := path.Join(c.TemplatesDirectory, "static", filepath.Clean(r.URL.Path))
 45		http.ServeFile(w, r, fileName)
 46		return
 47	}
 48	authd, _, isAdmin := getAuthUser(r)
 49	indexFiles, err := getIndexFiles()
 50	if err != nil {
 51		log.Println(err)
 52		renderError(w, InternalServerErrorMsg, 500)
 53		return
 54	}
 55	allUsers, err := getUsers()
 56	if err != nil {
 57		log.Println(err)
 58		renderError(w, InternalServerErrorMsg, 500)
 59		return
 60	}
 61	data := struct {
 62		Host      string
 63		PageTitle string
 64		Files     []*File
 65		Users     []string
 66		LoggedIn  bool
 67		IsAdmin   bool
 68	}{c.Host, c.SiteTitle, indexFiles, allUsers, authd, isAdmin}
 69	err = t.ExecuteTemplate(w, "index.html", data)
 70	if err != nil {
 71		log.Println(err)
 72		renderError(w, InternalServerErrorMsg, 500)
 73		return
 74	}
 75}
 76
 77func editFileHandler(w http.ResponseWriter, r *http.Request) {
 78	session, _ := SessionStore.Get(r, "cookie-session")
 79	authUser, ok := session.Values["auth_user"].(string)
 80	if !ok {
 81		renderError(w, "Forbidden", 403)
 82		return
 83	}
 84	fileName := filepath.Clean(r.URL.Path[len("/edit/"):])
 85	filePath := path.Join(c.FilesDirectory, authUser, fileName)
 86	if r.Method == "GET" {
 87		err := checkIfValidFile(filePath, nil)
 88		if err != nil {
 89			log.Println(err)
 90			renderError(w, err.Error(), 400)
 91			return
 92		}
 93		f, err := os.OpenFile(filePath, os.O_RDONLY|os.O_CREATE, 0644)
 94		defer f.Close()
 95		fileBytes, err := ioutil.ReadAll(f)
 96		if err != nil {
 97			log.Println(err)
 98			renderError(w, InternalServerErrorMsg, 500)
 99			return
100		}
101		data := struct {
102			FileName  string
103			FileText  string
104			PageTitle string
105		}{fileName, string(fileBytes), c.SiteTitle}
106		err = t.ExecuteTemplate(w, "edit_file.html", data)
107		if err != nil {
108			log.Println(err)
109			renderError(w, InternalServerErrorMsg, 500)
110			return
111		}
112	} else if r.Method == "POST" {
113		// get post body
114		r.ParseForm()
115		fileBytes := []byte(r.Form.Get("file_text"))
116		err := checkIfValidFile(filePath, fileBytes)
117		if err != nil {
118			log.Println(err)
119			renderError(w, err.Error(), 400)
120			return
121		}
122		err = ioutil.WriteFile(filePath, fileBytes, 0644)
123		if err != nil {
124			log.Println(err)
125			renderError(w, InternalServerErrorMsg, 500)
126			return
127		}
128		http.Redirect(w, r, "/my_site", 302)
129	}
130}
131
132func uploadFilesHandler(w http.ResponseWriter, r *http.Request) {
133	if r.Method == "POST" {
134		session, _ := SessionStore.Get(r, "cookie-session")
135		authUser, ok := session.Values["auth_user"].(string)
136		if !ok {
137			renderError(w, "Forbidden", 403)
138			return
139		}
140		r.ParseMultipartForm(10 << 6) // why does this not work
141		file, fileHeader, err := r.FormFile("file")
142		fileName := filepath.Clean(fileHeader.Filename)
143		defer file.Close()
144		if err != nil {
145			log.Println(err)
146			renderError(w, err.Error(), 400)
147			return
148		}
149		dest, _ := ioutil.ReadAll(file)
150		err = checkIfValidFile(fileName, dest)
151		if err != nil {
152			log.Println(err)
153			renderError(w, err.Error(), 400)
154			return
155		}
156		destPath := path.Join(c.FilesDirectory, authUser, fileName)
157
158		f, err := os.OpenFile(destPath, os.O_WRONLY|os.O_CREATE, 0644)
159		if err != nil {
160			log.Println(err)
161			renderError(w, InternalServerErrorMsg, 500)
162			return
163		}
164		defer f.Close()
165		io.Copy(f, bytes.NewReader(dest))
166	}
167	http.Redirect(w, r, "/my_site", 302)
168}
169
170// bool whether auth'd, string is auth user
171func getAuthUser(r *http.Request) (bool, string, bool) {
172	session, _ := SessionStore.Get(r, "cookie-session")
173	user, ok := session.Values["auth_user"].(string)
174	isAdmin, _ := session.Values["admin"].(bool)
175	return ok, user, isAdmin
176}
177func deleteFileHandler(w http.ResponseWriter, r *http.Request) {
178	authd, authUser, _ := getAuthUser(r)
179	if !authd {
180		renderError(w, "Forbidden", 403)
181		return
182	}
183	fileName := filepath.Clean(r.URL.Path[len("/delete/"):])
184	filePath := path.Join(c.FilesDirectory, authUser, fileName)
185	if r.Method == "POST" {
186		os.Remove(filePath) // suppress error
187	}
188	http.Redirect(w, r, "/my_site", 302)
189}
190
191func mySiteHandler(w http.ResponseWriter, r *http.Request) {
192	authd, authUser, _ := getAuthUser(r)
193	if !authd {
194		renderError(w, "Forbidden", 403)
195		return
196	}
197	// check auth
198	files, _ := getUserFiles(authUser)
199	data := struct {
200		Host      string
201		PageTitle string
202		AuthUser  string
203		Files     []*File
204		LoggedIn  bool
205	}{c.Host, c.SiteTitle, authUser, files, authd}
206	_ = t.ExecuteTemplate(w, "my_site.html", data)
207}
208
209func loginHandler(w http.ResponseWriter, r *http.Request) {
210	if r.Method == "GET" {
211		// show page
212		data := struct {
213			Error     string
214			PageTitle string
215		}{"", "Login"}
216		err := t.ExecuteTemplate(w, "login.html", data)
217		if err != nil {
218			log.Println(err)
219			renderError(w, InternalServerErrorMsg, 500)
220			return
221		}
222	} else if r.Method == "POST" {
223		r.ParseForm()
224		name := r.Form.Get("username")
225		password := r.Form.Get("password")
226		row := DB.QueryRow("SELECT password_hash, active, admin FROM user where username = $1", name)
227		var db_password []byte
228		var active bool
229		var isAdmin bool
230		_ = row.Scan(&db_password, &active, &isAdmin)
231		if db_password != nil && !active {
232			data := struct {
233				Error     string
234				PageTitle string
235			}{"Your account is not active yet. Pending admin approval", c.SiteTitle}
236			t.ExecuteTemplate(w, "login.html", data)
237			return
238		}
239		if bcrypt.CompareHashAndPassword(db_password, []byte(password)) == nil {
240			log.Println("logged in")
241			session, _ := SessionStore.Get(r, "cookie-session")
242			session.Values["auth_user"] = name
243			session.Values["admin"] = isAdmin
244			session.Save(r, w)
245			http.Redirect(w, r, "/my_site", 302)
246		} else {
247			data := struct {
248				Error     string
249				PageTitle string
250			}{"Invalid login or password", c.SiteTitle}
251			err := t.ExecuteTemplate(w, "login.html", data)
252			if err != nil {
253				log.Println(err)
254				renderError(w, InternalServerErrorMsg, 500)
255				return
256			}
257		}
258	}
259}
260
261func logoutHandler(w http.ResponseWriter, r *http.Request) {
262	session, _ := SessionStore.Get(r, "cookie-session")
263	session.Options.MaxAge = -1
264	session.Save(r, w)
265	http.Redirect(w, r, "/", 302)
266}
267
268const ok = "-0123456789abcdefghijklmnopqrstuvwxyz"
269
270func isOkUsername(s string) bool {
271	if len(s) < 1 {
272		return false
273	}
274	if len(s) > 31 {
275		return false
276	}
277	for _, char := range s {
278		if !strings.Contains(ok, strings.ToLower(string(char))) {
279			return false
280		}
281	}
282	return true
283}
284func registerHandler(w http.ResponseWriter, r *http.Request) {
285	if r.Method == "GET" {
286		data := struct {
287			Host      string
288			Errors    []string
289			PageTitle string
290		}{c.Host, nil, "Register"}
291		err := t.ExecuteTemplate(w, "register.html", data)
292		if err != nil {
293			log.Println(err)
294			renderError(w, InternalServerErrorMsg, 500)
295			return
296		}
297	} else if r.Method == "POST" {
298		r.ParseForm()
299		email := r.Form.Get("email")
300		password := r.Form.Get("password")
301		errors := []string{}
302		if !strings.Contains(email, "@") {
303			errors = append(errors, "Invalid Email")
304		}
305		if r.Form.Get("password") != r.Form.Get("password2") {
306			errors = append(errors, "Passwords don't match")
307		}
308		if len(password) < 6 {
309			errors = append(errors, "Password is too short")
310		}
311		username := strings.ToLower(r.Form.Get("username"))
312		if !isOkUsername(username) {
313			errors = append(errors, "Username is invalid: can only contain letters, numbers and hypens. Maximum 32 characters.")
314		}
315		hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), 8) // TODO handle error
316		if len(errors) == 0 {
317			_, err = DB.Exec("insert into user (username, email, password_hash) values ($1, $2, $3)", username, email, string(hashedPassword))
318			if err != nil {
319				log.Println(err)
320				errors = append(errors, "Username or email is already used")
321			}
322		}
323		if len(errors) > 0 {
324			data := struct {
325				Host      string
326				Errors    []string
327				PageTitle string
328			}{c.Host, errors, "Register"}
329			t.ExecuteTemplate(w, "register.html", data)
330		} else {
331			data := struct {
332				Host      string
333				Message   string
334				PageTitle string
335			}{c.Host, "Registration complete! The server admin will approve your request before you can log in.", "Registration Complete"}
336			t.ExecuteTemplate(w, "message.html", data)
337		}
338	}
339}
340
341type User struct {
342}
343
344func adminHandler(w http.ResponseWriter, r *http.Request) {
345	_, _, isAdmin := getAuthUser(r)
346	if !isAdmin {
347		renderError(w, "Forbidden", 403)
348		return
349	}
350	// LIST USERS
351	data := struct {
352		users     []User
353		LoggedIn  bool
354		IsAdmin   bool
355		PageTitle string
356	}{[]User{}, true, true, "admin"}
357	t.ExecuteTemplate(w, "admin.html", data)
358}
359
360// Server a user's file
361func userFile(w http.ResponseWriter, r *http.Request) {
362	userName := strings.Split(r.Host, ".")[0]
363	p := filepath.Clean(r.URL.Path)
364	if p == "/" {
365		p = "index.gmi"
366	}
367	fileName := path.Join(c.FilesDirectory, userName, p)
368	extension := path.Ext(fileName)
369	if r.URL.Path == "/style.css" {
370		http.ServeFile(w, r, path.Join(c.TemplatesDirectory, "static/style.css"))
371	}
372	query := r.URL.Query()
373	_, raw := query["raw"]
374	if !raw && (extension == ".gmi" || extension == ".gemini") {
375		_, err := os.Stat(fileName)
376		if err != nil {
377			renderError(w, "404: file not found", 404)
378			return
379		}
380		file, _ := os.Open(fileName)
381
382		htmlString := textToHTML(gmi.Parse(file))
383		data := struct {
384			SiteBody  template.HTML
385			PageTitle string
386		}{template.HTML(htmlString), userName}
387		t.ExecuteTemplate(w, "user_page.html", data)
388	} else {
389		http.ServeFile(w, r, fileName)
390	}
391}
392
393func runHTTPServer() {
394	log.Printf("Running http server with hostname %s on port %d. TLS enabled: %t", c.Host, c.HttpPort, c.HttpsEnabled)
395	var err error
396	t, err = template.ParseGlob(path.Join(c.TemplatesDirectory, "*.html"))
397	if err != nil {
398		log.Fatal(err)
399	}
400	serveMux := http.NewServeMux()
401
402	s := strings.SplitN(c.Host, ":", 2)
403	hostname := s[0]
404	port := c.HttpPort
405
406	serveMux.HandleFunc(hostname+"/", rootHandler)
407	serveMux.HandleFunc(hostname+"/my_site", mySiteHandler)
408	serveMux.HandleFunc(hostname+"/admin", adminHandler)
409	serveMux.HandleFunc(hostname+"/edit/", editFileHandler)
410	serveMux.HandleFunc(hostname+"/upload", uploadFilesHandler)
411	serveMux.HandleFunc(hostname+"/login", loginHandler)
412	serveMux.HandleFunc(hostname+"/logout", logoutHandler)
413	serveMux.HandleFunc(hostname+"/register", registerHandler)
414	serveMux.HandleFunc(hostname+"/delete/", deleteFileHandler)
415
416	// TODO rate limit login https://github.com/ulule/limiter
417
418	wrapped := handlers.LoggingHandler(log.Writer(), serveMux)
419
420	// handle user files based on subdomain
421	serveMux.HandleFunc("/", userFile)
422	// login+register functions
423	srv := &http.Server{
424		ReadTimeout:  5 * time.Second,
425		WriteTimeout: 10 * time.Second,
426		IdleTimeout:  120 * time.Second,
427		Addr:         fmt.Sprintf(":%d", port),
428		// TLSConfig:    tlsConfig,
429		Handler: wrapped,
430	}
431	if c.HttpsEnabled {
432		log.Fatal(srv.ListenAndServeTLS(c.TLSCertFile, c.TLSKeyFile))
433	} else {
434		log.Fatal(srv.ListenAndServe())
435	}
436}