Files
OMT-SM/server/db/init/99_seed_admin.sh
T

59 lines
1.9 KiB
Bash
Executable File

#!/usr/bin/env bash
# Seed (or reset) the default admin user, default shop, owner role, Till 1.
set -euo pipefail
ADMIN_EMAIL="${ADMIN_EMAIL:-admin@local.test}"
ADMIN_PASSWORD="${ADMIN_PASSWORD:-ChangeMe123!}"
ADMIN_NAME="${ADMIN_NAME:-Local Admin}"
echo ">> seeding admin user: ${ADMIN_EMAIL}"
# Use psql -v to safely substitute values inside the DO block via :'name' --
# but :'name' only works at top level. So we generate plain SQL with the
# values inlined as quoted literals (escaping single quotes).
escape() { printf "%s" "$1" | sed "s/'/''/g"; }
EM=$(escape "$ADMIN_EMAIL")
PW=$(escape "$ADMIN_PASSWORD")
NM=$(escape "$ADMIN_NAME")
psql -v ON_ERROR_STOP=1 \
--username "$POSTGRES_USER" \
--dbname "$POSTGRES_DB" <<SQL
do \$\$
declare
v_user_id uuid;
v_shop_id uuid;
begin
insert into auth.users(email, password_hash, full_name, is_system_admin, is_active)
values ('${EM}', crypt('${PW}', gen_salt('bf', 10)), '${NM}', true, true)
on conflict (email) do update
set password_hash = excluded.password_hash,
full_name = excluded.full_name,
is_system_admin = true,
is_active = true
returning id into v_user_id;
insert into app.user_profiles(user_id, full_name, is_active)
values (v_user_id, '${NM}', true)
on conflict (user_id) do update
set full_name = excluded.full_name,
is_active = true;
insert into app.shops(name, created_by)
values ('Default Shop', v_user_id)
on conflict do nothing;
select id into v_shop_id from app.shops where name = 'Default Shop' limit 1;
insert into app.user_shop_assignments(user_id, shop_id, role, assigned_by)
values (v_user_id, v_shop_id, 'owner', v_user_id)
on conflict (user_id, shop_id) do update set role = 'owner';
insert into app.tills(shop_id, name)
values (v_shop_id, 'Till 1')
on conflict (shop_id, name) do nothing;
end \$\$;
SQL
echo ">> admin user ensured: ${ADMIN_EMAIL}"