this repo has no description
1package state
2
3import (
4 "log"
5 "net/http"
6 "time"
7
8 comatproto "github.com/bluesky-social/indigo/api/atproto"
9 "github.com/bluesky-social/indigo/xrpc"
10 "github.com/icyphox/bild/appview"
11 "github.com/icyphox/bild/appview/auth"
12)
13
14type Middleware func(http.Handler) http.Handler
15
16func AuthMiddleware(s *State) Middleware {
17 return func(next http.Handler) http.Handler {
18 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
19 session, _ := s.auth.Store.Get(r, appview.SessionName)
20 authorized, ok := session.Values[appview.SessionAuthenticated].(bool)
21 if !ok || !authorized {
22 log.Printf("not logged in, redirecting")
23 http.Redirect(w, r, "/login", http.StatusTemporaryRedirect)
24 return
25 }
26
27 // refresh if nearing expiry
28 // TODO: dedup with /login
29 expiryStr := session.Values[appview.SessionExpiry].(string)
30 expiry, err := time.Parse(appview.TimeLayout, expiryStr)
31 if err != nil {
32 log.Println("invalid expiry time", err)
33 return
34 }
35 pdsUrl := session.Values[appview.SessionPds].(string)
36 did := session.Values[appview.SessionDid].(string)
37 refreshJwt := session.Values[appview.SessionRefreshJwt].(string)
38
39 if time.Now().After(expiry) {
40 log.Println("token expired, refreshing ...")
41
42 client := xrpc.Client{
43 Host: pdsUrl,
44 Auth: &xrpc.AuthInfo{
45 Did: did,
46 AccessJwt: refreshJwt,
47 RefreshJwt: refreshJwt,
48 },
49 }
50 atSession, err := comatproto.ServerRefreshSession(r.Context(), &client)
51 if err != nil {
52 log.Println(err)
53 return
54 }
55
56 sessionish := auth.RefreshSessionWrapper{atSession}
57
58 err = s.auth.StoreSession(r, w, &sessionish, pdsUrl)
59 if err != nil {
60 log.Printf("failed to store session for did: %s\n: %s", atSession.Did, err)
61 return
62 }
63
64 log.Println("successfully refreshed token")
65 }
66
67 next.ServeHTTP(w, r)
68 })
69 }
70}