Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if have got sudo right info

Tags:

node.js

Is it possible to detect that I have the right sudo when I run

node app.js

I hope that when I run the command

sudo node app.js

it will tell me that the app.js node is running with the right sudo.

like image 625
arachide Avatar asked Nov 02 '25 07:11

arachide


2 Answers

I can't ensure this is correct since I currently have no way of testing it but if I remember correctly you should be able to use the getuid() function from the process package (Documentation).
(Note: This only works on POSIX platforms, which means no Windows)

This should return "root" when you run the command with super user permissions.

IMPORTANT You should never run a webserver like node with super user permissions. If you need the permissions for some setup work you should revert the granted root permissions by doing something like this at the end of your initialization work:

var uid = parseInt(process.env.SUDO_UID);
if (uid) process.setuid(uid);
like image 92
Sascha Wolf Avatar answered Nov 04 '25 12:11

Sascha Wolf


I found the accepted answer confusing. Coming from that, and based on some personal testing, the following code works:

function isRoot() {
    return !!process.env.SUDO_UID; // SUDO_UID is undefined when not root
}

as well as this:

function isRoot() {
    return !process.getuid(); // getuid() returns 0 for root
}
like image 33
electrovir Avatar answered Nov 04 '25 11:11

electrovir