implemented access token refreshing - untested

This commit is contained in:
2026-01-04 21:34:24 -07:00
parent e36c759dc2
commit 8ccc795812
5 changed files with 221 additions and 23 deletions
+24 -1
View File
@@ -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)
+13 -8
View File
@@ -4,6 +4,7 @@ import (
"fmt"
"net/http"
"ruben/inventory2/internal/site/response"
"time"
)
// GET /login
@@ -53,14 +54,18 @@ func (s *Server) loginCallback(r *http.Request) (response.Response, error) {
// set access_token cookie and redirect to a reasonable place
return response.TemporaryRedirect("/").
Cookie(http.Cookie{
Name: "access_token",
Value: accessToken,
Path: "/",
Expires: expiration,
MaxAge: 0, // using Expiration instead
Secure: true,
}), nil
Cookie(newAccessTokenCookie(accessToken, expiration)), nil
}
func newAccessTokenCookie(tkn string, expiration time.Time) http.Cookie {
return http.Cookie{
Name: "access_token",
Value: tkn,
Path: "/",
Expires: expiration,
MaxAge: 0, // using Expiration instead
Secure: true,
}
}
// GET /logout