this repo has no description
1package routes 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) 11 12const ( 13 layout = "2006-01-02 15:04:05.999999999 -0700 MST" 14) 15 16func (h *Handle) AuthMiddleware(next http.Handler) http.Handler { 17 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 18 session, _ := h.s.Get(r, "bild-session") 19 auth, ok := session.Values["authenticated"].(bool) 20 21 if !ok || !auth { 22 http.Error(w, "Forbidden: You are not logged in", http.StatusForbidden) 23 return 24 } 25 26 // refresh if nearing expiry 27 // TODO: dedup with /login 28 expiryStr := session.Values["expiry"].(string) 29 expiry, _ := time.Parse(layout, expiryStr) 30 pdsUrl := session.Values["pds"].(string) 31 did := session.Values["did"].(string) 32 refreshJwt := session.Values["refreshJwt"].(string) 33 34 if time.Now().After((expiry)) { 35 log.Println("token expired, refreshing ...") 36 37 client := xrpc.Client{ 38 Host: pdsUrl, 39 Auth: &xrpc.AuthInfo{ 40 Did: did, 41 AccessJwt: refreshJwt, 42 RefreshJwt: refreshJwt, 43 }, 44 } 45 atSession, err := comatproto.ServerRefreshSession(r.Context(), &client) 46 47 if err != nil { 48 log.Println(err) 49 http.Error(w, "Internal Server Error", http.StatusInternalServerError) 50 return 51 } 52 53 clientSession, _ := h.s.Get(r, "bild-session") 54 clientSession.Values["handle"] = atSession.Handle 55 clientSession.Values["did"] = atSession.Did 56 clientSession.Values["accessJwt"] = atSession.AccessJwt 57 clientSession.Values["refreshJwt"] = atSession.RefreshJwt 58 clientSession.Values["expiry"] = time.Now().Add(time.Hour).String() 59 clientSession.Values["pds"] = pdsUrl 60 clientSession.Values["authenticated"] = true 61 62 err = clientSession.Save(r, w) 63 64 if err != nil { 65 log.Printf("failed to store session for did: %s\n", atSession.Did) 66 log.Println(err) 67 http.Error(w, "Internal Server Error", http.StatusInternalServerError) 68 return 69 } 70 71 log.Println("successfully refreshed token") 72 } 73 74 next.ServeHTTP(w, r) 75 }) 76}