diff options
author | Justin Wernick <justin@worthe-it.co.za> | 2023-03-29 14:16:06 +0200 |
---|---|---|
committer | Justin Wernick <justin@worthe-it.co.za> | 2023-03-29 14:16:06 +0200 |
commit | ff2a4b09646a8a5949808bfadf31747751831963 (patch) | |
tree | b5db991f6829d2f9564bf5bb915176b4f978c63c /user-info | |
parent | 2e84602de722694c5cce4172e7455f592cee6a03 (diff) |
Function to get the current user's groups
Diffstat (limited to 'user-info')
-rw-r--r-- | user-info/src/lib.rs | 19 |
1 files changed, 18 insertions, 1 deletions
diff --git a/user-info/src/lib.rs b/user-info/src/lib.rs index bd5ff42..7a42db9 100644 --- a/user-info/src/lib.rs +++ b/user-info/src/lib.rs @@ -1,10 +1,18 @@ -use nix::unistd::{getuid, User}; +use nix::unistd::{getgroups, getuid, Group, User}; pub fn get_username() -> Option<String> { let uid = getuid(); User::from_uid(uid).ok().flatten().map(|user| user.name) } +pub fn get_user_groups() -> Vec<String> { + let gids = getgroups().unwrap_or(Vec::default()); + gids.into_iter() + .filter_map(|gid| Group::from_gid(gid).ok().flatten()) + .map(|group| group.name) + .collect() +} + #[cfg(test)] mod test { use super::*; @@ -17,4 +25,13 @@ mod test { let username_len = username.unwrap().trim().len(); assert!(username_len > 0); } + + #[test] + fn it_returns_some_groups() { + let groups = get_user_groups(); + assert!(groups.len() > 0); + for group in groups { + assert!(group.trim().len() > 0); + } + } } |