title: Recording the invoker of a Postgres function that is set to SECURITY DEFINER
body: <p>Is there a way for a function in Postgres (using 9.4) to find out the user that invoked it if the function is set to <code>SECURITY DEFINER</code>?</p>
  
  <p>The design problem that I have is that I want to do user authentication via my web app (so that I can share a connection pool) but still maintain audit records within the database that reference the authenticated end user from the web app.</p>
  
  <p>The current flow is:</p>
  
  <ul>
  <li>Users connect to a web app, and it does the authentication to verify that they are who they say they are.</li>
  <li>The web app then connects to Postgres via an app user.</li>
  <li>When any queries are executed on behalf of a user, the web app runs a <code>SET ROLE [username]</code>, then the relevant query, then a <code>RESET ROLE</code> before returning the connection to the connection pool.</li>
  <li>All user queries are done via functions. The users have privileges to run the functions but do not have privileges to make changes to tables directly (the web app account has no permissions except for the permission to impersonate certain users). The functions also maintain columns for concepts like "created by", "last updated", etc. by inserting/updating the appropriate values with <code>CURRENT_USER</code> and <code>CURRENT_TIMESTAMP</code>.</li>
  </ul>
  
  <p>The problem that I'm running into is that the <code>CURRENT_USER</code> always returns the function owner, and <code>SESSION_USER</code> always returns the web app account, whereas what I really want is the name of the account that invoked the function.</p>
  
  <p>Is this possible? I'm not seeing anything particularly promising in the documentation. Conversely, how have other people solved this design problem?</p>