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/legit/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 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["expiry"].(string)
30 expiry, _ := time.Parse(layout, expiryStr)
31 pdsUrl := session.Values["pds"].(string)
32 did := session.Values["did"].(string)
33 refreshJwt := session.Values["refreshJwt"].(string)
34
35 if time.Now().After((expiry)) {
36 log.Println("token expired, refreshing ...")
37
38 client := xrpc.Client{
39 Host: pdsUrl,
40 Auth: &xrpc.AuthInfo{
41 Did: did,
42 AccessJwt: refreshJwt,
43 RefreshJwt: refreshJwt,
44 },
45 }
46 atSession, err := comatproto.ServerRefreshSession(r.Context(), &client)
47 if err != nil {
48 log.Println(err)
49 h.Write500(w)
50 return
51 }
52
53 err = h.auth.StoreSession(r, w, nil, &rauth.AtSessionRefresh{ServerRefreshSession_Output: *atSession, PDSEndpoint: pdsUrl})
54 if err != nil {
55 log.Printf("failed to store session for did: %s\n: %s", atSession.Did, err)
56 h.Write500(w)
57 return
58 }
59
60 log.Println("successfully refreshed token")
61 }
62
63 next.ServeHTTP(w, r)
64 })
65}