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