2 Commits

Author SHA1 Message Date
28bfbb84ad add oidc sqlite 2025-02-13 04:51:17 -06:00
4e61d7714e rename structs 2025-02-09 09:38:02 -06:00
12 changed files with 522 additions and 39 deletions

View File

@@ -1,6 +1,14 @@
version: "3" version: "3"
vars:
test_db: "~/databases/test.db"
schema_db: "./sqlite/schema.sql"
tasks: tasks:
sql: sqlc:
cmds: cmds:
- sqlc generate - sqlc generate
rebuild_test_db:
cmds:
- rm {{.test_db}}
- sqlite3 {{.test_db}} < {{.schema_db}}

View File

@@ -5,7 +5,7 @@ import (
"git.infra.nkode.tech/dkelly/nkode-core/config" "git.infra.nkode.tech/dkelly/nkode-core/config"
"git.infra.nkode.tech/dkelly/nkode-core/email" "git.infra.nkode.tech/dkelly/nkode-core/email"
"git.infra.nkode.tech/dkelly/nkode-core/entities" "git.infra.nkode.tech/dkelly/nkode-core/entities"
"git.infra.nkode.tech/dkelly/nkode-core/memCache" "git.infra.nkode.tech/dkelly/nkode-core/memcache"
"git.infra.nkode.tech/dkelly/nkode-core/repository" "git.infra.nkode.tech/dkelly/nkode-core/repository"
"git.infra.nkode.tech/dkelly/nkode-core/security" "git.infra.nkode.tech/dkelly/nkode-core/security"
"github.com/google/uuid" "github.com/google/uuid"
@@ -24,7 +24,7 @@ type NKodeAPI struct {
repo repository.CustomerUserRepository repo repository.CustomerUserRepository
signupSessionCache *cache.Cache signupSessionCache *cache.Cache
emailQueue *email.Queue emailQueue *email.Queue
forgotNkodeCache memCache.ForgotNKodeCache forgotNkodeCache memcache.ForgotNKodeCache
} }
func NewNKodeAPI(repo repository.CustomerUserRepository, queue *email.Queue) NKodeAPI { func NewNKodeAPI(repo repository.CustomerUserRepository, queue *email.Queue) NKodeAPI {
@@ -32,7 +32,7 @@ func NewNKodeAPI(repo repository.CustomerUserRepository, queue *email.Queue) NKo
repo: repo, repo: repo,
emailQueue: queue, emailQueue: queue,
signupSessionCache: cache.New(sessionExpiration, sessionCleanupInterval), signupSessionCache: cache.New(sessionExpiration, sessionCleanupInterval),
forgotNkodeCache: memCache.NewForgotNKodeCache(), forgotNkodeCache: memcache.NewForgotNKodeCache(),
} }
} }

View File

@@ -18,12 +18,12 @@ func TestNKodeAPI(t *testing.T) {
dbPath := os.Getenv("TEST_DB") dbPath := os.Getenv("TEST_DB")
ctx := context.Background() ctx := context.Background()
sqlitedb, err := repository.NewSqliteRepository(ctx, dbPath) sqlitedb, err := repository.NewSqliteNKodeRepo(ctx, dbPath)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
sqlitedb.Start() sqlitedb.Start()
defer func(sqldb *repository.SqliteRepository) { defer func(sqldb *repository.SqliteNKodeRepo) {
if err := sqldb.Stop(); err != nil { if err := sqldb.Stop(); err != nil {
log.Fatal(err) log.Fatal(err)
} }

View File

@@ -29,9 +29,9 @@ func main() {
log.Fatal(err) log.Fatal(err)
} }
ctx := context.Background() ctx := context.Background()
sqliteRepo, err := repository.NewSqliteRepository(ctx, *dbPath) sqliteRepo, err := repository.NewSqliteNKodeRepo(ctx, *dbPath)
sqliteRepo.Start() sqliteRepo.Start()
defer func(sqliteRepo *repository.SqliteRepository) { defer func(sqliteRepo *repository.SqliteNKodeRepo) {
if err := sqliteRepo.Stop(); err != nil { if err := sqliteRepo.Stop(); err != nil {
log.Fatal(err) log.Fatal(err)
} }
@@ -41,7 +41,7 @@ func main() {
log.Println(fmt.Sprintf("Successfully added all SVGs in %s to the database at %s\n", *svgPath, *dbPath)) log.Println(fmt.Sprintf("Successfully added all SVGs in %s to the database at %s\n", *svgPath, *dbPath))
} }
func FlaticonToSqlite(repo *repository.SqliteRepository, svgDir string) { func FlaticonToSqlite(repo *repository.SqliteNKodeRepo, svgDir string) {
files, err := os.ReadDir(svgDir) files, err := os.ReadDir(svgDir)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)

View File

@@ -133,7 +133,7 @@ func TestNKodeAPI(t *testing.T) {
type TestRouter struct { type TestRouter struct {
router *gin.Engine router *gin.Engine
emailQueue *email.Queue emailQueue *email.Queue
repo *repository.SqliteRepository repo *repository.SqliteNKodeRepo
handler *NkodeHandler handler *NkodeHandler
} }
@@ -143,7 +143,7 @@ func NewTestRouter() *TestRouter {
logger := log.Default() logger := log.Default()
ctx := context.Background() ctx := context.Background()
dbPath := os.Getenv("TEST_DB") dbPath := os.Getenv("TEST_DB")
repo, err := repository.NewSqliteRepository(ctx, dbPath) repo, err := repository.NewSqliteNKodeRepo(ctx, dbPath)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }

View File

@@ -1,4 +1,4 @@
package memCache package memcache
import ( import (
"git.infra.nkode.tech/dkelly/nkode-core/entities" "git.infra.nkode.tech/dkelly/nkode-core/entities"

View File

@@ -14,12 +14,12 @@ import (
"log" "log"
) )
type SqliteRepository struct { type SqliteNKodeRepo struct {
Queue *sqlc.Queue Queue *sqlc.Queue
ctx context.Context ctx context.Context
} }
func NewSqliteRepository(ctx context.Context, dbPath string) (*SqliteRepository, error) { func NewSqliteNKodeRepo(ctx context.Context, dbPath string) (*SqliteNKodeRepo, error) {
sqliteDb, err := sqlc.OpenSqliteDb(dbPath) sqliteDb, err := sqlc.OpenSqliteDb(dbPath)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -28,21 +28,21 @@ func NewSqliteRepository(ctx context.Context, dbPath string) (*SqliteRepository,
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &SqliteRepository{ return &SqliteNKodeRepo{
Queue: queue, Queue: queue,
ctx: ctx, ctx: ctx,
}, nil }, nil
} }
func (d *SqliteRepository) Start() { func (d *SqliteNKodeRepo) Start() {
d.Queue.Start() d.Queue.Start()
} }
func (d *SqliteRepository) Stop() error { func (d *SqliteNKodeRepo) Stop() error {
return d.Queue.Stop() return d.Queue.Stop()
} }
func (d *SqliteRepository) CreateCustomer(c entities.Customer) error { func (d *SqliteNKodeRepo) CreateCustomer(c entities.Customer) error {
queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) error { queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) error {
params, ok := args.(sqlc.CreateCustomerParams) params, ok := args.(sqlc.CreateCustomerParams)
if !ok { if !ok {
@@ -54,7 +54,7 @@ func (d *SqliteRepository) CreateCustomer(c entities.Customer) error {
return d.Queue.EnqueueWriteTx(queryFunc, c.ToSqlcCreateCustomerParams()) return d.Queue.EnqueueWriteTx(queryFunc, c.ToSqlcCreateCustomerParams())
} }
func (d *SqliteRepository) WriteNewUser(u entities.User) error { func (d *SqliteNKodeRepo) WriteNewUser(u entities.User) error {
queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) error { queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) error {
params, ok := args.(sqlc.CreateUserParams) params, ok := args.(sqlc.CreateUserParams)
if !ok { if !ok {
@@ -92,7 +92,7 @@ func (d *SqliteRepository) WriteNewUser(u entities.User) error {
return d.Queue.EnqueueWriteTx(queryFunc, params) return d.Queue.EnqueueWriteTx(queryFunc, params)
} }
func (d *SqliteRepository) UpdateUserNKode(u entities.User) error { func (d *SqliteNKodeRepo) UpdateUserNKode(u entities.User) error {
queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) error { queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) error {
params, ok := args.(sqlc.UpdateUserParams) params, ok := args.(sqlc.UpdateUserParams)
if !ok { if !ok {
@@ -126,7 +126,7 @@ func (d *SqliteRepository) UpdateUserNKode(u entities.User) error {
return d.Queue.EnqueueWriteTx(queryFunc, params) return d.Queue.EnqueueWriteTx(queryFunc, params)
} }
func (d *SqliteRepository) UpdateUserInterface(id entities.UserId, ui entities.UserInterface) error { func (d *SqliteNKodeRepo) UpdateUserInterface(id entities.UserId, ui entities.UserInterface) error {
queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) error { queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) error {
params, ok := args.(sqlc.UpdateUserInterfaceParams) params, ok := args.(sqlc.UpdateUserInterfaceParams)
if !ok { if !ok {
@@ -143,7 +143,7 @@ func (d *SqliteRepository) UpdateUserInterface(id entities.UserId, ui entities.U
return d.Queue.EnqueueWriteTx(queryFunc, params) return d.Queue.EnqueueWriteTx(queryFunc, params)
} }
func (d *SqliteRepository) UpdateUserRefreshToken(id entities.UserId, refreshToken string) error { func (d *SqliteNKodeRepo) UpdateUserRefreshToken(id entities.UserId, refreshToken string) error {
queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) error { queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) error {
params, ok := args.(sqlc.UpdateUserRefreshTokenParams) params, ok := args.(sqlc.UpdateUserRefreshTokenParams)
if !ok { if !ok {
@@ -161,7 +161,7 @@ func (d *SqliteRepository) UpdateUserRefreshToken(id entities.UserId, refreshTok
return d.Queue.EnqueueWriteTx(queryFunc, params) return d.Queue.EnqueueWriteTx(queryFunc, params)
} }
func (d *SqliteRepository) RenewCustomer(renewParams sqlc.RenewCustomerParams) error { func (d *SqliteNKodeRepo) RenewCustomer(renewParams sqlc.RenewCustomerParams) error {
queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) error { queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) error {
params, ok := args.(sqlc.RenewCustomerParams) params, ok := args.(sqlc.RenewCustomerParams)
if !ok { if !ok {
@@ -172,7 +172,7 @@ func (d *SqliteRepository) RenewCustomer(renewParams sqlc.RenewCustomerParams) e
return d.Queue.EnqueueWriteTx(queryFunc, renewParams) return d.Queue.EnqueueWriteTx(queryFunc, renewParams)
} }
func (d *SqliteRepository) Renew(id entities.CustomerId) error { func (d *SqliteNKodeRepo) Renew(id entities.CustomerId) error {
setXor, attrXor, err := d.renewCustomer(id) setXor, attrXor, err := d.renewCustomer(id)
if err != nil { if err != nil {
return err return err
@@ -224,7 +224,7 @@ func (d *SqliteRepository) Renew(id entities.CustomerId) error {
return nil return nil
} }
func (d *SqliteRepository) renewCustomer(id entities.CustomerId) ([]uint64, []uint64, error) { func (d *SqliteNKodeRepo) renewCustomer(id entities.CustomerId) ([]uint64, []uint64, error) {
customer, err := d.GetCustomer(id) customer, err := d.GetCustomer(id)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
@@ -253,7 +253,7 @@ func (d *SqliteRepository) renewCustomer(id entities.CustomerId) ([]uint64, []ui
return setXor, attrXor, nil return setXor, attrXor, nil
} }
func (d *SqliteRepository) RefreshUserPasscode(user entities.User, passcodeIdx []int, customerAttr entities.CustomerAttributes) error { func (d *SqliteNKodeRepo) RefreshUserPasscode(user entities.User, passcodeIdx []int, customerAttr entities.CustomerAttributes) error {
if err := user.RefreshPasscode(passcodeIdx, customerAttr); err != nil { if err := user.RefreshPasscode(passcodeIdx, customerAttr); err != nil {
return err return err
} }
@@ -278,7 +278,7 @@ func (d *SqliteRepository) RefreshUserPasscode(user entities.User, passcodeIdx [
return d.Queue.EnqueueWriteTx(queryFunc, params) return d.Queue.EnqueueWriteTx(queryFunc, params)
} }
func (d *SqliteRepository) AddSvg(svg string) error { func (d *SqliteNKodeRepo) AddSvg(svg string) error {
queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) error { queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) error {
params, ok := args.(string) params, ok := args.(string)
if !ok { if !ok {
@@ -289,7 +289,7 @@ func (d *SqliteRepository) AddSvg(svg string) error {
return d.Queue.EnqueueWriteTx(queryFunc, svg) return d.Queue.EnqueueWriteTx(queryFunc, svg)
} }
func (d *SqliteRepository) GetCustomer(id entities.CustomerId) (*entities.Customer, error) { func (d *SqliteNKodeRepo) GetCustomer(id entities.CustomerId) (*entities.Customer, error) {
customer, err := d.Queue.Queries.GetCustomer(d.ctx, uuid.UUID(id).String()) customer, err := d.Queue.Queries.GetCustomer(d.ctx, uuid.UUID(id).String())
if err != nil { if err != nil {
return nil, err return nil, err
@@ -309,7 +309,7 @@ func (d *SqliteRepository) GetCustomer(id entities.CustomerId) (*entities.Custom
}, nil }, nil
} }
func (d *SqliteRepository) GetUser(email entities.UserEmail, customerId entities.CustomerId) (*entities.User, error) { func (d *SqliteNKodeRepo) GetUser(email entities.UserEmail, customerId entities.CustomerId) (*entities.User, error) {
userRow, err := d.Queue.Queries.GetUser(d.ctx, sqlc.GetUserParams{ userRow, err := d.Queue.Queries.GetUser(d.ctx, sqlc.GetUserParams{
Email: string(email), Email: string(email),
CustomerID: uuid.UUID(customerId).String(), CustomerID: uuid.UUID(customerId).String(),
@@ -359,7 +359,7 @@ func (d *SqliteRepository) GetUser(email entities.UserEmail, customerId entities
return &user, nil return &user, nil
} }
func (d *SqliteRepository) RandomSvgInterface(kp entities.KeypadDimension) ([]string, error) { func (d *SqliteNKodeRepo) RandomSvgInterface(kp entities.KeypadDimension) ([]string, error) {
ids, err := d.getRandomIds(kp.TotalAttrs()) ids, err := d.getRandomIds(kp.TotalAttrs())
if err != nil { if err != nil {
return nil, err return nil, err
@@ -367,16 +367,16 @@ func (d *SqliteRepository) RandomSvgInterface(kp entities.KeypadDimension) ([]st
return d.getSvgsById(ids) return d.getSvgsById(ids)
} }
func (d *SqliteRepository) RandomSvgIdxInterface(kp entities.KeypadDimension) (entities.SvgIdInterface, error) { func (d *SqliteNKodeRepo) RandomSvgIdxInterface(kp entities.KeypadDimension) (entities.SvgIdInterface, error) {
return d.getRandomIds(kp.TotalAttrs()) return d.getRandomIds(kp.TotalAttrs())
} }
func (d *SqliteRepository) GetSvgStringInterface(idxs entities.SvgIdInterface) ([]string, error) { func (d *SqliteNKodeRepo) GetSvgStringInterface(idxs entities.SvgIdInterface) ([]string, error) {
return d.getSvgsById(idxs) return d.getSvgsById(idxs)
} }
// Is this even useful? // Is this even useful?
func (d *SqliteRepository) AddUserPermission(userEmail entities.UserEmail, customerId entities.CustomerId, permission entities.UserPermission) error { func (d *SqliteNKodeRepo) AddUserPermission(userEmail entities.UserEmail, customerId entities.CustomerId, permission entities.UserPermission) error {
user, err := d.GetUser(userEmail, customerId) user, err := d.GetUser(userEmail, customerId)
if err != nil { if err != nil {
return err return err
@@ -395,7 +395,7 @@ func (d *SqliteRepository) AddUserPermission(userEmail entities.UserEmail, custo
return d.Queue.EnqueueWriteTx(queryFunc, params) return d.Queue.EnqueueWriteTx(queryFunc, params)
} }
func (d *SqliteRepository) getSvgsById(ids []int) ([]string, error) { func (d *SqliteNKodeRepo) getSvgsById(ids []int) ([]string, error) {
svgs := make([]string, len(ids)) svgs := make([]string, len(ids))
for idx, id := range ids { for idx, id := range ids {
svg, err := d.Queue.Queries.GetSvgId(d.ctx, int64(id)) svg, err := d.Queue.Queries.GetSvgId(d.ctx, int64(id))
@@ -407,7 +407,7 @@ func (d *SqliteRepository) getSvgsById(ids []int) ([]string, error) {
return svgs, nil return svgs, nil
} }
func (d *SqliteRepository) getRandomIds(count int) ([]int, error) { func (d *SqliteNKodeRepo) getRandomIds(count int) ([]int, error) {
totalRows, err := d.Queue.Queries.GetSvgCount(d.ctx) totalRows, err := d.Queue.Queries.GetSvgCount(d.ctx)
if err != nil { if err != nil {
log.Print(err) log.Print(err)

View File

@@ -11,10 +11,10 @@ import (
func TestNewSqliteDB(t *testing.T) { func TestNewSqliteDB(t *testing.T) {
dbPath := os.Getenv("TEST_DB") dbPath := os.Getenv("TEST_DB")
ctx := context.Background() ctx := context.Background()
sqliteDb, err := NewSqliteRepository(ctx, dbPath) sqliteDb, err := NewSqliteNKodeRepo(ctx, dbPath)
assert.NoError(t, err) assert.NoError(t, err)
sqliteDb.Start() sqliteDb.Start()
defer func(t *testing.T, sqliteDb *SqliteRepository) { defer func(t *testing.T, sqliteDb *SqliteNKodeRepo) {
err := sqliteDb.Stop() err := sqliteDb.Stop()
assert.NoError(t, err) assert.NoError(t, err)
}(t, sqliteDb) }(t, sqliteDb)

View File

@@ -6,8 +6,43 @@ package sqlc
import ( import (
"database/sql" "database/sql"
"time"
) )
type AuthorizationCode struct {
ID int64
Code string
CodeChallenge string
CodeChallengeMethod string
UserID string
ClientID string
Scope sql.NullString
RedirectUri string
CreatedAt sql.NullTime
ExpiresAt time.Time
UsedAt sql.NullTime
}
type Client struct {
ID string
Name string
Owner string
CreatedAt sql.NullTime
}
type ClientApproval struct {
ID int64
UserID string
ClientID string
}
type ClientRedirect struct {
ID int64
Uri string
ClientID string
CreatedAt sql.NullTime
}
type Customer struct { type Customer struct {
ID string ID string
MaxNkodeLen int64 MaxNkodeLen int64
@@ -27,6 +62,17 @@ type SvgIcon struct {
Svg string Svg string
} }
type Token struct {
ID int64
TokenType string
TokenValue string
UserID string
ClientID string
Scope sql.NullString
CreatedAt sql.NullTime
ExpiresAt time.Time
}
type User struct { type User struct {
ID string ID string
Email string Email string

View File

@@ -8,6 +8,7 @@ package sqlc
import ( import (
"context" "context"
"database/sql" "database/sql"
"time"
) )
const addSvg = `-- name: AddSvg :exec const addSvg = `-- name: AddSvg :exec
@@ -33,6 +34,69 @@ func (q *Queries) AddUserPermission(ctx context.Context, arg AddUserPermissionPa
return err return err
} }
const approveClient = `-- name: ApproveClient :exec
INSERT INTO client_approvals (user_id, client_id)
VALUES (?, ?)
`
type ApproveClientParams struct {
UserID string
ClientID string
}
func (q *Queries) ApproveClient(ctx context.Context, arg ApproveClientParams) error {
_, err := q.db.ExecContext(ctx, approveClient, arg.UserID, arg.ClientID)
return err
}
const clientApproved = `-- name: ClientApproved :one
SELECT id, user_id, client_id
FROM client_approvals
WHERE user_id = ? AND client_id = ?
`
type ClientApprovedParams struct {
UserID string
ClientID string
}
func (q *Queries) ClientApproved(ctx context.Context, arg ClientApprovedParams) (ClientApproval, error) {
row := q.db.QueryRowContext(ctx, clientApproved, arg.UserID, arg.ClientID)
var i ClientApproval
err := row.Scan(&i.ID, &i.UserID, &i.ClientID)
return i, err
}
const createAuthorizationCode = `-- name: CreateAuthorizationCode :exec
INSERT INTO authorization_codes (code, code_challenge, code_challenge_method, user_id, client_id, scope, redirect_uri, expires_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`
type CreateAuthorizationCodeParams struct {
Code string
CodeChallenge string
CodeChallengeMethod string
UserID string
ClientID string
Scope sql.NullString
RedirectUri string
ExpiresAt time.Time
}
func (q *Queries) CreateAuthorizationCode(ctx context.Context, arg CreateAuthorizationCodeParams) error {
_, err := q.db.ExecContext(ctx, createAuthorizationCode,
arg.Code,
arg.CodeChallenge,
arg.CodeChallengeMethod,
arg.UserID,
arg.ClientID,
arg.Scope,
arg.RedirectUri,
arg.ExpiresAt,
)
return err
}
const createCustomer = `-- name: CreateCustomer :exec const createCustomer = `-- name: CreateCustomer :exec
INSERT INTO customer ( INSERT INTO customer (
id id
@@ -81,6 +145,63 @@ func (q *Queries) CreateCustomer(ctx context.Context, arg CreateCustomerParams)
return err return err
} }
const createOIDCClient = `-- name: CreateOIDCClient :exec
INSERT INTO clients (id, name, owner)
VALUES (?, ?, ?)
`
type CreateOIDCClientParams struct {
ID string
Name string
Owner string
}
func (q *Queries) CreateOIDCClient(ctx context.Context, arg CreateOIDCClientParams) error {
_, err := q.db.ExecContext(ctx, createOIDCClient, arg.ID, arg.Name, arg.Owner)
return err
}
const createRedirectURI = `-- name: CreateRedirectURI :exec
INSERT INTO client_redirects (uri, client_id)
VALUES (?, ?)
`
type CreateRedirectURIParams struct {
Uri string
ClientID string
}
func (q *Queries) CreateRedirectURI(ctx context.Context, arg CreateRedirectURIParams) error {
_, err := q.db.ExecContext(ctx, createRedirectURI, arg.Uri, arg.ClientID)
return err
}
const createToken = `-- name: CreateToken :exec
INSERT INTO tokens (token_type, token_value, user_id, client_id, scope, expires_at)
VALUES (?, ?, ?, ?, ?, ?)
`
type CreateTokenParams struct {
TokenType string
TokenValue string
UserID string
ClientID string
Scope sql.NullString
ExpiresAt time.Time
}
func (q *Queries) CreateToken(ctx context.Context, arg CreateTokenParams) error {
_, err := q.db.ExecContext(ctx, createToken,
arg.TokenType,
arg.TokenValue,
arg.UserID,
arg.ClientID,
arg.Scope,
arg.ExpiresAt,
)
return err
}
const createUser = `-- name: CreateUser :exec const createUser = `-- name: CreateUser :exec
INSERT INTO user ( INSERT INTO user (
id id
@@ -150,6 +271,110 @@ func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) error {
return err return err
} }
const deleteAuthCode = `-- name: DeleteAuthCode :exec
DELETE FROM authorization_codes
WHERE code = ?
`
func (q *Queries) DeleteAuthCode(ctx context.Context, code string) error {
_, err := q.db.ExecContext(ctx, deleteAuthCode, code)
return err
}
const deleteOldAuthCodes = `-- name: DeleteOldAuthCodes :exec
DELETE FROM authorization_codes
WHERE expires_at < CURRENT_TIMESTAMP
`
func (q *Queries) DeleteOldAuthCodes(ctx context.Context) error {
_, err := q.db.ExecContext(ctx, deleteOldAuthCodes)
return err
}
const deleteOldTokens = `-- name: DeleteOldTokens :exec
DELETE FROM tokens
WHERE expires_at < CURRENT_TIMESTAMP
`
func (q *Queries) DeleteOldTokens(ctx context.Context) error {
_, err := q.db.ExecContext(ctx, deleteOldTokens)
return err
}
const deleteRedirectURI = `-- name: DeleteRedirectURI :exec
DELETE FROM client_redirects
WHERE uri = ? AND client_id = ?
`
type DeleteRedirectURIParams struct {
Uri string
ClientID string
}
func (q *Queries) DeleteRedirectURI(ctx context.Context, arg DeleteRedirectURIParams) error {
_, err := q.db.ExecContext(ctx, deleteRedirectURI, arg.Uri, arg.ClientID)
return err
}
const getAuthorizationCode = `-- name: GetAuthorizationCode :one
SELECT id, code, code_challenge, code_challenge_method, user_id, client_id, scope, redirect_uri, created_at, expires_at, used_at
FROM authorization_codes
WHERE code = ?
`
func (q *Queries) GetAuthorizationCode(ctx context.Context, code string) (AuthorizationCode, error) {
row := q.db.QueryRowContext(ctx, getAuthorizationCode, code)
var i AuthorizationCode
err := row.Scan(
&i.ID,
&i.Code,
&i.CodeChallenge,
&i.CodeChallengeMethod,
&i.UserID,
&i.ClientID,
&i.Scope,
&i.RedirectUri,
&i.CreatedAt,
&i.ExpiresAt,
&i.UsedAt,
)
return i, err
}
const getClientRedirectURIs = `-- name: GetClientRedirectURIs :many
SELECT id, uri, client_id, created_at
FROM client_redirects
WHERE client_id = ?
`
func (q *Queries) GetClientRedirectURIs(ctx context.Context, clientID string) ([]ClientRedirect, error) {
rows, err := q.db.QueryContext(ctx, getClientRedirectURIs, clientID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ClientRedirect
for rows.Next() {
var i ClientRedirect
if err := rows.Scan(
&i.ID,
&i.Uri,
&i.ClientID,
&i.CreatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const getCustomer = `-- name: GetCustomer :one const getCustomer = `-- name: GetCustomer :one
SELECT SELECT
max_nkode_len max_nkode_len
@@ -191,6 +416,24 @@ func (q *Queries) GetCustomer(ctx context.Context, id string) (GetCustomerRow, e
return i, err return i, err
} }
const getOIDCClientByID = `-- name: GetOIDCClientByID :one
SELECT id, name, owner, created_at
FROM clients
WHERE id = ?
`
func (q *Queries) GetOIDCClientByID(ctx context.Context, id string) (Client, error) {
row := q.db.QueryRowContext(ctx, getOIDCClientByID, id)
var i Client
err := row.Scan(
&i.ID,
&i.Name,
&i.Owner,
&i.CreatedAt,
)
return i, err
}
const getSvgCount = `-- name: GetSvgCount :one const getSvgCount = `-- name: GetSvgCount :one
SELECT COUNT(*) as count FROM svg_icon SELECT COUNT(*) as count FROM svg_icon
` `
@@ -215,6 +458,28 @@ func (q *Queries) GetSvgId(ctx context.Context, id int64) (string, error) {
return svg, err return svg, err
} }
const getTokenByValue = `-- name: GetTokenByValue :one
SELECT id, token_type, token_value, user_id, client_id, scope, created_at, expires_at
FROM tokens
WHERE token_value = ?
`
func (q *Queries) GetTokenByValue(ctx context.Context, tokenValue string) (Token, error) {
row := q.db.QueryRowContext(ctx, getTokenByValue, tokenValue)
var i Token
err := row.Scan(
&i.ID,
&i.TokenType,
&i.TokenValue,
&i.UserID,
&i.ClientID,
&i.Scope,
&i.CreatedAt,
&i.ExpiresAt,
)
return i, err
}
const getUser = `-- name: GetUser :one const getUser = `-- name: GetUser :one
SELECT SELECT
id id
@@ -282,6 +547,42 @@ func (q *Queries) GetUser(ctx context.Context, arg GetUserParams) (GetUserRow, e
return i, err return i, err
} }
const getUserClients = `-- name: GetUserClients :many
SELECT id, name, owner, created_at
FROM clients
WHERE owner = ?
`
// -------- go-oidc
func (q *Queries) GetUserClients(ctx context.Context, owner string) ([]Client, error) {
rows, err := q.db.QueryContext(ctx, getUserClients, owner)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Client
for rows.Next() {
var i Client
if err := rows.Scan(
&i.ID,
&i.Name,
&i.Owner,
&i.CreatedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const getUserPermissions = `-- name: GetUserPermissions :many const getUserPermissions = `-- name: GetUserPermissions :many
SELECT permission FROM user_permission WHERE user_id = ? SELECT permission FROM user_permission WHERE user_id = ?
` `

View File

@@ -143,3 +143,72 @@ SELECT permission FROM user_permission WHERE user_id = ?;
-- name: AddUserPermission :exec -- name: AddUserPermission :exec
INSERT INTO user_permission (user_id, permission) VALUES (?, ?); INSERT INTO user_permission (user_id, permission) VALUES (?, ?);
---------- go-oidc
-- name: GetUserClients :many
SELECT *
FROM clients
WHERE owner = ?;
-- name: GetOIDCClientByID :one
SELECT *
FROM clients
WHERE id = ?;
-- name: CreateOIDCClient :exec
INSERT INTO clients (id, name, owner)
VALUES (?, ?, ?);
-- name: CreateRedirectURI :exec
INSERT INTO client_redirects (uri, client_id)
VALUES (?, ?);
-- name: DeleteRedirectURI :exec
DELETE FROM client_redirects
WHERE uri = ? AND client_id = ?;
-- name: GetClientRedirectURIs :many
SELECT *
FROM client_redirects
WHERE client_id = ?;
-- name: GetAuthorizationCode :one
SELECT *
FROM authorization_codes
WHERE code = ?;
-- name: CreateAuthorizationCode :exec
INSERT INTO authorization_codes (code, code_challenge, code_challenge_method, user_id, client_id, scope, redirect_uri, expires_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?);
-- name: DeleteOldAuthCodes :exec
DELETE FROM authorization_codes
WHERE expires_at < CURRENT_TIMESTAMP;
-- name: DeleteOldTokens :exec
DELETE FROM tokens
WHERE expires_at < CURRENT_TIMESTAMP;
-- name: GetTokenByValue :one
SELECT *
FROM tokens
WHERE token_value = ?;
-- name: CreateToken :exec
INSERT INTO tokens (token_type, token_value, user_id, client_id, scope, expires_at)
VALUES (?, ?, ?, ?, ?, ?);
-- name: ApproveClient :exec
INSERT INTO client_approvals (user_id, client_id)
VALUES (?, ?);
-- name: ClientApproved :one
SELECT *
FROM client_approvals
WHERE user_id = ? AND client_id = ?;
-- name: DeleteAuthCode :exec
DELETE FROM authorization_codes
WHERE code = ?;

View File

@@ -64,3 +64,62 @@ CREATE TABLE IF NOT EXISTS user_permission (
,FOREIGN KEY (user_id) REFERENCES user(id) ,FOREIGN KEY (user_id) REFERENCES user(id)
,UNIQUE(user_id, permission) ,UNIQUE(user_id, permission)
); );
---- go-oidc
CREATE TABLE IF NOT EXISTS clients (
id TEXT PRIMARY KEY
,name TEXT NOT NULL
,owner TEXT NOT NULL
,created_at DATETIME DEFAULT CURRENT_TIMESTAMP
,FOREIGN KEY (owner) REFERENCES user (id)
,UNIQUE(name, owner)
);
CREATE TABLE IF NOT EXISTS client_redirects (
id INTEGER PRIMARY KEY AUTOINCREMENT
,uri TEXT NOT NULL
,client_id TEXT NOT NULL
,created_at DATETIME DEFAULT CURRENT_TIMESTAMP
,FOREIGN KEY (client_id) REFERENCES clients (id)
,UNIQUE(uri, client_id)
);
CREATE TABLE IF NOT EXISTS authorization_codes (
id INTEGER PRIMARY KEY AUTOINCREMENT
,code TEXT NOT NULL UNIQUE
,code_challenge TEXT NOT NULL UNIQUE
,code_challenge_method TEXT NOT NULL CHECK (code_challenge_method IN ('S256', 'plain'))
,user_id TEXT NOT NULL
,client_id TEXT NOT NULL
,scope TEXT
,redirect_uri TEXT NOT NULL
,created_at DATETIME DEFAULT CURRENT_TIMESTAMP
,expires_at DATETIME NOT NULL
,used_at DATETIME
,FOREIGN KEY (user_id) REFERENCES user (id)
,FOREIGN KEY (client_id) REFERENCES client (id)
);
CREATE TABLE IF NOT EXISTS tokens (
id INTEGER PRIMARY KEY AUTOINCREMENT
,token_type TEXT NOT NULL CHECK (token_type IN ('access', 'refresh'))
,token_value TEXT NOT NULL UNIQUE
,user_id TEXT NOT NULL
,client_id TEXT NOT NULL
,scope TEXT
,created_at DATETIME DEFAULT CURRENT_TIMESTAMP
,expires_at DATETIME NOT NULL
,FOREIGN KEY (user_id) REFERENCES user (id)
,FOREIGN KEY (client_id) REFERENCES clients (id)
);
CREATE TABLE IF NOT EXISTS client_approvals (
id INTEGER PRIMARY KEY AUTOINCREMENT
,user_id TEXT NOT NULL
,client_id TEXT NOT NULL
,UNIQUE(user_id, client_id)
,FOREIGN KEY (user_id) REFERENCES users (id)
,FOREIGN KEY (client_id) REFERENCES clients (id)
);