You cannot, for the general case, because PostgreSQL talks to the client over a network socket. There is no reliable way to determine the operating system user name from a TCP/IP connection from a remote host.
For unix domain sockets it's possible to require that the connecting user be the same as the PostgreSQL user using peer
mode authentication. PostgreSQL doesn't expose the client OS username from a unix domain socket to SQL, so if you use another authentication method you can't easily find out their username even if they connected over a unix domain socket.
For loopback TCP/IP connections the host OS might run an identd, though these days almost none do. This might allow PostgreSQL to ask the other end what the username is. It supports this via the ident
auth method, but like peer
, you can't ask for the OS username from SQL once the user is connected.
For other users you can't reliably find out what user they are on the host OS. You would have to just trust what the client told you, and it's trivial to modify the client to lie.
You can't even get this information using a C extension function, since PostgreSQL doesn't remember it after authentication completes, and for most authentication methods it never asks the client for it in the first place. This would require protocol changes. Since the client can just lie about the host OS username, there doesn't seem to be much point.
If you want to authenticate client identity, SSL client certificates or Kerberos (SSPI, on Windows) authentication would be a better option.