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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
|
# Copyright © 2010 Julian Blake Kongslie <jblake@omgwallhack.org>
# Licensed under the BSD 3-clause license.
package Piny::Group;
use Moose;
use Piny::User;
# Attributes
has 'gid' =>
( is => 'ro'
, isa => 'Int'
, lazy_build => 1
);
has 'groupname' =>
( is => 'ro'
, isa => 'Str'
, lazy_build => 1
);
has 'grent' =>
( is => 'ro'
, isa => 'ArrayRef'
, lazy_build => 1
, init_arg => undef
);
has 'members' =>
( is => 'ro'
, isa => 'ArrayRef[Piny::User]'
, lazy_build => 1
, init_arg => undef
);
# Public methods
sub add_member {
my ( $s, @users ) = @_;
foreach my $user ( @users ) {
system( "/usr/sbin/adduser", $user->username( ), $s->groupname( ) );
$user->clear_groups( );
};
$s->clear_members( );
};
sub remove_member {
my ( $s, @users ) = @_;
foreach my $user ( @users ) {
system( "/usr/sbin/deluser", $user->username( ), $s->groupname( ) );
$user->clear_groups( );
};
$s->clear_members( );
};
# Builder methods
# If constructed with just one argument, then
# * If that argument is numeric, treat it as a UID.
# * Otherwise, treat it as a username.
around BUILDARGS => sub {
my ( $orig, $class ) = ( shift, shift );
if ( @_ == 1 && ! ref $_[0] ) {
if ( $_[0] =~ m/^\d+$/ ) {
return $class->$orig( gid => $_[0] );
} else {
return $class->$orig( groupname => $_[0] );
};
} else {
return $class->$orig( @_ );
};
};
sub BUILD {
my ( $s ) = @_;
if ( not ( $s->has_gid( ) or $s->has_groupname( ) ) ) {
die "You must provide either GID or groupname!";
};
if ( $s->has_gid( ) and $s->has_groupname( ) ) {
die "You must not provide both GID and groupname!";
};
};
sub _build_gid {
my ( $s ) = @_;
return $s->grent( )->[2];
};
sub _build_groupname {
my ( $s ) = @_;
return $s->grent( )->[0];
};
sub _build_grent {
my ( $s ) = @_;
if ( $s->has_gid( ) ) {
my @res = getgrgid( $s->gid( ) );
die "getgrgid( " . $s->gid( ) . " ) failed: $!" unless @res;
return \@res;
} elsif ( $s->has_groupname( ) ) {
my @res = getgrnam( $s->groupname( ) );
die "getgrnam( " . $s->groupname( ) . " ) failed: $!" unless @res;
return \@res;
} else {
die "Not enough information provided to lookup group!";
};
};
sub _build_members {
my ( $s ) = @_;
return [ ] if ( $s->grent( )->[3] eq "" );
return [ map { Piny::User->new( username => $_ ) } split( /:/, $s->grent( )->[3] ) ];
};
# Moose boilerplate
__PACKAGE__->meta->make_immutable;
1;
|