github.com/coreos/mantle@v0.13.0/system/user/user.go (about)

     1  // Copyright 2016 CoreOS, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // user provides an extended User struct to simplify usage
    16  package user
    17  
    18  import (
    19  	"os/user"
    20  	"strconv"
    21  )
    22  
    23  // User represents a user account.
    24  type User struct {
    25  	*user.User
    26  	Groupname string
    27  	// For convenience so users don't need to strconv themselves.
    28  	UidNo int
    29  	GidNo int
    30  }
    31  
    32  // Current returns the current user.
    33  func Current() (*User, error) {
    34  	return newUser(user.Current())
    35  }
    36  
    37  // Lookup looks up a user by username.
    38  func Lookup(username string) (*User, error) {
    39  	return newUser(user.Lookup(username))
    40  }
    41  
    42  // LookupId looks up a user by userid.
    43  func LookupId(uid string) (*User, error) {
    44  	return newUser(user.LookupId(uid))
    45  }
    46  
    47  // Convert the stock user.User to our own User strict with group info.
    48  func newUser(u *user.User, err error) (*User, error) {
    49  	if err != nil {
    50  		return nil, err
    51  	}
    52  
    53  	g, err := user.LookupGroupId(u.Gid)
    54  	if err != nil {
    55  		return nil, err
    56  	}
    57  
    58  	uid, err := strconv.Atoi(u.Uid)
    59  	if err != nil {
    60  		return nil, err
    61  	}
    62  
    63  	gid, err := strconv.Atoi(u.Gid)
    64  	if err != nil {
    65  		return nil, err
    66  	}
    67  
    68  	return &User{
    69  		User:      u,
    70  		Groupname: g.Name,
    71  		UidNo:     uid,
    72  		GidNo:     gid,
    73  	}, nil
    74  }