Monorepo for Tangled
tangled.org
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 redirectURL, err := s.oauth.ClientApp.StartAuthFlow(r.Context(), did)
27 if err != nil {
28 l.Error("failed to resume login flow", "err", err)
29 s.pages.HxRedirect(w, "/login?error=session")
30 return
31 }
32 s.pages.HxRedirect(w, redirectURL)
33 return
34 }
35
36 l.Info("switched account", "did", did)
37 if returnUrl := r.FormValue("return_url"); returnUrl != "" {
38 s.pages.HxRedirect(w, returnUrl)
39 } else {
40 s.pages.HxRefresh(w)
41 }
42}
43
44func (s *State) RemoveAccount(w http.ResponseWriter, r *http.Request) {
45 l := s.logger.With("handler", "RemoveAccount")
46
47 did := chi.URLParam(r, "did")
48 if did == "" {
49 http.Error(w, "missing did", http.StatusBadRequest)
50 return
51 }
52
53 currentUser := s.oauth.GetMultiAccountUser(r)
54 isCurrentAccount := currentUser != nil && currentUser.Did == did
55
56 var remainingAccounts []string
57 if currentUser != nil {
58 for _, acc := range currentUser.Accounts {
59 if acc.Did != did {
60 remainingAccounts = append(remainingAccounts, acc.Did)
61 }
62 }
63 }
64
65 if err := s.oauth.RemoveAccount(w, r, did); err != nil {
66 l.Error("failed to remove account", "err", err)
67 http.Error(w, "failed to remove account", http.StatusInternalServerError)
68 return
69 }
70
71 l.Info("removed account", "did", did)
72
73 if isCurrentAccount {
74 if len(remainingAccounts) > 0 {
75 nextDid := remainingAccounts[0]
76 if err := s.oauth.SwitchAccount(w, r, nextDid); err != nil {
77 l.Error("failed to switch to next account", "err", err)
78 s.pages.HxRedirect(w, "/login")
79 return
80 }
81 s.pages.HxRefresh(w)
82 return
83 }
84
85 if err := s.oauth.DeleteSession(w, r); err != nil {
86 l.Error("failed to delete session", "err", err)
87 }
88 s.pages.HxRedirect(w, "/login")
89 return
90 }
91
92 s.pages.HxRefresh(w)
93}