Monorepo for Tangled
1package state
2
3import (
4 "net/http"
5
6 "github.com/go-chi/chi/v5"
7)
8
9func (s *State) SwitchAccount(w http.ResponseWriter, r *http.Request) {
10 l := s.logger.With("handler", "SwitchAccount")
11
12 if err := r.ParseForm(); err != nil {
13 l.Error("failed to parse form", "err", err)
14 http.Error(w, "invalid request", http.StatusBadRequest)
15 return
16 }
17
18 did := r.FormValue("did")
19 if did == "" {
20 http.Error(w, "missing did", http.StatusBadRequest)
21 return
22 }
23
24 if err := s.oauth.SwitchAccount(w, r, did); err != nil {
25 l.Error("failed to switch account", "err", err)
26 s.pages.HxRedirect(w, "/login?error=session")
27 return
28 }
29
30 l.Info("switched account", "did", did)
31 s.pages.HxRedirect(w, "/")
32}
33
34func (s *State) RemoveAccount(w http.ResponseWriter, r *http.Request) {
35 l := s.logger.With("handler", "RemoveAccount")
36
37 did := chi.URLParam(r, "did")
38 if did == "" {
39 http.Error(w, "missing did", http.StatusBadRequest)
40 return
41 }
42
43 currentUser := s.oauth.GetMultiAccountUser(r)
44 isCurrentAccount := currentUser != nil && currentUser.Active.Did == did
45
46 var remainingAccounts []string
47 if currentUser != nil {
48 for _, acc := range currentUser.Accounts {
49 if acc.Did != did {
50 remainingAccounts = append(remainingAccounts, acc.Did)
51 }
52 }
53 }
54
55 if err := s.oauth.RemoveAccount(w, r, did); err != nil {
56 l.Error("failed to remove account", "err", err)
57 http.Error(w, "failed to remove account", http.StatusInternalServerError)
58 return
59 }
60
61 l.Info("removed account", "did", did)
62
63 if isCurrentAccount {
64 if len(remainingAccounts) > 0 {
65 nextDid := remainingAccounts[0]
66 if err := s.oauth.SwitchAccount(w, r, nextDid); err != nil {
67 l.Error("failed to switch to next account", "err", err)
68 s.pages.HxRedirect(w, "/login")
69 return
70 }
71 s.pages.HxRefresh(w)
72 return
73 }
74
75 if err := s.oauth.DeleteSession(w, r); err != nil {
76 l.Error("failed to delete session", "err", err)
77 }
78 s.pages.HxRedirect(w, "/login")
79 return
80 }
81
82 s.pages.HxRefresh(w)
83}