Add CreatedBy value in apikeys

This commit is contained in:
Zoe Roux 2025-04-23 22:45:39 +02:00
parent dcbbb6352a
commit 667249bc81
No known key found for this signature in database
5 changed files with 28 additions and 10 deletions

View File

@ -85,10 +85,22 @@ func (h *Handler) CreateApiKey(c echo.Context) error {
return err
}
var user *int32
uid, err :=GetCurrentUserId(c)
// if err, we probably are using an api key (so no user)
if err != nil {
u, _ := h.db.GetUser(context.Background(), dbc.GetUserParams{
UseId: true,
Id: uid,
})
user = &u[0].User.Pk
}
dbkey, err := h.db.CreateApiKey(context.Background(), dbc.CreateApiKeyParams{
Name: req.Name,
Token: base64.RawURLEncoding.EncodeToString(id),
Claims: req.Claims,
CreatedBy: user,
})
if ErrIs(err, pgerrcode.UniqueViolation) {
return echo.NewHTTPError(409, "An apikey with the same name already exists.")

View File

@ -13,20 +13,26 @@ import (
)
const createApiKey = `-- name: CreateApiKey :one
insert into apikeys(name, token, claims)
values ($1, $2, $3)
insert into apikeys(name, token, claims, created_by)
values ($1, $2, $3, $4)
returning
pk, id, name, token, claims, created_by, created_at, last_used
`
type CreateApiKeyParams struct {
Name string `json:"name"`
Token string `json:"token"`
Claims jwt.MapClaims `json:"claims"`
Name string `json:"name"`
Token string `json:"token"`
Claims jwt.MapClaims `json:"claims"`
CreatedBy *int32 `json:"createdBy"`
}
func (q *Queries) CreateApiKey(ctx context.Context, arg CreateApiKeyParams) (Apikey, error) {
row := q.db.QueryRow(ctx, createApiKey, arg.Name, arg.Token, arg.Claims)
row := q.db.QueryRow(ctx, createApiKey,
arg.Name,
arg.Token,
arg.Claims,
arg.CreatedBy,
)
var i Apikey
err := row.Scan(
&i.Pk,

View File

@ -17,7 +17,7 @@ type Apikey struct {
Name string `json:"name"`
Token string `json:"token"`
Claims jwt.MapClaims `json:"claims"`
CreatedBy int32 `json:"createdBy"`
CreatedBy *int32 `json:"createdBy"`
CreatedAt time.Time `json:"createdAt"`
LastUsed time.Time `json:"lastUsed"`
}

View File

@ -7,7 +7,7 @@ create table apikeys(
token varchar(128) not null unique,
claims jsonb not null,
created_by integer not null references users(pk) on delete cascade,
created_by integer references users(pk) on delete cascade,
created_at timestamptz not null default now()::timestamptz,
last_used timestamptz not null default now()::timestamptz
);

View File

@ -24,8 +24,8 @@ order by
last_used;
-- name: CreateApiKey :one
insert into apikeys(name, token, claims)
values ($1, $2, $3)
insert into apikeys(name, token, claims, created_by)
values ($1, $2, $3, $4)
returning
*;