github.com/keybase/client/go@v0.0.0-20241007131713-f10651d043c8/kbnm/hostmanifest/user.go (about)

     1  package hostmanifest
     2  
     3  import (
     4  	"os/user"
     5  )
     6  
     7  // User is an interface for an OS user.
     8  type User interface {
     9  	// IsAdmin returns true if the user is root, usually uid == 0
    10  	IsAdmin() bool
    11  	// PrefixPath is where paths relative to that user should be. Usually $HOME.
    12  	PrefixPath() string
    13  }
    14  
    15  // UserPath is a straightforward implementation of User.
    16  type UserPath struct {
    17  	Admin bool
    18  	Path  string
    19  }
    20  
    21  // IsAdmin implements User.
    22  func (u *UserPath) IsAdmin() bool { return u.Admin }
    23  
    24  // PrefixPath implements User.
    25  func (u *UserPath) PrefixPath() string { return u.Path }
    26  
    27  // CurrentUser returns a UserPath representing the current user.
    28  func CurrentUser() (*UserPath, error) {
    29  	current, err := user.Current()
    30  	if err != nil {
    31  		return nil, err
    32  	}
    33  	u := &UserPath{
    34  		Admin: current.Uid == "0",
    35  	}
    36  	if !u.IsAdmin() {
    37  		u.Path = current.HomeDir
    38  	}
    39  	return u, nil
    40  }