polycule-connect/polyculeconnect/internal/db/authrequest/authrequest.go
Melora Hugues 9206c8e41e
Some checks failed
/ docker-build-only (push) Failing after 45s
/ go-test (push) Failing after 1m28s
Add start of auth request storage
2024-09-22 10:26:27 +02:00

77 lines
2.2 KiB
Go

package authrequest
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"git.faercol.me/faercol/polyculeconnect/polyculeconnect/internal/model"
"github.com/google/uuid"
)
var ErrNotFound = errors.New("backend not found")
const authRequestRows = `"id", "client_id", "backend_id", "scopes", "redirect_uri", "state", "nonce", "response_type", "creation_time"`
type AuthRequestDB interface {
GetAuthRequestByID(ctx context.Context, id uuid.UUID) (*model.AuthRequest, error)
CreateAuthRequest(ctx context.Context, req model.AuthRequest) error
}
type sqlAuthRequestDB struct {
db *sql.DB
}
func (db *sqlAuthRequestDB) GetAuthRequestByID(ctx context.Context, id uuid.UUID) (*model.AuthRequest, error) {
query := fmt.Sprintf(`SELECT %s FROM "auth_request_2" WHERE "id" = ?`, authRequestRows)
row := db.db.QueryRowContext(ctx, query, id)
var res model.AuthRequest
var scopesStr []byte
if err := row.Scan(&res.ID, &res.ClientID, &res.BackendID, &scopesStr, &res.RedirectURI, &res.State, &res.Nonce, &res.ResponseType, &res.CreationDate); err != nil {
return nil, fmt.Errorf("failed to get auth request from DB: %w", err)
}
if err := json.Unmarshal(scopesStr, &res.Scopes); err != nil {
return nil, fmt.Errorf("invalid format for scopes: %w", err)
}
fmt.Println(res)
return &res, nil
}
func (db *sqlAuthRequestDB) CreateAuthRequest(ctx context.Context, req model.AuthRequest) error {
tx, err := db.db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("failed to start transaction: %w", err)
}
defer func() { _ = tx.Rollback() }()
scopesStr, err := json.Marshal(req.Scopes)
if err != nil {
return fmt.Errorf("failed to serialize scopes: %w", err)
}
query := fmt.Sprintf(`INSERT INTO "auth_request_2" (%s) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`, authRequestRows)
_, err = tx.ExecContext(ctx, query,
req.ID, req.ClientID, req.BackendID,
scopesStr, req.RedirectURI, req.State,
req.Nonce, req.ResponseType, req.CreationDate, req.AuthTime,
)
if err != nil {
return fmt.Errorf("failed to insert in DB: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("failed to commit transaction: %w", err)
}
return nil
}
func New(db *sql.DB) *sqlAuthRequestDB {
return &sqlAuthRequestDB{db: db}
}