lookup.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright 2011 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package user
  5. import "sync"
  6. // Current returns the current user.
  7. //
  8. // The first call will cache the current user information.
  9. // Subsequent calls will return the cached value and will not reflect
  10. // changes to the current user.
  11. func Current() (*User, error) {
  12. cache.Do(func() { cache.u, cache.err = current() })
  13. if cache.err != nil {
  14. return nil, cache.err
  15. }
  16. u := *cache.u // copy
  17. return &u, nil
  18. }
  19. // cache of the current user
  20. var cache struct {
  21. sync.Once
  22. u *User
  23. err error
  24. }
  25. // Lookup looks up a user by username. If the user cannot be found, the
  26. // returned error is of type UnknownUserError.
  27. func Lookup(username string) (*User, error) {
  28. if u, err := Current(); err == nil && u.Username == username {
  29. return u, err
  30. }
  31. return lookupUser(username)
  32. }
  33. // LookupId looks up a user by userid. If the user cannot be found, the
  34. // returned error is of type UnknownUserIdError.
  35. func LookupId(uid string) (*User, error) {
  36. if u, err := Current(); err == nil && u.Uid == uid {
  37. return u, err
  38. }
  39. return lookupUserId(uid)
  40. }
  41. // LookupGroup looks up a group by name. If the group cannot be found, the
  42. // returned error is of type UnknownGroupError.
  43. func LookupGroup(name string) (*Group, error) {
  44. return lookupGroup(name)
  45. }
  46. // LookupGroupId looks up a group by groupid. If the group cannot be found, the
  47. // returned error is of type UnknownGroupIdError.
  48. func LookupGroupId(gid string) (*Group, error) {
  49. return lookupGroupId(gid)
  50. }
  51. // GroupIds returns the list of group IDs that the user is a member of.
  52. func (u *User) GroupIds() ([]string, error) {
  53. return listGroups(u)
  54. }