Skip to content
Snippets Groups Projects
Commit a3e58c1d authored by Gabriel Zachmann's avatar Gabriel Zachmann
Browse files

restructer polling code in db

parent f38413b5
No related branches found
No related tags found
No related merge requests found
......@@ -36,3 +36,16 @@ func NewNullString(s string) sql.NullString {
Valid: true,
}
}
func Transact(fn func(*sqlx.Tx) error) error {
tx, err := DB().Beginx()
if err != nil {
return err
}
err = fn(tx)
if err != nil {
tx.Rollback()
return err
}
return tx.Commit()
}
......@@ -4,6 +4,8 @@ import (
"database/sql"
"log"
"github.com/jmoiron/sqlx"
"github.com/zachmann/mytoken/internal/db"
"github.com/zachmann/mytoken/internal/supertoken/capabilities"
"github.com/zachmann/mytoken/internal/supertoken/restrictions"
......@@ -19,12 +21,12 @@ type AuthFlowInfo struct {
}
type authFlowInfo struct {
State string
Issuer string
Restrictions restrictions.Restrictions
Capabilities capabilities.Capabilities
Name sql.NullString
PollingCode sql.NullString `db:"polling_code"`
State string
Issuer string
Restrictions restrictions.Restrictions
Capabilities capabilities.Capabilities
Name sql.NullString
PollingCodeID *uint64 `db:"polling_code_id"`
}
func newAuthFlowInfo(i *AuthFlowInfo) *authFlowInfo {
......@@ -34,13 +36,26 @@ func newAuthFlowInfo(i *AuthFlowInfo) *authFlowInfo {
Restrictions: i.Restrictions,
Capabilities: i.Capabilities,
Name: db.NewNullString(i.Name),
PollingCode: db.NewNullString(i.PollingCode),
}
}
func (e *AuthFlowInfo) Store() error {
log.Printf("Storing auth flow info")
store := newAuthFlowInfo(e)
_, err := db.DB().NamedExec(`INSERT INTO AuthInfo (state, iss, restrictions, capabilities, name, polling_code) VALUES(:state, :issuer, :restrictions, :capabilities, :name, :polling_code)`, store)
return err
return db.Transact(func(tx *sqlx.Tx) error {
if e.PollingCode != "" {
res, err := tx.Exec(`INSERT INTO PollingCodes (polling_code) VALUES(?)`, e.PollingCode)
if err != nil {
return err
}
pid, err := res.LastInsertId()
if err != nil {
return err
}
upid := uint64(pid)
store.PollingCodeID = &upid
}
_, err := tx.NamedExec(`INSERT INTO AuthInfo (state, iss, restrictions, capabilities, name, polling_code_id) VALUES(:state, :issuer, :restrictions, :capabilities, :name, :polling_code_id)`, store)
return err
})
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment