aboutsummaryrefslogtreecommitdiff
path: root/internal/webui/login.go
blob: cc48275e9953049da5b266891e6f3c2cde14bce2 (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
package webui

import (
	"fmt"
	"html/template"
	"net/http"
	"regexp"

	"git.adyxax.org/adyxax/trains/pkg/database"
	"git.adyxax.org/adyxax/trains/pkg/model"
)

const sessionCookieName = "session-trains-webui"

var validUsername = regexp.MustCompile(`^[a-zA-Z]\w*$`)
var validPassword = regexp.MustCompile(`^.+$`)

var loginTemplate = template.Must(template.ParseFS(templatesFS, "html/base.html", "html/login.html"))

type LoginPage struct{} // no variables to pass for now, but a previous error message would be good

// The login handler of the webui
func loginHandler(e *env, w http.ResponseWriter, r *http.Request) error {
	if r.URL.Path == "/login" {
		_, err := tryAndResumeSession(e, r)
		if err == nil {
			// already logged in
			http.Redirect(w, r, "/", http.StatusFound) // TODO fail some other way, at least check if username parameter matches the logged in user
			return nil
		}
		switch r.Method {
		case http.MethodPost:
			r.ParseForm()
			// username
			username, ok := r.Form["username"]
			if !ok {
				return newStatusError(http.StatusBadRequest, fmt.Errorf("No username field in POST"))
			}
			if len(username) != 1 {
				return newStatusError(http.StatusBadRequest, fmt.Errorf("Invalid multiple username fields in POST"))
			}
			if ok := validUsername.MatchString(username[0]); !ok {
				return newStatusError(http.StatusBadRequest, fmt.Errorf("Invalid username field in POST"))
			}
			// password
			password, ok := r.Form["password"]
			if !ok {
				return newStatusError(http.StatusBadRequest, fmt.Errorf("No password field in POST"))
			}
			if len(password) != 1 {
				return newStatusError(http.StatusBadRequest, fmt.Errorf("Invalid multiple password fields in POST"))
			}
			if ok := validPassword.MatchString(password[0]); !ok {
				return newStatusError(http.StatusBadRequest, fmt.Errorf("Invalid password field in POST"))
			}
			// try to login
			user, err := e.dbEnv.Login(&model.UserLogin{Username: username[0], Password: password[0]})
			if err != nil {
				switch e := err.(type) {
				case database.PasswordError:
					// TODO log error
					return e
				case database.QueryError:
					// TODO log error
					return e
				default:
					// TODO log error
					return e
				}
				// TODO display login form with error
			}
			token, err := e.dbEnv.CreateSession(user)
			if err != nil {
				return newStatusError(http.StatusInternalServerError, err)
			}
			cookie := http.Cookie{Name: sessionCookieName, Value: *token, Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: 3600000}
			http.SetCookie(w, &cookie)
			http.Redirect(w, r, "/", http.StatusFound)
			return nil
		case http.MethodGet:
			p := LoginPage{}
			err := loginTemplate.ExecuteTemplate(w, "login.html", p)
			if err != nil {
				return newStatusError(http.StatusInternalServerError, err)
			}
			return nil
		default:
			return newStatusError(http.StatusMethodNotAllowed, fmt.Errorf(http.StatusText(http.StatusMethodNotAllowed)))
		}
	} else {
		return newStatusError(http.StatusNotFound, fmt.Errorf("Invalid path in loginHandler"))
	}
}