aboutsummaryrefslogtreecommitdiff
path: root/web.go
blob: bff8acc408407429704e2afd0c26e3ff3914913f (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
package main

import (
	"crypto/rand"
	"html/template"
	"log"
	"net/http"
	"strings"

	"github.com/gorilla/mux"
	"github.com/gorilla/sessions"
	"golang.org/x/crypto/argon2"

	"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 := make([]byte, 32)
	n, err := rand.Read(session_key)
	if err != nil || n != 32 {
		log.Fatal(err)
	}
	sessionsStore = sessions.NewCookieStore(session_key)

	r := mux.NewRouter()
	r.HandleFunc("/", handleHome)
	r.HandleFunc("/logout", handleLogout)

	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"]
		if ok {
			login_info = &LoginInfo{
				MxId: mxid.(string),
			}
		}
	}

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

	return login_info
}

// ----

type HomeData struct {
	Login    *LoginInfo
	Accounts map[string]*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
	}

	accountsLock.Lock()
	defer accountsLock.Unlock()
	templateHome.Execute(w, &HomeData{
		Login:    login,
		Accounts: registeredAccounts[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
		syncDbAccounts(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

		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 syncDbAccounts(mxid string, key *[32]byte) {
	accountsLock.Lock()
	defer accountsLock.Unlock()

	// 1. Save all accounts that we have
	var accounts map[string]*Account
	if accts, ok := registeredAccounts[mxid]; ok {
		accounts = accts
		for name, acct := range accts {
			var entry DbAccountConfig
			db.Where(&DbAccountConfig{
				MxUserID: mxid,
				Name:     name,
			}).Assign(&DbAccountConfig{
				Protocol: acct.Protocol,
				Config:   encryptAccountConfig(acct.Config, key),
			}).FirstOrCreate(&entry)
		}
	} else {
		accounts = make(map[string]*Account)
		registeredAccounts[mxid] = accounts
	}

	// 2. Load and start missing accounts
	var allAccounts []DbAccountConfig
	db.Where(&DbAccountConfig{MxUserID: mxid}).Find(&allAccounts)
	for _, acct := range allAccounts {
		if _, ok := accounts[acct.Name]; !ok {
			config, err := decryptAccountConfig(acct.Config, key)
			if err != nil {
				ezbrSystemSendf("Could not decrypt stored configuration for account %s", acct.Name)
				continue
			}
			conn := createConnector(acct.Protocol)
			if conn == nil {
				ezbrSystemSendf("Could not create connector for protocol %s", acct.Protocol)
				continue
			}
			account := &Account{
				MatrixUser:  mxid,
				AccountName: acct.Name,
				Protocol:    acct.Protocol,
				Config:      config,
				Conn:        conn,
				JoinedRooms: map[connector.RoomID]bool{},
			}
			conn.SetHandler(account)

			accounts[acct.Name] = account

			go account.connect(config)
		}
	}
}