aboutsummaryrefslogtreecommitdiff
path: root/web.go
blob: d50d91c35f9270c336934d37897fd69f053ad8b6 (plain) (blame)
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
package main

import (
	"html/template"
	"net/http"
	"strconv"
	"strings"

	"github.com/gorilla/mux"
	"github.com/gorilla/sessions"
	log "github.com/sirupsen/logrus"
	"golang.org/x/crypto/argon2"
	"golang.org/x/crypto/blake2b"

	"git.deuxfleurs.fr/Deuxfleurs/easybridge/connector"
	"git.deuxfleurs.fr/Deuxfleurs/easybridge/mxlib"
)

const SESSION_NAME = "easybridge_session"

var sessionsStore sessions.Store = nil
var userKeys = map[string]*[32]byte{}

func StartWeb() {
	session_key := blake2b.Sum256([]byte(config.SessionKey))
	sessionsStore = sessions.NewCookieStore(session_key[:])

	r := mux.NewRouter()
	r.HandleFunc("/", handleHome)
	r.HandleFunc("/logout", handleLogout)
	r.HandleFunc("/add/{protocol}", handleAdd)
	r.HandleFunc("/edit/{account}", handleEdit)
	r.HandleFunc("/delete/{account}", handleDelete)

	staticfiles := http.FileServer(http.Dir("static"))
	r.Handle("/static/{file:.*}", http.StripPrefix("/static/", staticfiles))

	log.Printf("Starting web UI HTTP server on %s", config.WebBindAddr)
	go func() {
		err := http.ListenAndServe(config.WebBindAddr, logRequest(r))
		if err != nil {
			log.Fatal("Cannot start http server: ", err)
		}
	}()
}

func logRequest(handler http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		log.Printf("%s %s %s\n", r.RemoteAddr, r.Method, r.URL)
		handler.ServeHTTP(w, r)
	})
}

// ----

type LoginInfo struct {
	MxId string
}

func checkLogin(w http.ResponseWriter, r *http.Request) *LoginInfo {
	var login_info *LoginInfo

	session, err := sessionsStore.Get(r, SESSION_NAME)
	if err == nil {
		mxid, ok := session.Values["login_mxid"].(string)
		user_key, ok2 := session.Values["login_user_key"].([]byte)
		if ok && ok2 {
			if _, had_key := userKeys[mxid]; !had_key && len(user_key) == 32 {
				key := new([32]byte)
				copy(key[:], user_key)
				userKeys[mxid] = key
				LoadDbAccounts(mxid, key)
			}
			login_info = &LoginInfo{
				MxId: mxid,
			}
		}
	}

	if login_info == nil {
		login_info = handleLogin(w, r)
	}

	return login_info
}

// ----

type HomeData struct {
	Login    *LoginInfo
	Accounts []*Account
}

func handleHome(w http.ResponseWriter, r *http.Request) {
	templateHome := template.Must(template.ParseFiles("templates/layout.html", "templates/home.html"))

	login := checkLogin(w, r)
	if login == nil {
		return
	}

	templateHome.Execute(w, &HomeData{
		Login:    login,
		Accounts: ListAccounts(login.MxId),
	})
}

func handleLogout(w http.ResponseWriter, r *http.Request) {
	session, err := sessionsStore.Get(r, SESSION_NAME)
	if err != nil {
		session, _ = sessionsStore.New(r, SESSION_NAME)
	}

	delete(session.Values, "login_mxid")

	err = session.Save(r, w)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	http.Redirect(w, r, "/", http.StatusFound)
}

type LoginFormData struct {
	Username     string
	WrongPass    bool
	ErrorMessage string
	MatrixDomain string
}

func handleLogin(w http.ResponseWriter, r *http.Request) *LoginInfo {
	templateLogin := template.Must(template.ParseFiles("templates/layout.html", "templates/login.html"))

	data := &LoginFormData{
		MatrixDomain: config.MatrixDomain,
	}

	if r.Method == "GET" {
		templateLogin.Execute(w, data)
		return nil
	} else if r.Method == "POST" {
		r.ParseForm()

		username := strings.Join(r.Form["username"], "")
		password := strings.Join(r.Form["password"], "")

		cli := mxlib.NewClient(config.Server, "")
		mxid, err := cli.PasswordLogin(username, password, "EZBRIDGE", "Easybridge")

		if err != nil {
			data.Username = username
			data.ErrorMessage = err.Error()
			templateLogin.Execute(w, data)
			return nil
		}

		key := new([32]byte)
		key_slice := argon2.IDKey([]byte(password), []byte("EZBRIDGE account store"), 3, 64*1024, 4, 32)
		copy(key[:], key_slice)
		userKeys[mxid] = key

		SaveDbAccounts(mxid, key)
		LoadDbAccounts(mxid, key)

		// Successfully logged in, save it to session
		session, err := sessionsStore.Get(r, SESSION_NAME)
		if err != nil {
			session, _ = sessionsStore.New(r, SESSION_NAME)
		}

		session.Values["login_mxid"] = mxid
		session.Values["login_user_key"] = key_slice

		err = session.Save(r, w)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return nil
		}

		return &LoginInfo{
			MxId: mxid,
		}
	} else {
		http.Error(w, "Unsupported method", http.StatusBadRequest)
		return nil
	}
}

// ----

func handleAdd(w http.ResponseWriter, r *http.Request) {
	login := checkLogin(w, r)
	if login == nil {
		return
	}

	protocol := mux.Vars(r)["protocol"]

	configForm(w, r, login, "", protocol, map[string]string{})
}

func handleEdit(w http.ResponseWriter, r *http.Request) {
	login := checkLogin(w, r)
	if login == nil {
		return
	}

	account := mux.Vars(r)["account"]
	acct := FindAccount(login.MxId, account)
	if acct == nil {
		http.Error(w, "No such account", http.StatusNotFound)
		return
	}

	configForm(w, r, login, account, acct.Protocol, acct.Config)
}

type ConfigFormData struct {
	ErrorMessage string

	Name         string
	NameEditable bool
	InvalidName  bool

	Protocol string

	Config map[string]string
	Errors map[string]string
	Schema connector.ConfigSchema
}

func configForm(w http.ResponseWriter, r *http.Request,
	login *LoginInfo, name string, protocol string,
	prevConfig map[string]string) {
	templateConfig := template.Must(template.ParseFiles("templates/layout.html", "templates/config.html"))

	data := &ConfigFormData{
		Name:         name,
		NameEditable: (name == ""),
		Protocol:     protocol,
		Config:       map[string]string{},
		Errors:       map[string]string{},
		Schema:       connector.Protocols[protocol].Schema,
	}
	for k, v := range prevConfig {
		data.Config[k] = v
	}
	for _, sch := range data.Schema {
		if _, ok := data.Config[sch.Name]; !ok && sch.Default != "" {
			data.Config[sch.Name] = sch.Default
		}
	}

	if r.Method == "POST" {
		ok := true
		r.ParseForm()

		if data.NameEditable {
			data.Name = strings.Join(r.Form["name"], "")
			if data.Name == "" {
				ok = false
				data.InvalidName = true
			}
		}

		for _, schema := range data.Schema {
			field := schema.Name
			old_value := data.Config[field]
			data.Config[field] = strings.Join(r.Form[field], "")
			if schema.IsPassword {
				if data.Config[field] == "" {
					data.Config[field] = old_value
				}
			} else if data.Config[field] == "" {
				if schema.Required {
					ok = false
					data.Errors[field] = "This field is required"
				}
			} else if schema.FixedValue != "" {
				if data.Config[field] != schema.FixedValue {
					ok = false
					data.Errors[field] = "This field must be equal to " + schema.FixedValue
				}
			} else if schema.IsBoolean {
				if data.Config[field] != "false" && data.Config[field] != "true" {
					ok = false
					data.Errors[field] = "This field must be 'true' or 'false'"
				}
			} else if schema.IsNumeric {
				_, err := strconv.Atoi(data.Config[field])
				if err != nil {
					ok = false
					data.Errors[field] = "This field must be a valid number"
				}
			}
		}

		if ok {
			var entry DbAccountConfig
			db.Where(&DbAccountConfig{
				MxUserID: login.MxId,
				Name:     data.Name,
			}).Assign(&DbAccountConfig{
				Protocol: protocol,
				Config:   encryptAccountConfig(data.Config, userKeys[login.MxId]),
			}).FirstOrCreate(&entry)

			err := SetAccount(login.MxId, data.Name, protocol, data.Config)
			if err == nil {
				http.Redirect(w, r, "/", http.StatusFound)
				return
			}
			data.ErrorMessage = err.Error()
		}
	}

	templateConfig.Execute(w, data)
}

func handleDelete(w http.ResponseWriter, r *http.Request) {
	templateDelete := template.Must(template.ParseFiles("templates/layout.html", "templates/delete.html"))

	login := checkLogin(w, r)
	if login == nil {
		return
	}

	account := mux.Vars(r)["account"]

	if r.Method == "POST" {
		r.ParseForm()
		del := strings.Join(r.Form["delete"], "")
		if del == "Yes" {
			RemoveAccount(login.MxId, account)
			db.Where(&DbAccountConfig{
				MxUserID: login.MxId,
				Name:     account,
			}).Delete(&DbAccountConfig{})
			http.Redirect(w, r, "/", http.StatusFound)
			return
		}
	}

	templateDelete.Execute(w, account)
}