Sample Header Ad - 728x90

How create a row-level policy for purposes of using a new_user_id as a fk entry to another table

0 votes
1 answer
1283 views
I have row-level security enabled on my users table. The table is part of a core schema. I have the following policy that provides access by the api user:
create policy "Api(public) can view record when id=current_user_id"
    on core.users
    for all
    to api
    using(current_user_id() = id)
    with check (true);
However, the following procedure/function to register a new user violates the row-level security.
create or replace
function api.register(
    auth_agent core.auth_agent,
    auth_id text,
    email text
)
returns void as $$
    declare
        new_user_id uuid;
    begin
        raise info '👉 api.register: 🙂%', current_user;
        -- create a new users record
        insert into core.users (email)
        values (register.email)
        returning id into new_user_id; -- << Error causing

        -- create a new entry in the auth_ids_link_user
        insert into core.auth_ids_link_user (auth_agent, auth_id, user_id)
        values (auth_agent, auth_id, new_user_id);

        -- login using the new record
        perform api.login(auth_agent, auth_id);
    end;
$$ security definer language plpgsql;
... the error:
new row violates row-level security policy for table "users"
CONTEXT:  SQL statement "insert into core.users (email)
        values (register.email)
What is the the correct policy that 1. allows the api only to view the row/record where id = current_user_id() 2. lets the api use the core.users.id value to insert a new record in a table that uses the id as a fk Thank you in advance to providing where there is surely an "idiomatic" way to do this.
Asked by Edmund&#39;s Echo (133 rep)
Feb 15, 2022, 05:37 PM
Last activity: Feb 5, 2025, 11:05 AM