Skip to content

Commit

Permalink
Allow using DataSync without a user session
Browse files Browse the repository at this point in the history
  • Loading branch information
mpscholten committed Jan 26, 2022
1 parent 5f67c9c commit 9c83b81
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
12 changes: 11 additions & 1 deletion IHP/DataSync/RowLevelSecurity.hs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,17 @@ withRLS callback = withTransaction inner
inner = do
let maybeUserId :: Maybe userId = get #id <$> currentUserOrNothing
sqlExec "SET LOCAL ROLE ?" [PG.Identifier Role.authenticatedRole]
sqlExec "SET LOCAL rls.ihp_user_id = ?" (PG.Only maybeUserId)

-- When the user is not logged in and maybeUserId is Nothing, we cannot
-- just pass @NULL@ to postgres. The @SET LOCAL@ values can only be strings.
--
-- Therefore we map Nothing to an empty string here. The empty string
-- means "not logged in".
--
let encodedUserId = case maybeUserId of
Just userId -> PG.toField userId
Nothing -> PG.toField ("" :: Text)
sqlExec "SET LOCAL rls.ihp_user_id = ?" (PG.Only encodedUserId)
callback

-- | Returns a proof that RLS is enabled for a table
Expand Down
2 changes: 1 addition & 1 deletion lib/IHP/IHPSchema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ CREATE TYPE JOB_STATUS AS ENUM ('job_status_not_started', 'job_status_running',

-- Used by IHP.DataSync
CREATE FUNCTION ihp_user_id() RETURNS UUID AS $$
SELECT current_setting('rls.ihp_user_id')::uuid;
SELECT NULLIF(current_setting('rls.ihp_user_id'), '')::uuid;
$$ LANGUAGE SQL;

0 comments on commit 9c83b81

Please sign in to comment.