Skip to content

Instantly share code, notes, and snippets.

@korylprince
Created May 31, 2023 18:22
Show Gist options
  • Save korylprince/67c66156030b13f2d6cadb12fa7b14ef to your computer and use it in GitHub Desktop.
Save korylprince/67c66156030b13f2d6cadb12fa7b14ef to your computer and use it in GitHub Desktop.
Get console user on macOS using SCDynamicStoreCopyConsoleUser
package main
import (
"fmt"
"os/user"
"strconv"
)
//#cgo LDFLAGS: -framework SystemConfiguration
/*
#import <SystemConfiguration/SystemConfiguration.h>
struct user_info {
uid_t uid;
gid_t gid;
int error_code;
const char * error;
};
struct user_info get_console_user() {
struct user_info info;
CFStringRef ref = SCDynamicStoreCopyConsoleUser(NULL, &info.uid, &info.gid);
if (ref == NULL) {
int code = SCError();
if (code != kSCStatusOK) {
info.error_code = code;
info.error = SCErrorString(code);
}
} else {
CFRelease(ref);
}
return info;
}
*/
import "C"
func GetConsoleUserID() (uid, gid int, err error) {
info := C.get_console_user()
if errstr := C.GoString(info.error); len(errstr) > 0 {
err = fmt.Errorf("%s (SCError: %d)", errstr, info.error_code)
}
return int(info.uid), int(info.gid), err
}
func main() {
uid, gid, err := GetConsoleUserID()
if err != nil {
panic(fmt.Errorf("could get console user id: %w", err))
}
usr, err := user.LookupId(strconv.Itoa(uid))
if err != nil {
panic(fmt.Errorf("could not look up user: %w", err))
}
fmt.Println("User:", usr.Username)
grp, err := user.LookupGroupId(strconv.Itoa(gid))
if err != nil {
panic(fmt.Errorf("could not look up group: %w", err))
}
fmt.Println("Group:", grp.Name)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment