internal/httpd/account.go
322 lines · 10082 bytes
1package httpd
2
3import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "net/http"
8 "net/url"
9 "strings"
10
11 "gitbay.org/gitbay/internal/control"
12 "gitbay.org/gitbay/internal/protocol"
13 "gitbay.org/gitbay/internal/store"
14)
15
16// accountKey is one SSH key as the settings page shows it: enough to
17// recognise which key this is without printing the whole blob.
18type accountKey struct {
19 Fingerprint string
20 Algo string
21 Scope string
22 Label string
23 Confirm string // the 8 characters after SHA256: — a label can be empty
24}
25
26type accountPGP struct {
27 Fingerprint string
28 UIDs []string
29 Expired bool
30 Revoked bool
31 Confirm string // the fingerprint's first 8 characters
32}
33
34// accountDevice is one registered APNs device as the settings page shows
35// it. Token is truncated to its first 8 characters: the full token is
36// device-identifying and never reaches the page.
37type accountDevice struct {
38 ID int64
39 Label string
40 Token string
41 LastSeenAt string
42 Confirm string // the truncated token, typed back to confirm removal
43}
44
45// accountForm renders the account's own settings: keys, addresses, and the
46// commands for everything that stays on SSH.
47func (s *Server) accountForm(w http.ResponseWriter, r *http.Request, u store.User) {
48 s.accountPage(w, r, u)
49}
50
51// accountPage renders the settings page.
52func (s *Server) accountPage(w http.ResponseWriter, r *http.Request, u store.User) {
53 var keys []accountKey
54 if list, err := s.st.ListSSHKeys(u.ID); err == nil {
55 for _, k := range list {
56 confirm := prefix8(strings.TrimPrefix(k.Fingerprint, "SHA256:"))
57 keys = append(keys, accountKey{Fingerprint: k.Fingerprint, Algo: k.Algo, Scope: k.Scope, Label: k.Label, Confirm: confirm})
58 }
59 }
60 var pgp []accountPGP
61 if list, err := s.st.ListPGPKeys(u.ID); err == nil {
62 for _, k := range list {
63 var uids []string
64 json.Unmarshal([]byte(k.UIDsJSON), &uids)
65 confirm := prefix8(k.Fingerprint)
66 pgp = append(pgp, accountPGP{
67 Fingerprint: k.Fingerprint, UIDs: uids,
68 Expired: k.ExpiresAt != nil, Revoked: k.RevokedAt != nil, Confirm: confirm,
69 })
70 }
71 }
72 emails, _ := s.st.ListEmails(u.ID)
73
74 var profile control.ProfileOut
75 s.runControlInto(u, []string{"profile", "show"}, &profile)
76 mailOn, _ := s.st.MailEnabled(u.ID)
77 watchOn, _ := s.st.WatchEnabled(u.ID)
78 pushOn, _ := s.st.PushEnabled(u.ID)
79 theme, _ := s.st.Theme(u.ID)
80
81 var devices []accountDevice
82 if list, err := s.st.PushDevices(u.ID); err == nil {
83 for _, d := range list {
84 token := prefix8(d.Token)
85 devices = append(devices, accountDevice{ID: d.ID, Label: d.Label, Token: token, LastSeenAt: d.LastSeenAt, Confirm: token})
86 }
87 }
88
89 // The about text is a file. The page points at it rather than editing
90 // it: the repository's own editor already does that job.
91 aboutRepo := u.Username + "/" + control.ProfileRepoName
92 aboutEdit := ""
93 if profile.AboutPath != "" {
94 aboutEdit = "/" + aboutRepo + "/edit/main/" + profile.AboutPath
95 }
96
97 s.render(w, "account.html", struct {
98 basePage
99 Tab string // marks the rail's Settings row as current
100 Keys []accountKey
101 PGP []accountPGP
102 Emails []store.Email
103 Profile control.ProfileOut
104 LinksText string
105 AboutRepo string // <user>/.gitbay, which holds the about text
106 AboutEdit string // the file editor's URL, empty when there is no file yet
107 Host string
108 Notice string
109 Message string
110 MailOn bool
111 WatchOn bool
112 PushOn bool
113 Devices []accountDevice
114 ThemeSetting string // system, light or dark: the form's selected option
115 }{s.baseFor(u), "account", keys, pgp, emails, profile, profileLinksText(profile.Links),
116 aboutRepo, aboutEdit, s.cfg.SiteHost(),
117 s.takeFlash(w, r), r.URL.Query().Get("m"), mailOn, watchOn, pushOn, devices, theme})
118}
119
120// accountExport hands the browser the same bundle `account export`
121// writes. The command is ReadOnly, so a GET is enough; the response is an
122// attachment rather than a page because the bundle is a file to keep.
123func (s *Server) accountExport(w http.ResponseWriter, r *http.Request, u store.User) {
124 out, msg, code := s.runControlCode(u, []string{"account", "export"})
125 if code != protocol.ExitOK {
126 s.setFlash(w, msg)
127 http.Redirect(w, r, "/settings", http.StatusSeeOther)
128 return
129 }
130 w.Header().Set("Content-Type", "application/json")
131 w.Header().Set("X-Content-Type-Options", "nosniff")
132 w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", u.Username+".bundle"))
133 io.WriteString(w, out)
134}
135
136// profileLinksText turns a profile's links into the form the textarea
137// shows and reads back: one per line, "label|url" when there is a label
138// and the bare url otherwise.
139func profileLinksText(links []store.ProfileLink) string {
140 lines := make([]string, len(links))
141 for i, l := range links {
142 if l.Label != "" {
143 lines[i] = l.Label + "|" + l.URL
144 } else {
145 lines[i] = l.URL
146 }
147 }
148 return strings.Join(lines, "\n")
149}
150
151// profileLinkArgs turns the textarea back into the --link values profile
152// set expects: one per non-blank line, or a single empty one to clear the
153// list when the field was emptied.
154func profileLinkArgs(raw string) []string {
155 var links []string
156 for _, line := range strings.Split(raw, "\n") {
157 if line = strings.TrimSpace(line); line != "" {
158 links = append(links, line)
159 }
160 }
161 if links == nil {
162 return []string{""}
163 }
164 return links
165}
166
167// accountSubmit routes the account forms to their commands. Keys,
168// addresses and the profile are the whole surface — no secret is accepted
169// over the web.
170func (s *Server) accountSubmit(w http.ResponseWriter, r *http.Request, u store.User) {
171 back := func(msg, note string) {
172 q := ""
173 if note != "" {
174 q = "?m=" + url.QueryEscape(note)
175 }
176 s.setFlash(w, msg)
177 http.Redirect(w, r, "/settings"+q, http.StatusSeeOther)
178 }
179
180 switch r.FormValue("field") {
181 case "key-add":
182 body := strings.TrimSpace(r.FormValue("key"))
183 if body == "" {
184 back("paste a public key in authorized_keys format", "")
185 return
186 }
187 argv := []string{"keys", "add"}
188 if scope := r.FormValue("scope"); scope == "git" {
189 argv = append(argv, "--scope", "git")
190 }
191 if label := strings.TrimSpace(r.FormValue("label")); label != "" {
192 argv = append(argv, "--label", label)
193 }
194 if msg, ok := s.runControlStdin(u, argv, body+"\n"); !ok {
195 back(msg, "")
196 return
197 }
198 back("", "key registered")
199 case "key-remove":
200 want := prefix8(strings.TrimPrefix(r.FormValue("fingerprint"), "SHA256:"))
201 if ok, msg := confirmed(r, want); !ok {
202 back(msg, "")
203 return
204 }
205 if _, msg, ok := s.runControl(u, []string{"keys", "remove", r.FormValue("fingerprint")}); !ok {
206 back(msg, "")
207 return
208 }
209 back("", "key removed")
210 case "pgp-add":
211 body := strings.TrimSpace(r.FormValue("key"))
212 if body == "" {
213 back("paste an armored OpenPGP public key", "")
214 return
215 }
216 if msg, ok := s.runControlStdin(u, []string{"pgp", "add"}, body+"\n"); !ok {
217 back(msg, "")
218 return
219 }
220 back("", "PGP key registered")
221 case "pgp-remove":
222 fp := r.FormValue("fingerprint")
223 want := prefix8(fp)
224 if ok, msg := confirmed(r, want); !ok {
225 back(msg, "")
226 return
227 }
228 if _, msg, ok := s.runControl(u, []string{"pgp", "remove", fp}); !ok {
229 back(msg, "")
230 return
231 }
232 back("", "PGP key removed")
233 case "email-add":
234 if _, msg, ok := s.runControl(u, []string{"email", "add", strings.TrimSpace(r.FormValue("address"))}); !ok {
235 back(msg, "")
236 return
237 }
238 back("", "check that inbox for a verification code")
239 case "email-verify":
240 if _, msg, ok := s.runControl(u, []string{"email", "verify", strings.TrimSpace(r.FormValue("code"))}); !ok {
241 back(msg, "")
242 return
243 }
244 back("", "address verified")
245 case "email-remove":
246 address := r.FormValue("address")
247 if ok, msg := confirmed(r, address); !ok {
248 back(msg, "")
249 return
250 }
251 if _, msg, ok := s.runControl(u, []string{"email", "remove", address}); !ok {
252 back(msg, "")
253 return
254 }
255 back("", "address removed")
256 case "email-primary":
257 if _, msg, ok := s.runControl(u, []string{"email", "primary", r.FormValue("address")}); !ok {
258 back(msg, "")
259 return
260 }
261 back("", "primary address changed")
262 case "theme":
263 if _, msg, ok := s.runControl(u, []string{"web", "theme", "set", r.FormValue("theme")}); !ok {
264 back(msg, "")
265 return
266 }
267 back("", "colour scheme saved")
268 case "notify-mail", "notify-watch", "notify-push":
269 pref := strings.TrimPrefix(r.FormValue("field"), "notify-")
270 state := "off"
271 if r.FormValue(pref) == "on" {
272 state = "on"
273 }
274 if _, msg, ok := s.runControl(u, []string{"notifications", "settings", pref, state}); !ok {
275 back(msg, "")
276 return
277 }
278 back("", "notification preferences saved")
279 case "device-remove":
280 want := r.FormValue("tokenprefix")
281 if ok, msg := confirmed(r, want); !ok {
282 back(msg, "")
283 return
284 }
285 if _, msg, ok := s.runControl(u, []string{"notifications", "device", "remove", r.FormValue("id")}); !ok {
286 back(msg, "")
287 return
288 }
289 back("", "device removed")
290 case "profile":
291 argv := []string{"profile", "set",
292 "--description", r.FormValue("description"),
293 "--website", r.FormValue("website"),
294 }
295 for _, link := range profileLinkArgs(r.FormValue("links")) {
296 argv = append(argv, "--link", link)
297 }
298 if _, msg, ok := s.runControl(u, argv); !ok {
299 back(msg, "")
300 return
301 }
302 back("", "profile updated")
303 case "profile-repo":
304 // The about text is a file. Create the repository that holds it and
305 // commit a starter README, so the file editor has a branch to open.
306 path := u.Username + "/" + control.ProfileRepoName
307 if _, msg, ok := s.runControl(u, []string{"repo", "create", path}); !ok {
308 back(msg, "")
309 return
310 }
311 starter := "# " + u.Username + "\n\nThis is the about text on your profile.\n"
312 if msg, ok := s.runControlStdin(u, []string{"repo", "commit-file", path,
313 control.AboutBase + ".md", "--ref", "main",
314 "--message", "add profile about", "--file", "-"}, starter); !ok {
315 back(msg, "")
316 return
317 }
318 back("", "profile repository created")
319 default:
320 back("unknown form", "")
321 }
322}