This repository has no description
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 s.pages.HxRefresh(w)
38}
39
40func (s *State) RemoveAccount(w http.ResponseWriter, r *http.Request) {
41 l := s.logger.With("handler", "RemoveAccount")
42
43 did := chi.URLParam(r, "did")
44 if did == "" {
45 http.Error(w, "missing did", http.StatusBadRequest)
46 return
47 }
48
49 currentUser := s.oauth.GetMultiAccountUser(r)
50 isCurrentAccount := currentUser != nil && currentUser.Did == did
51
52 var remainingAccounts []string
53 if currentUser != nil {
54 for _, acc := range currentUser.Accounts {
55 if acc.Did != did {
56 remainingAccounts = append(remainingAccounts, acc.Did)
57 }
58 }
59 }
60
61 if err := s.oauth.RemoveAccount(w, r, did); err != nil {
62 l.Error("failed to remove account", "err", err)
63 http.Error(w, "failed to remove account", http.StatusInternalServerError)
64 return
65 }
66
67 l.Info("removed account", "did", did)
68
69 if isCurrentAccount {
70 if len(remainingAccounts) > 0 {
71 nextDid := remainingAccounts[0]
72 if err := s.oauth.SwitchAccount(w, r, nextDid); err != nil {
73 l.Error("failed to switch to next account", "err", err)
74 s.pages.HxRedirect(w, "/login")
75 return
76 }
77 s.pages.HxRefresh(w)
78 return
79 }
80
81 if err := s.oauth.DeleteSession(w, r); err != nil {
82 l.Error("failed to delete session", "err", err)
83 }
84 s.pages.HxRedirect(w, "/login")
85 return
86 }
87
88 s.pages.HxRefresh(w)
89}