implemented access token refreshing - untested
This commit is contained in:
+24
-1
@@ -1,9 +1,11 @@
|
||||
package site
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -100,10 +102,31 @@ func (s *Server) authenticateAndAddIdentity(f response.HandlerFunc, assertions .
|
||||
return nil, response.Errorf("failed to authenticate: %w", err)
|
||||
}
|
||||
|
||||
if expiration.Before(time.Now()) {
|
||||
now := time.Now()
|
||||
|
||||
if expiration.Before(now) {
|
||||
return response.TemporaryRedirect("/").Cookie(getExpiredCookie("access_token")), nil
|
||||
}
|
||||
|
||||
// refresh tokens, when the access token is "old enough"
|
||||
|
||||
const idTokenLifetime = 10 * time.Hour
|
||||
if refreshFloor := expiration.Add(-idTokenLifetime); refreshFloor.Before(now) {
|
||||
accessToken, expiration, err = s.auth.RefreshAccessToken(ctx, accessToken)
|
||||
if err != nil {
|
||||
fmt.Println("failed to refresh access token:", err)
|
||||
return response.TemporaryRedirect("/").
|
||||
Body(io.NopCloser(bytes.NewBuffer([]byte(fmt.Sprintf("failed to refresh access token: %v", err))))).
|
||||
Cookie(getExpiredCookie("access_token")), nil
|
||||
}
|
||||
|
||||
// 'redirect' to same url, to set the new access_token cookie
|
||||
return response.TemporaryRedirect(r.URL.String()).
|
||||
Cookie(newAccessTokenCookie(accessToken, expiration)), nil
|
||||
}
|
||||
|
||||
// add identity info to request context
|
||||
|
||||
user, acct, err := s.accts.GetUserAndAccountByAccessToken(ctx, accessToken)
|
||||
if err != nil {
|
||||
return nil, response.Errorf("failed to authorize: %w", err)
|
||||
|
||||
Reference in New Issue
Block a user