forked from
tangled.org/core
Monorepo for Tangled — https://tangled.org
1package state
2
3import (
4 "fmt"
5 "net/http"
6 "strings"
7
8 "tangled.org/core/appview/pages"
9)
10
11func (s *State) Login(w http.ResponseWriter, r *http.Request) {
12 l := s.logger.With("handler", "Login")
13
14 switch r.Method {
15 case http.MethodGet:
16 returnURL := r.URL.Query().Get("return_url")
17 errorCode := r.URL.Query().Get("error")
18 s.pages.Login(w, pages.LoginParams{
19 ReturnUrl: returnURL,
20 ErrorCode: errorCode,
21 })
22 case http.MethodPost:
23 handle := r.FormValue("handle")
24
25 // when users copy their handle from bsky.app, it tends to have these characters around it:
26 //
27 // @nelind.dk:
28 // \u202a ensures that the handle is always rendered left to right and
29 // \u202c reverts that so the rest of the page renders however it should
30 handle = strings.TrimPrefix(handle, "\u202a")
31 handle = strings.TrimSuffix(handle, "\u202c")
32
33 // `@` is harmless
34 handle = strings.TrimPrefix(handle, "@")
35
36 // basic handle validation
37 if !strings.Contains(handle, ".") {
38 l.Error("invalid handle format", "raw", handle)
39 s.pages.Notice(
40 w,
41 "login-msg",
42 fmt.Sprintf("\"%s\" is an invalid handle. Did you mean %s.bsky.social or %s.tngl.sh?", handle, handle, handle),
43 )
44 return
45 }
46
47 redirectURL, err := s.oauth.ClientApp.StartAuthFlow(r.Context(), handle)
48 if err != nil {
49 l.Error("failed to start auth", "err", err)
50 http.Error(w, err.Error(), http.StatusInternalServerError)
51 return
52 }
53
54 s.pages.HxRedirect(w, redirectURL)
55 }
56}
57
58func (s *State) Logout(w http.ResponseWriter, r *http.Request) {
59 l := s.logger.With("handler", "Logout")
60
61 err := s.oauth.DeleteSession(w, r)
62 if err != nil {
63 l.Error("failed to logout", "err", err)
64 } else {
65 l.Info("logged out successfully")
66 }
67
68 s.pages.HxRedirect(w, "/login")
69}