save oauth user_id and link users and accounts

This commit is contained in:
2025-12-30 02:06:14 -07:00
parent bc592718bf
commit 8090a6f25e
21 changed files with 468 additions and 198 deletions
+75 -9
View File
@@ -21,8 +21,9 @@ type (
}
Account struct {
ID int64
Email string
UserID string
ID int64
Email string
}
)
@@ -39,12 +40,24 @@ func (db *Store) WithContext(ctx context.Context) *StoreWithContext {
}
}
func (db *Store) CreateAccount(ctx context.Context, email string) (Account, error) {
func (db *Store) CreateAccount(ctx context.Context, userID, email string) (Account, error) {
rows, err := db.db.Query(
ctx,
"INSERT INTO accounts (email) VALUES (@email) RETURNING account_id",
`
INSERT INTO accounts (
user_id,
email
)
VALUES (
@user_id,
@email
)
RETURNING
account_id
`,
pgx.NamedArgs{
"email": email,
"user_id": userID,
"email": email,
},
)
if err != nil {
@@ -53,12 +66,16 @@ func (db *Store) CreateAccount(ctx context.Context, email string) (Account, erro
acctID, err := pgx.CollectExactlyOneRow(rows, pgx.RowTo[int64])
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return Account{}, consts.ErrNotFound
}
return Account{}, fmt.Errorf("failed to scan row: %w", err)
}
return Account{
ID: acctID,
Email: email,
UserID: userID,
ID: acctID,
Email: email,
}, nil
}
@@ -89,6 +106,44 @@ func (db *Store) GetAccount(ctx context.Context, id int64) (Account, error) {
}, nil
}
func (db *Store) GetAccountByUserID(ctx context.Context, userID string) (Account, error) {
rows, err := db.db.Query(
ctx,
`SELECT
email, account_id
FROM
accounts
WHERE
user_id = @user_id`,
pgx.NamedArgs{
"user_id": userID,
},
)
if err != nil {
return Account{}, fmt.Errorf("failed to perform query: %w", err)
}
type Row struct {
Email string
Account_ID int64
}
r, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByNameLax[Row])
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
return Account{}, consts.ErrNotFound
}
return Account{}, fmt.Errorf("failed to scan row: %w", err)
}
return Account{
UserID: userID,
ID: r.Account_ID,
Email: r.Email,
}, nil
}
func (db *Store) GetAccountByEmail(ctx context.Context, email string) (Account, error) {
rows, err := db.db.Query(
ctx,
@@ -116,10 +171,21 @@ func (db *Store) GetAccountByEmail(ctx context.Context, email string) (Account,
}, nil
}
func (db *StoreWithContext) CreateAccount(email string) (Account, error) {
return db.db.CreateAccount(db.ctx, email)
func (db *StoreWithContext) CreateAccount(userID, email string) (Account, error) {
return db.db.CreateAccount(db.ctx, userID, email)
}
func (db *StoreWithContext) GetAccount(id int64) (Account, error) {
return db.db.GetAccount(db.ctx, id)
}
func (db *StoreWithContext) GetAccountPointerByUserID(userID string) (*Account, error) {
acct, err := db.db.GetAccountByUserID(db.ctx, userID)
if err == nil {
return &acct, nil
}
if errors.Is(err, consts.ErrNotFound) {
return nil, nil
}
return nil, err
}