Created
October 20, 2024 17:57
-
-
Save tmountain/7a4d6755ef2e8da0253cce5ed3713aee to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- call auth.login_as_user('[email protected]'); | |
create or replace procedure auth.login_as_user(user_email text) | |
language plpgsql | |
as $$ | |
declare | |
auth_user auth.users; | |
event_jsonb jsonb; | |
result_event jsonb; | |
begin | |
select | |
* into auth_user | |
from | |
auth.users | |
where | |
email = user_email; | |
-- Prepare event JSON with the basic user information and empty metadata | |
event_jsonb := jsonb_build_object( | |
'claims', jsonb_build_object( | |
'app_metadata', jsonb_build_object() | |
), | |
'user_id', auth_user.id, | |
'authentication_method', 'password' -- Assuming password authentication | |
); | |
-- Call the custom access token hook function | |
result_event := public.custom_access_token_hook(event_jsonb); | |
-- Extract and set the session variables from the result | |
execute format('set request.jwt.claim.sub=%L', auth_user.id::text); | |
execute format('set request.jwt.claim.role=%I', auth_user.role); | |
execute format('set request.jwt.claim.email=%L', auth_user.email); | |
execute format('set request.jwt.claims=%L', result_event -> 'claims'::text); | |
-- Log the results | |
raise notice '%', format('User logged in with updated claims: %s', result_event -> 'claims'); | |
-- Set the role as usual | |
execute format('set role %I', auth_user.role); | |
end; | |
$$; | |
-- call auth.login_as_anon(); | |
create or replace procedure auth.login_as_anon() | |
language plpgsql | |
as $$ | |
begin | |
set request.jwt.claim.sub=''; | |
set request.jwt.claim.role=''; | |
set request.jwt.claim.email=''; | |
set request.jwt.claims=''; | |
set role anon; | |
end; | |
$$; | |
-- call auth.logout(); | |
create or replace procedure auth.logout() | |
language plpgsql | |
as $$ | |
begin | |
set request.jwt.claim.sub=''; | |
set request.jwt.claim.role=''; | |
set request.jwt.claim.email=''; | |
set request.jwt.claims=''; | |
set role postgres; | |
end; | |
$$; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment