redirect to desired page after authenticating

This commit is contained in:
2026-01-06 02:33:48 -07:00
parent 34061d21c1
commit e20623a6d3
7 changed files with 80 additions and 34 deletions
+35 -13
View File
@@ -10,10 +10,11 @@ import (
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
)
// NewState creates a new state for logging in, saving it in the database.
func (a *Authenticator) NewState(ctx context.Context) ([32]byte, error) {
func (a *Authenticator) NewState(ctx context.Context, targetURI string) ([32]byte, error) {
state, err := generateRandomState()
if err != nil {
return state, fmt.Errorf("failed to generate random state: %w", err)
@@ -21,9 +22,20 @@ func (a *Authenticator) NewState(ctx context.Context) ([32]byte, error) {
if _, err = a.db.Exec(
ctx,
"INSERT INTO oauth_login_states (state) VALUES (@state)",
`
INSERT INTO
oauth_login_states (
state,
target_uri
)
VALUES (
@state,
@target_uri
)
`,
pgx.NamedArgs{
"state": state[:],
"state": state[:],
"target_uri": targetURI,
},
); err != nil {
return state, fmt.Errorf("failed to execute query: %w", err)
@@ -38,31 +50,41 @@ func generateRandomState() ([32]byte, error) {
return b, err
}
// GetStateExpiration get's the oauth state's expiration
// func (a *Authenticator) GetStateExpiration(ctx context.Context, state [32]byte) (time.Time, error) {
func (a *Authenticator) GetStateExpiration(ctx context.Context, state string) (time.Time, error) {
// GetStateExpirationAndURL get's the oauth state's expiration
func (a *Authenticator) GetStateExpirationAndURL(ctx context.Context, state string) (time.Time, string, error) {
rows, err := a.db.Query(
ctx,
`SELECT expiration from oauth_login_states WHERE state = ('\x' || @state)::BYTEA`,
`
SELECT
expiration,
target_uri
FROM
oauth_login_states
WHERE
state = ('\x' || @state)::BYTEA`,
pgx.NamedArgs{
//"state": state[:],
"state": state,
},
)
if err != nil {
return time.Time{}, fmt.Errorf("failed to perform query: %w", err)
return time.Time{}, "", fmt.Errorf("failed to perform query: %w", err)
}
exp, err := pgx.CollectExactlyOneRow(rows, pgx.RowTo[time.Time])
type Row struct {
Expiration time.Time
Target_uri pgtype.Text
}
r, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByNameLax[Row])
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return time.Time{}, consts.ErrNotFound
return time.Time{}, "", consts.ErrNotFound
}
return time.Time{}, fmt.Errorf("failed to scan row: %w", err)
return time.Time{}, "", fmt.Errorf("failed to scan row: %w", err)
}
return exp, nil
return r.Expiration, r.Target_uri.String, nil
}
// TODO: need to automatically clean up expired tokens