Files
inventory-plus-plus/internal/server/middleware/auth.go
T
2026-01-12 23:21:52 -07:00

185 lines
4.9 KiB
Go

package middleware
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"time"
"ruben/inventory2/internal/consts"
"ruben/inventory2/internal/domains/accounts"
"ruben/inventory2/internal/domains/authentication"
"ruben/inventory2/internal/logging"
"ruben/inventory2/internal/server/cookies"
"ruben/inventory2/internal/server/response"
)
type (
Auth struct {
log *logging.Logger
auth *authentication.Authenticator
newLoginURL LoginURLProviderFunc
accts *accounts.Store
}
Identity struct {
AccessToken string
Claims authentication.AccessTokenClaims
User accounts.OAuthUser
Account *accounts.Account
}
LoginURLProviderFunc = func(ctx context.Context, auth *authentication.Authenticator, targetURI string) (string, error)
AuthorizationAssertions = response.HandlerFunc
)
func NewAuth(
logger *logging.Logger,
auth *authentication.Authenticator,
newLoginURL LoginURLProviderFunc,
accts *accounts.Store,
) *Auth {
return &Auth{
log: logger,
auth: auth,
newLoginURL: newLoginURL,
accts: accts,
}
}
func (a *Auth) AddIdentity(fn response.HandlerFunc) response.HandlerFunc {
return func(r *http.Request) (response.Response, error) {
r, err := a.AddIdentityToRequest(r)
if err != nil {
return nil, err
}
return fn(r)
}
}
func (a *Auth) AddIdentityToRequest(r *http.Request) (*http.Request, error) {
ck, err := r.Cookie("access_token")
if err != nil {
return r, nil
}
ctx := r.Context()
accessToken := ck.Value
claims, expiration, err := a.auth.GetAccessTokenClaimsAndExpiration(ctx, accessToken)
if err != nil {
if errors.Is(err, consts.ErrNotFound) {
return r, nil
}
return r, response.Errorf("failed to load authentication details: %w", err)
}
if expiration.Before(time.Now()) {
return r, nil
}
user, acct, err := a.accts.GetUserAndAccountByAccessToken(ctx, accessToken)
if err != nil {
return r, response.Errorf("failed to load user and account defails: %w", err)
}
return r.WithContext(SetIdentity(ctx, Identity{
AccessToken: accessToken,
Claims: claims,
User: user,
Account: acct,
})), nil
}
// TODO: after getting auth, consider making http handler functions take 'claims', etc, as function arguments
// - then consider doing the same with authorizationAssertions
// auth middleware to verify access_token cookie and set custom claims in the request context
func (a *Auth) AuthenticateAndAddIdentity(f response.HandlerFunc, assertions ...AuthorizationAssertions) response.HandlerFunc {
return func(r *http.Request) (response.Response, error) {
ck, err := r.Cookie("access_token")
if err != nil {
return response.TemporaryRedirect("/").
JSON("no access_token cookie provided"), nil
}
ctx := r.Context()
accessToken := ck.Value
claims, expiration, err := a.auth.GetAccessTokenClaimsAndExpiration(ctx, accessToken)
if err != nil {
if errors.Is(err, consts.ErrNotFound) {
u, err := a.newLoginURL(ctx, a.auth, r.URL.String())
if err != nil {
return nil, response.Errorf("failed to generate login url: %w", err)
}
return response.TemporaryRedirect(u), nil
}
return nil, response.Errorf("failed to authenticate: %w", err)
}
now := time.Now()
// refresh tokens, when the access token is "old enough"
// id token lifetime is 48 hours, allowing a person to use the app everyday comfortably, with wiggle room, without having to log in.
const idTokenLifetime = 48 * time.Hour
if refreshFloor := expiration.Add(-(idTokenLifetime / 4)); refreshFloor.Before(now) {
accessToken, expiration, err = a.auth.RefreshAccessToken(ctx, accessToken)
if err != nil {
a.log.Warn("failed to refresh access token", "error", err)
return response.TemporaryRedirect("/").
Body(io.NopCloser(bytes.NewBuffer([]byte(fmt.Sprintf("failed to refresh access token: %v", err))))).
Cookie(cookies.Expired("access_token")), nil
}
// 'redirect' to same url, to set the new access_token cookie
return response.TemporaryRedirect(r.URL.String()).
Cookie(cookies.AccessToken(accessToken, expiration)), nil
}
// add identity info to request context
user, acct, err := a.accts.GetUserAndAccountByAccessToken(ctx, accessToken)
if err != nil {
return nil, response.Errorf("failed to authorize: %w", err)
}
for _, as := range assertions {
if res, err := as(r); res != nil || err != nil {
return res, err
}
}
return f(r.WithContext(SetIdentity(ctx, Identity{
AccessToken: accessToken,
Claims: claims,
User: user,
Account: acct,
})))
}
}
type identityKey struct{}
// stores identity in request context
func SetIdentity(ctx context.Context, id Identity) context.Context {
return context.WithValue(ctx, identityKey{}, id)
}
// get identity from request context
func GetIdentity(ctx context.Context) Identity {
id, _ := ctx.Value(identityKey{}).(Identity)
return id
}