1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use crate::core::{grp, pwd};
use crate::error::{Error, ErrorKind};
pub fn groups(uid: nc::uid_t) -> Result<Vec<String>, Error> {
let passwd = pwd::getpwuid(uid)?;
match passwd {
None => Err(Error::from_string(
ErrorKind::PwdError,
format!("Invalid uid: {}", uid),
)),
Some(passwd) => {
let group_iter = grp::getgrent()?;
let mut result = Vec::new();
for g in group_iter {
if g.mem.contains(&passwd.name) || g.gid == passwd.gid {
result.push(g.name);
}
}
return Ok(result);
}
}
}
pub fn groups_by_name(name: &str) -> Result<Vec<String>, Error> {
let passwd = pwd::getpwname(name)?;
match passwd {
None => Err(Error::from_string(
ErrorKind::PwdError,
format!("Invalid user name: {}", name),
)),
Some(passwd) => {
let group_iter = grp::getgrent()?;
let mut result = Vec::new();
for g in group_iter {
if g.mem.contains(&passwd.name) || g.gid == passwd.gid {
result.push(g.name);
}
}
return Ok(result);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_groups() {
let root_uid = 0;
let root_group = "root".to_string();
let ret = groups(root_uid);
assert!(ret.is_ok());
let ret = ret.unwrap();
assert!(ret.contains(&root_group));
}
#[test]
fn test_groups_by_name() {
let root_name = "root";
let root_group = "root".to_string();
let ret = groups_by_name(root_name);
assert!(ret.is_ok());
let ret = ret.unwrap();
assert!(ret.contains(&root_group));
}
}