55 lines
1.4 KiB
Go
55 lines
1.4 KiB
Go
package hwsauth
|
|
|
|
import (
|
|
"database/sql"
|
|
"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]) getAuthenticatedUser(
|
|
tx *sql.Tx,
|
|
w http.ResponseWriter,
|
|
r *http.Request,
|
|
) (*authenticatedModel[T], error) {
|
|
// Get token strings from cookies
|
|
atStr, rtStr := jwt.GetTokenCookies(r)
|
|
if atStr == "" && rtStr == "" {
|
|
return nil, errors.New("No token strings provided")
|
|
}
|
|
// Attempt to parse the access token
|
|
aT, err := auth.tokenGenerator.ValidateAccess(tx, atStr)
|
|
if err != nil {
|
|
// Access token invalid, attempt to parse refresh token
|
|
rT, err := auth.tokenGenerator.ValidateRefresh(tx, rtStr)
|
|
if err != nil {
|
|
return nil, 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 nil, 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(tx, aT.SUB)
|
|
if err != nil {
|
|
return nil, errors.Wrap(err, "auth.load")
|
|
}
|
|
authUser := authenticatedModel[T]{
|
|
model: model,
|
|
fresh: aT.Fresh,
|
|
}
|
|
return &authUser, nil
|
|
}
|