Put `getUsername` and `getHostname` functions into common code which can be reused
Right now there are several definitions of these two functions, which are all the same, in different places. We shouldn't have to duplicate this code. (see !867 (comment 9383159))