2024-01-17 15:00:28 +00:00
|
|
|
//go:build darwin
|
|
|
|
|
// +build darwin
|
|
|
|
|
|
|
|
|
|
package user
|
|
|
|
|
|
|
|
|
|
import (
|
2025-03-20 14:49:23 +00:00
|
|
|
"bytes"
|
2024-01-17 15:00:28 +00:00
|
|
|
"os/exec"
|
2025-03-20 14:49:23 +00:00
|
|
|
"regexp"
|
2024-01-17 15:00:28 +00:00
|
|
|
)
|
|
|
|
|
|
2025-03-20 14:49:23 +00:00
|
|
|
var re = regexp.MustCompile(`\s+Name : (\S+)`)
|
2024-01-17 15:00:28 +00:00
|
|
|
|
2025-03-20 14:49:23 +00:00
|
|
|
// UserLoggedInViaGui returns the name of the user logged into the machine via the GUI.
|
|
|
|
|
func UserLoggedInViaGui() (*string, error) {
|
|
|
|
|
// Attempt to get the console user.
|
|
|
|
|
cmd := exec.Command("/bin/sh", "-c", `scutil <<< "show State:/Users/ConsoleUser"`)
|
|
|
|
|
var out bytes.Buffer
|
|
|
|
|
cmd.Stdout = &out
|
|
|
|
|
err := cmd.Run()
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
2024-01-17 15:00:28 +00:00
|
|
|
}
|
|
|
|
|
|
2025-03-20 14:49:23 +00:00
|
|
|
// Extract all "Name : username" entries, and return the first one that
|
|
|
|
|
// isn't _mbsetupuser (if any).
|
|
|
|
|
matches := re.FindAllStringSubmatch(out.String(), -1)
|
|
|
|
|
|
|
|
|
|
for _, match := range matches {
|
|
|
|
|
if len(match) > 1 && match[1] != "" && match[1] != "_mbsetupuser" {
|
|
|
|
|
return &match[1], nil
|
|
|
|
|
}
|
2024-01-17 15:00:28 +00:00
|
|
|
}
|
|
|
|
|
|
2025-03-20 14:49:23 +00:00
|
|
|
// No valid user found
|
|
|
|
|
return nil, nil
|
2024-01-17 15:00:28 +00:00
|
|
|
}
|