diff --git a/ensureuserisroot.go b/checkuser.go similarity index 75% rename from ensureuserisroot.go rename to checkuser.go index 237cb71..e8f2a16 100644 --- a/ensureuserisroot.go +++ b/checkuser.go @@ -21,14 +21,19 @@ import ( "os/user" ) -func ensureUserIsRoot() error { - user, err := user.Current() +func checkUser(username string) error { + cur, err := user.Current() if err != nil { return err } - if user.Uid != "0" { - return fmt.Errorf("must be run as root") + other, err := user.Lookup(username) + if err != nil { + return err + } + + if cur.Uid != other.Uid { + return fmt.Errorf("must be run as %s", username) } return nil diff --git a/instance.go b/instance.go index 1243f4b..a8caae5 100644 --- a/instance.go +++ b/instance.go @@ -385,7 +385,12 @@ func (i *Instance) ExecuteAsManager() error { // This command only functions if the calling program is running as root. // It returns any error encountered. func (i *Instance) ExecuteAsUser(execUser string) error { - if err := ensureUserIsRoot(); err != nil { + // no need to switch users if we're already who we want to be + if err := checkUser(execUser); err == nil { + return nil + } + + if err := checkUser("root"); err != nil { return err }