This repository has no description
1package state
2
3import (
4 "errors"
5 "fmt"
6 "net/http"
7 "strings"
8 "time"
9
10 comatproto "github.com/bluesky-social/indigo/api/atproto"
11 "github.com/bluesky-social/indigo/xrpc"
12 "tangled.org/core/appview/pages"
13)
14
15func (s *State) Login(w http.ResponseWriter, r *http.Request) {
16 l := s.logger.With("handler", "Login")
17
18 switch r.Method {
19 case http.MethodGet:
20 returnURL := r.URL.Query().Get("return_url")
21 errorCode := r.URL.Query().Get("error")
22 addAccount := r.URL.Query().Get("mode") == "add_account"
23 handle := r.URL.Query().Get("handle")
24
25 registry := s.oauth.GetAccounts(r)
26 s.pages.Login(w, pages.LoginParams{
27 ReturnUrl: returnURL,
28 ErrorCode: errorCode,
29 AddAccount: addAccount,
30 Handle: handle,
31 Accounts: registry.Accounts,
32 })
33 case http.MethodPost:
34 handle := r.FormValue("handle")
35 returnURL := r.FormValue("return_url")
36
37 // remove spaces around the handle, handles can't have spaces around them
38 handle = strings.TrimSpace(handle)
39
40 // when users copy their handle from bsky.app, it tends to have these characters around it:
41 //
42 // @nelind.dk:
43 // \u202a ensures that the handle is always rendered left to right and
44 // \u202c reverts that so the rest of the page renders however it should
45 handle = strings.TrimPrefix(handle, "\u202a")
46 handle = strings.TrimSuffix(handle, "\u202c")
47
48 // `@` is harmless
49 handle = strings.TrimPrefix(handle, "@")
50
51 // basic handle validation
52 if !strings.Contains(handle, ".") {
53 l.Error("invalid handle format", "raw", handle)
54 s.pages.Notice(
55 w,
56 "login-msg",
57 fmt.Sprintf("\"%s\" is an invalid handle. Did you mean %s.bsky.social or %s.tngl.sh?", handle, handle, handle),
58 )
59 return
60 }
61
62 ident, err := s.idResolver.ResolveAtIdentifier(r.Context(), handle)
63 if err != nil {
64 l.Warn("handle resolution failed", "handle", handle, "err", err)
65 s.pages.Notice(w, "login-msg", fmt.Sprintf("Could not resolve handle \"%s\". The account may not exist.", handle))
66 return
67 }
68
69 pdsEndpoint := ident.PDSEndpoint()
70 if pdsEndpoint == "" {
71 s.pages.Notice(w, "login-msg", fmt.Sprintf("No PDS found for \"%s\".", handle))
72 return
73 }
74
75 pdsClient := &xrpc.Client{Host: pdsEndpoint, Client: &http.Client{Timeout: 5 * time.Second}}
76 _, err = comatproto.RepoDescribeRepo(r.Context(), pdsClient, ident.DID.String())
77 if err != nil {
78 var xrpcErr *xrpc.Error
79 var xrpcBody *xrpc.XRPCError
80 isDeactivated := errors.As(err, &xrpcErr) &&
81 errors.As(xrpcErr.Wrapped, &xrpcBody) &&
82 xrpcBody.ErrStr == "RepoDeactivated"
83
84 if !isDeactivated {
85 l.Warn("describeRepo failed", "handle", handle, "did", ident.DID, "pds", pdsEndpoint, "err", err)
86 s.pages.Notice(w, "login-msg", fmt.Sprintf("Account \"%s\" is no longer available.", handle))
87 return
88 }
89 }
90
91 if err := s.oauth.SetAuthReturn(w, r, sanitizeReturnURL(returnURL)); err != nil {
92 l.Error("failed to set auth return", "err", err)
93 }
94
95 redirectURL, err := s.oauth.ClientApp.StartAuthFlow(r.Context(), ident.DID.String())
96 if err != nil {
97 l.Error("failed to start auth", "err", err)
98 s.pages.Notice(
99 w,
100 "login-msg",
101 fmt.Sprintf("Failed to start auth flow: %v", err),
102 )
103 return
104 }
105
106 s.pages.HxRedirect(w, redirectURL)
107 }
108}
109
110// sanitizeReturnURL ensures the return URL is a relative path on the same
111// origin. Anything else — absolute URLs, protocol-relative URLs — is replaced
112// with "/" to prevent open redirect after OAuth login.
113func sanitizeReturnURL(s string) string {
114 if strings.HasPrefix(s, "/") && !strings.HasPrefix(s, "//") {
115 return s
116 }
117 return "/"
118}
119
120func (s *State) Logout(w http.ResponseWriter, r *http.Request) {
121 l := s.logger.With("handler", "Logout")
122
123 currentUser := s.oauth.GetMultiAccountUser(r)
124 if currentUser == nil {
125 s.pages.HxRedirect(w, "/login")
126 return
127 }
128
129 currentDid := currentUser.Did
130
131 var remainingAccounts []string
132 for _, acc := range currentUser.Accounts {
133 if acc.Did != currentDid {
134 remainingAccounts = append(remainingAccounts, acc.Did)
135 }
136 }
137
138 if err := s.oauth.RemoveAccount(w, r, currentDid); err != nil {
139 l.Error("failed to remove account from registry", "err", err)
140 }
141
142 if err := s.oauth.DeleteSession(w, r); err != nil {
143 l.Error("failed to delete session", "err", err)
144 }
145
146 if len(remainingAccounts) > 0 {
147 nextDid := remainingAccounts[0]
148 if err := s.oauth.SwitchAccount(w, r, nextDid); err != nil {
149 l.Error("failed to switch to next account", "err", err)
150 s.pages.HxRedirect(w, "/login")
151 return
152 }
153 l.Info("switched to next account after logout", "did", nextDid)
154 s.pages.HxRefresh(w)
155 return
156 }
157
158 l.Info("logged out last account")
159 s.pages.HxRedirect(w, "/login")
160}