Created
May 31, 2023 18:22
-
-
Save korylprince/67c66156030b13f2d6cadb12fa7b14ef to your computer and use it in GitHub Desktop.
Get console user on macOS using SCDynamicStoreCopyConsoleUser
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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