Reputation: 151
I'm a developer for a cross platform Java application. I know virtually nothing about OS X. We have a general method isAdmin() that's used to determine if the current process has administrator/root privileges. This information is then used various other places in the application to determine which options to present or action to take for privileged operations.
We have working ways to check this for Windows and Linux, but until now this simply returns "true" for OS X. That works most of the time since the first user created in OS X automaticly has administrator privileges and I'm guessing that most OS X usage scenarios is single user in practice. It's not a proper solution however, and I'd like to fix this.
I don't think there's a pure Java way to do this, so running an external process and parsing the result is acceptable. We store the result so the query is only done once per session.
My understanding is that administrator privileges is not the same as root privileges in the underlying BSD base of OS X, but something Apple has built on top. It's not quite clear to me what the difference, but it seems that an administrator account has sudo privileges, so determining sudo privileges might be a way.
How do I determine if the current process has administrator privileges? I'm not wondering if the process is currently elevated, but if the user it runs as has the potential to elevate.
Upvotes: 1
Views: 766
Reputation: 151
Based on mattinbits suggestion, I ended up with the following Java code:
public boolean isAdmin() {
if (Platform.isMac()) {
try {
Process p = Runtime.getRuntime().exec("id -Gn");
InputStream is = p.getInputStream();
InputStreamReader isr = new InputStreamReader(is, StandardCharsets.US_ASCII);
BufferedReader br = new BufferedReader(isr);
p.waitFor();
int exitValue = p.exitValue();
String exitLine = br.readLine();
if (exitValue != 0 || exitLine == null || exitLine.isEmpty()) {
HandleError..
return false;
}
if (exitLine.matches(".*\\badmin\\b.*")) {
return true;
}
return false;
} catch (IOException | InterruptedException e) {
HandleError..
}
}
}
Upvotes: 0