internal/httpd/account.go

6521399c1c78577eb00f1bcf8947c0900b9cb62e
gitbay/internal/httpd/account.go

463 lines · 14767 bytes

  1package httpd
  2
  3import (
  4	"encoding/json"
  5	"fmt"
  6	"io"
  7	"net/http"
  8	"net/url"
  9	"strconv"
 10	"strings"
 11
 12	"gitbay.org/gitbay/internal/control"
 13	"gitbay.org/gitbay/internal/protocol"
 14	"gitbay.org/gitbay/internal/store"
 15)
 16
 17// accountKey is one SSH key as the settings page shows it: enough to
 18// recognise which key this is without printing the whole blob.
 19type accountKey struct {
 20	Fingerprint string
 21	Algo        string
 22	Scope       string
 23	Label       string
 24	LastUsed    string
 25	Expires     string
 26	Confirm     string // the 8 characters after SHA256: — a label can be empty
 27}
 28
 29type accountPGP struct {
 30	Fingerprint string
 31	UIDs        []string
 32	Expired     bool
 33	Revoked     bool
 34	Confirm     string // the fingerprint's first 8 characters
 35}
 36
 37// accountDevice is one registered APNs device as the settings page shows
 38// it. No form of the token reaches the page but the masked column:
 39// removal confirms on the id, which is not device-identifying.
 40type accountDevice struct {
 41	ID    int64
 42	Label string
 43	// Token is rendered by control.ShortToken, the same renderer
 44	// notifications device list uses.
 45	Token      string
 46	LastSeenAt string
 47	Confirm    string // the id as text, typed back to confirm removal
 48}
 49
 50// accountToken is one API token as the settings page shows it: never
 51// the token itself, only what identifies and describes it.
 52type accountToken struct {
 53	Name     string
 54	Scope    string
 55	Created  string
 56	Expires  string // "never" or a formatted timestamp
 57	LastUsed string // "never" or a formatted timestamp
 58}
 59
 60// accountForm renders the account's own settings: keys, addresses, and the
 61// commands for everything that stays on SSH.
 62func (s *Server) accountForm(w http.ResponseWriter, r *http.Request, u store.User) {
 63	s.accountPage(w, r, u)
 64}
 65
 66// accountPage renders the settings page.
 67func (s *Server) accountPage(w http.ResponseWriter, r *http.Request, u store.User) {
 68	s.renderAccount(w, r, u, "")
 69}
 70
 71// renderAccount draws the settings page. tokenShown is a token minted
 72// by the request being answered; it is shown in this response only.
 73func (s *Server) renderAccount(w http.ResponseWriter, r *http.Request, u store.User, tokenShown string) {
 74	var keys []accountKey
 75	if list, err := s.st.ListSSHKeys(u.ID); err == nil {
 76		for _, k := range list {
 77			confirm := prefix8(strings.TrimPrefix(k.Fingerprint, "SHA256:"))
 78			expires := "never"
 79			if k.ExpiresAt != nil {
 80				expires = k.ExpiresAt.UTC().Format("2006-01-02 15:04 UTC")
 81			}
 82			keys = append(keys, accountKey{
 83				Fingerprint: k.Fingerprint, Algo: k.Algo, Scope: k.Scope, Label: k.Label,
 84				LastUsed: k.LastUsedAt, Expires: expires, Confirm: confirm,
 85			})
 86		}
 87	}
 88	var pgp []accountPGP
 89	if list, err := s.st.ListPGPKeys(u.ID); err == nil {
 90		for _, k := range list {
 91			var uids []string
 92			json.Unmarshal([]byte(k.UIDsJSON), &uids)
 93			confirm := prefix8(k.Fingerprint)
 94			pgp = append(pgp, accountPGP{
 95				Fingerprint: k.Fingerprint, UIDs: uids,
 96				Expired: k.ExpiresAt != nil, Revoked: k.RevokedAt != nil, Confirm: confirm,
 97			})
 98		}
 99	}
100	emails, _ := s.st.ListEmails(u.ID)
101
102	var profile control.ProfileOut
103	s.runControlInto(u, []string{"profile", "show"}, &profile)
104	mailOn, _ := s.st.MailEnabled(u.ID)
105	watchOn, _ := s.st.WatchEnabled(u.ID)
106	pushOn, _ := s.st.PushEnabled(u.ID)
107	replyOn, _ := s.st.ReplyEnabled(u.ID)
108	theme, _ := s.st.Theme(u.ID)
109	diffPref, _ := s.st.DiffLayout(u.ID)
110
111	var devices []accountDevice
112	if list, err := s.st.PushDevices(u.ID); err == nil {
113		for _, d := range list {
114			devices = append(devices, accountDevice{ID: d.ID, Label: d.Label,
115				Token: control.ShortToken(d.Token), LastSeenAt: d.LastSeenAt,
116				Confirm: strconv.FormatInt(d.ID, 10)})
117		}
118	}
119
120	var tokens []accountToken
121	if list, err := s.st.ListAPITokens(u.ID); err == nil {
122		for _, tk := range list {
123			expires, lastUsed := "never", "never"
124			if tk.ExpiresAt != nil {
125				expires = tk.ExpiresAt.UTC().Format("2006-01-02 15:04 UTC")
126			}
127			if tk.LastUsedAt != nil {
128				lastUsed = tk.LastUsedAt.UTC().Format("2006-01-02 15:04 UTC")
129			}
130			tokens = append(tokens, accountToken{tk.Name, tk.Scope, tk.CreatedAt, expires, lastUsed})
131		}
132	}
133
134	var sessions []store.WebSession
135	s.runControlInto(u, []string{"web", "sessions", "list"}, &sessions)
136	currentSession := ""
137	if ck, err := r.Cookie(sessionCookie); err == nil {
138		if h := store.HashToken(ck.Value); len(h) >= 12 {
139			currentSession = h[:12]
140		}
141	}
142
143	// The about text is a file. The page points at it rather than editing
144	// it: the repository's own editor already does that job.
145	aboutRepo := u.Username + "/" + control.ProfileRepoName
146	aboutEdit := ""
147	if profile.AboutPath != "" {
148		aboutEdit = "/" + aboutRepo + "/edit/main/" + profile.AboutPath
149	}
150
151	notice := s.takeFlash(w, r)
152	reauth := s.reauthNotice(w, notice, "/settings")
153
154	s.render(w, "account.html", struct {
155		basePage
156		Tab            string // marks the rail's Settings row as current
157		Keys           []accountKey
158		PGP            []accountPGP
159		Emails         []store.Email
160		Profile        control.ProfileOut
161		LinksText      string
162		AboutRepo      string // <user>/.gitbay, which holds the about text
163		AboutEdit      string // the file editor's URL, empty when there is no file yet
164		Host           string
165		Notice         string
166		Message        string
167		MailOn         bool
168		WatchOn        bool
169		PushOn         bool
170		ReplyOn        bool
171		ReplyOffered   bool // the instance reads replies to its mail
172		Devices        []accountDevice
173		ThemeSetting   string // system, light or dark: the form's selected option
174		DiffSetting    string // unified or split: the form's selected option
175		Tokens         []accountToken
176		TokenShown     string // a token minted by this request, shown once
177		Sessions       []store.WebSession
178		CurrentSession string
179		Reauth         bool // Notice is the stale-session refusal: link to sign in
180	}{s.baseFor(u), "account", keys, pgp, emails, profile, profileLinksText(profile.Links),
181		aboutRepo, aboutEdit, s.cfg.SiteHost(),
182		notice, r.URL.Query().Get("m"), mailOn, watchOn, pushOn,
183		replyOn, s.cfg.Mail.Inbound.Enabled, devices, theme, diffPref,
184		tokens, tokenShown, sessions, currentSession, reauth})
185}
186
187// accountExport hands the browser the same bundle `account export`
188// writes. The command is ReadOnly, so a GET is enough; the response is an
189// attachment rather than a page because the bundle is a file to keep.
190func (s *Server) accountExport(w http.ResponseWriter, r *http.Request, u store.User) {
191	out, msg, code := s.runControlCode(u, []string{"account", "export"})
192	if code != protocol.ExitOK {
193		s.setFlash(w, msg)
194		http.Redirect(w, r, "/settings", http.StatusSeeOther)
195		return
196	}
197	w.Header().Set("Content-Type", "application/json")
198	w.Header().Set("X-Content-Type-Options", "nosniff")
199	w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%q", u.Username+".bundle"))
200	io.WriteString(w, out)
201}
202
203// profileLinksText turns a profile's links into the form the textarea
204// shows and reads back: one per line, "label|url" when there is a label
205// and the bare url otherwise.
206func profileLinksText(links []store.ProfileLink) string {
207	lines := make([]string, len(links))
208	for i, l := range links {
209		if l.Label != "" {
210			lines[i] = l.Label + "|" + l.URL
211		} else {
212			lines[i] = l.URL
213		}
214	}
215	return strings.Join(lines, "\n")
216}
217
218// profileLinkArgs turns the textarea back into the --link values profile
219// set expects: one per non-blank line, or a single empty one to clear the
220// list when the field was emptied.
221func profileLinkArgs(raw string) []string {
222	var links []string
223	for _, line := range strings.Split(raw, "\n") {
224		if line = strings.TrimSpace(line); line != "" {
225			links = append(links, line)
226		}
227	}
228	if links == nil {
229		return []string{""}
230	}
231	return links
232}
233
234// accountSubmit routes the account forms to their commands. Keys,
235// addresses and the profile are the whole surface — no secret is accepted
236// over the web.
237func (s *Server) accountSubmit(w http.ResponseWriter, r *http.Request, u store.User) {
238	back := func(msg, note string) {
239		q := ""
240		if note != "" {
241			q = "?m=" + url.QueryEscape(note)
242		}
243		s.setFlash(w, msg)
244		http.Redirect(w, r, "/settings"+q, http.StatusSeeOther)
245	}
246
247	switch r.FormValue("field") {
248	case "key-add":
249		body := strings.TrimSpace(r.FormValue("key"))
250		if body == "" {
251			back("paste a public key in authorized_keys format", "")
252			return
253		}
254		argv := []string{"keys", "add"}
255		if scope := r.FormValue("scope"); scope == "git" {
256			argv = append(argv, "--scope", "git")
257		}
258		if label := strings.TrimSpace(r.FormValue("label")); label != "" {
259			argv = append(argv, "--label", label)
260		}
261		if ttl := strings.TrimSpace(r.FormValue("ttl")); ttl != "" {
262			argv = append(argv, "--ttl", ttl)
263		}
264		if msg, ok := s.runControlStdin(u, argv, body+"\n"); !ok {
265			back(msg, "")
266			return
267		}
268		back("", "key registered")
269	case "session-revoke":
270		id := strings.TrimSpace(r.FormValue("id"))
271		if _, msg, ok := s.runControl(u, []string{"web", "sessions", "revoke", id}); !ok {
272			back(msg, "")
273			return
274		}
275		if ck, err := r.Cookie(sessionCookie); err == nil && strings.HasPrefix(store.HashToken(ck.Value), id) {
276			http.SetCookie(w, s.clearCookie(sessionCookie, sessionSameSite))
277			http.Redirect(w, r, "/", http.StatusSeeOther)
278			return
279		}
280		back("", "browser session ended")
281	case "session-revoke-all":
282		if _, msg, ok := s.runControl(u, []string{"web", "sessions", "revoke", "--all"}); !ok {
283			back(msg, "")
284			return
285		}
286		http.SetCookie(w, s.clearCookie(sessionCookie, sessionSameSite))
287		http.Redirect(w, r, "/", http.StatusSeeOther)
288	case "account-delete":
289		if ok, msg := confirmed(r, u.Username); !ok {
290			back(msg, "")
291			return
292		}
293		if _, msg, ok := s.runControl(u, []string{"account", "delete", "--confirm", u.Username}); !ok {
294			back(msg, "")
295			return
296		}
297		back("", "a deletion link was mailed to your primary address; nothing changes until it is opened")
298	case "key-remove":
299		want := prefix8(strings.TrimPrefix(r.FormValue("fingerprint"), "SHA256:"))
300		if ok, msg := confirmed(r, want); !ok {
301			back(msg, "")
302			return
303		}
304		if _, msg, ok := s.runControl(u, []string{"keys", "remove", r.FormValue("fingerprint")}); !ok {
305			back(msg, "")
306			return
307		}
308		back("", "key removed")
309	case "pgp-add":
310		body := strings.TrimSpace(r.FormValue("key"))
311		if body == "" {
312			back("paste an armored OpenPGP public key", "")
313			return
314		}
315		if msg, ok := s.runControlStdin(u, []string{"pgp", "add"}, body+"\n"); !ok {
316			back(msg, "")
317			return
318		}
319		back("", "PGP key registered")
320	case "pgp-remove":
321		fp := r.FormValue("fingerprint")
322		want := prefix8(fp)
323		if ok, msg := confirmed(r, want); !ok {
324			back(msg, "")
325			return
326		}
327		if _, msg, ok := s.runControl(u, []string{"pgp", "remove", fp}); !ok {
328			back(msg, "")
329			return
330		}
331		back("", "PGP key removed")
332	case "email-add":
333		if _, msg, ok := s.runControl(u, []string{"email", "add", strings.TrimSpace(r.FormValue("address"))}); !ok {
334			back(msg, "")
335			return
336		}
337		back("", "check that inbox for a verification code")
338	case "email-verify":
339		if _, msg, ok := s.runControl(u, []string{"email", "verify", strings.TrimSpace(r.FormValue("code"))}); !ok {
340			back(msg, "")
341			return
342		}
343		back("", "address verified")
344	case "email-remove":
345		address := r.FormValue("address")
346		if ok, msg := confirmed(r, address); !ok {
347			back(msg, "")
348			return
349		}
350		if _, msg, ok := s.runControl(u, []string{"email", "remove", address}); !ok {
351			back(msg, "")
352			return
353		}
354		back("", "address removed")
355	case "email-primary":
356		if _, msg, ok := s.runControl(u, []string{"email", "primary", r.FormValue("address")}); !ok {
357			back(msg, "")
358			return
359		}
360		back("", "primary address changed")
361	case "token-create":
362		name := strings.TrimSpace(r.FormValue("name"))
363		if name == "" {
364			back("name the token", "")
365			return
366		}
367		scope := r.FormValue("scope")
368		if scope != "full" {
369			scope = "read"
370		}
371		argv := []string{"token", "create", "--name", name, "--scope", scope}
372		if ttl := strings.TrimSpace(r.FormValue("ttl")); ttl != "" {
373			argv = append(argv, "--ttl", ttl)
374		}
375		var minted struct {
376			Token string `json:"token"`
377		}
378		if msg, ok := s.runControlInto(u, argv, &minted); !ok {
379			back(msg, "")
380			return
381		}
382		// The token is shown in this response and nowhere else: not in a
383		// redirect, a URL or a cookie, and never stored to be shown later.
384		w.Header().Set("Cache-Control", "no-store")
385		s.renderAccount(w, r, u, minted.Token)
386	case "token-revoke":
387		name := r.FormValue("name")
388		if ok, msg := confirmed(r, name); !ok {
389			back(msg, "")
390			return
391		}
392		if _, msg, ok := s.runControl(u, []string{"token", "revoke", "--", name}); !ok {
393			back(msg, "")
394			return
395		}
396		back("", "token revoked")
397	case "theme":
398		if _, msg, ok := s.runControl(u, []string{"web", "theme", "set", r.FormValue("theme")}); !ok {
399			back(msg, "")
400			return
401		}
402		back("", "colour scheme saved")
403	case "diff-layout":
404		if _, msg, ok := s.runControl(u, []string{"web", "diff", "set", r.FormValue("layout")}); !ok {
405			back(msg, "")
406			return
407		}
408		back("", "diff layout saved")
409	case "notify-mail", "notify-watch", "notify-push", "notify-reply":
410		pref := strings.TrimPrefix(r.FormValue("field"), "notify-")
411		state := "off"
412		if r.FormValue(pref) == "on" {
413			state = "on"
414		}
415		if _, msg, ok := s.runControl(u, []string{"notifications", "settings", pref, state}); !ok {
416			back(msg, "")
417			return
418		}
419		back("", "notification preferences saved")
420	case "device-remove":
421		id := r.FormValue("id")
422		if ok, msg := confirmed(r, id); !ok {
423			back(msg, "")
424			return
425		}
426		if _, msg, ok := s.runControl(u, []string{"notifications", "device", "remove", id}); !ok {
427			back(msg, "")
428			return
429		}
430		back("", "device removed")
431	case "profile":
432		argv := []string{"profile", "set",
433			"--description", r.FormValue("description"),
434			"--website", r.FormValue("website"),
435		}
436		for _, link := range profileLinkArgs(r.FormValue("links")) {
437			argv = append(argv, "--link", link)
438		}
439		if _, msg, ok := s.runControl(u, argv); !ok {
440			back(msg, "")
441			return
442		}
443		back("", "profile updated")
444	case "profile-repo":
445		// The about text is a file. Create the repository that holds it and
446		// commit a starter README, so the file editor has a branch to open.
447		path := u.Username + "/" + control.ProfileRepoName
448		if _, msg, ok := s.runControl(u, []string{"repo", "create", path}); !ok {
449			back(msg, "")
450			return
451		}
452		starter := "# " + u.Username + "\n\nThis is the about text on your profile.\n"
453		if msg, ok := s.runControlStdin(u, []string{"repo", "commit-file", path,
454			control.AboutBase + ".md", "--ref", "main",
455			"--message", "add profile about", "--file", "-"}, starter); !ok {
456			back(msg, "")
457			return
458		}
459		back("", "profile repository created")
460	default:
461		back("unknown form", "")
462	}
463}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form