Files
golib/hwsauth/authenticate.go

54 lines
1.5 KiB
Go

package hwsauth
import (
"net/http"
"time"
"git.haelnorr.com/h/golib/jwt"
"github.com/pkg/errors"
)
// Check the cookies for token strings and attempt to authenticate them
func (auth *Authenticator[T, TX]) getAuthenticatedUser(
tx TX,
w http.ResponseWriter,
r *http.Request,
) (authenticatedModel[T], error) {
// Get token strings from cookies
atStr, rtStr := jwt.GetTokenCookies(r)
if atStr == "" && rtStr == "" {
return authenticatedModel[T]{}, errors.New("No token strings provided")
}
// Attempt to parse the access token
aT, err := auth.tokenGenerator.ValidateAccess(jwt.DBTransaction(tx), atStr)
if err != nil {
// Access token invalid, attempt to parse refresh token
rT, err := auth.tokenGenerator.ValidateRefresh(jwt.DBTransaction(tx), rtStr)
if err != nil {
return authenticatedModel[T]{}, errors.Wrap(err, "auth.tokenGenerator.ValidateRefresh")
}
// Refresh token valid, attempt to get a new token pair
model, err := auth.refreshAuthTokens(tx, w, r, rT)
if err != nil {
return authenticatedModel[T]{}, errors.Wrap(err, "auth.refreshAuthTokens")
}
// New token pair sent, return the authorized user
authUser := authenticatedModel[T]{
model: model,
fresh: time.Now().Unix(),
}
return authUser, nil
}
// Access token valid
model, err := auth.load(r.Context(), tx, aT.SUB)
if err != nil {
return authenticatedModel[T]{}, errors.Wrap(err, "auth.load")
}
authUser := authenticatedModel[T]{
model: model,
fresh: aT.Fresh,
}
return authUser, nil
}