tcms-useradd 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. #!/usr/bin/env perl
  2. package tcms::useradd;
  3. use 5.040;
  4. use re '/aasx';
  5. use warnings FATAL => 'all';
  6. use FindBin::libs;
  7. use Getopt::Long;
  8. use Pod::Usage;
  9. use List::Util qw{first};
  10. use Trog::Auth;
  11. use Trog::Log;
  12. use Trog::Data;
  13. use Trog::Config;
  14. # Don't murder our terminal when done
  15. $ENV{NOHUP} = 1;
  16. =head1 SYNOPSIS
  17. Add or edit a tCMS user. In the event of a user edit, every option save for user is optional,
  18. and the ones you leave out keep whatever value they already had.
  19. Creating a user who does not exist yet needs --password, --display_name and --contact_email,
  20. as there is no existing profile post to inherit them from.
  21. Use this to reset user passwords or fix broken users.
  22. =head2 USAGE
  23. tcms-useradd --user foo --password bar --display_name baz --contact_email foo@bar.baz --acl fred --acl wilma
  24. =head2 OPTIONS
  25. =over 4
  26. =item --user
  27. Specify the user to add, or edit if the user already exists.
  28. =item --password
  29. Set a password for the user. Omit the option entirely if you want to keep the
  30. password an existing user already has.
  31. Passing --password with no value prompts for one instead, with echo off, which
  32. keeps it out of your shell history and off your screen:
  33. tcms-useradd --user foo --password # prompts, twice, to confirm
  34. It can also be piped in, in which case it is read once and not confirmed:
  35. echo hunter2 | tcms-useradd --user foo --password
  36. Note that setting a password kills any session the user currently holds, so
  37. they will have to log back in.
  38. =item --display_name
  39. Set the display name for the user.
  40. =item --contact_email
  41. Set the contact email for the user.
  42. =item --acl
  43. Set an acl for this user. May be passed multiple times.
  44. Defaults to 'admin' acl.
  45. =item --help, --man
  46. Display this output.
  47. =back
  48. =cut
  49. # The logger is set up per-request by the server; a CLI run has to do it itself,
  50. # or the first thing Trog::Auth logs blows up on an undefined $log.
  51. my sub init_logs {
  52. my ($who) = @_;
  53. Trog::Log::log_init( 'logs/tcms.log', 'info' );
  54. $Trog::Log::user = $who // 'nobody';
  55. return;
  56. }
  57. # Read a password off the terminal without echoing it, so it stays out of the
  58. # shell history and off the screen. Falls back to a plain read when we aren't
  59. # on a TTY, which is what makes `echo hunter2 | tcms-useradd ...` work.
  60. my sub read_password {
  61. my ($prompt) = @_;
  62. my $password;
  63. if ( -t STDIN ) {
  64. print STDERR $prompt;
  65. require Term::ReadKey;
  66. Term::ReadKey::ReadMode('noecho');
  67. $password = <STDIN>;
  68. Term::ReadKey::ReadMode('restore');
  69. print STDERR "\n";
  70. }
  71. else {
  72. $password = <STDIN>;
  73. }
  74. chomp $password if defined $password;
  75. return $password;
  76. }
  77. # What a brand new user's profile post looks like before we merge anything over
  78. # the top of it. Mirrors what setup() builds for the very first user.
  79. my sub default_user_post {
  80. return {
  81. data => 'Default user',
  82. preview => '/img/avatar/humm.gif',
  83. wallpaper => '/img/sys/testpattern.jpg',
  84. tags => ['about'],
  85. visibility => 'public',
  86. acls => ['admin'],
  87. callback => 'Trog::Routes::HTML::users',
  88. method => 'GET',
  89. form => 'profile.tx',
  90. aliases => [],
  91. };
  92. }
  93. sub main {
  94. my %options;
  95. Getopt::Long::GetOptionsFromArray(
  96. \@_,
  97. 'user=s' => \$options{user},
  98. 'display_name=s' => \$options{display_name},
  99. 'help|?' => \$options{help},
  100. 'password:s' => \$options{password},
  101. 'contact_email=s' => \$options{contact_email},
  102. 'acl=s@' => \$options{acl},
  103. );
  104. pod2usage( -exitval => 0, -verbose => 1 ) if $options{help};
  105. unless ( $options{user} ) {
  106. print STDERR "--user is required.\n";
  107. return 2;
  108. }
  109. # --password with no value means "ask me", as opposed to leaving the option
  110. # out entirely, which means "leave the password alone".
  111. if ( defined $options{password} && !$options{password} ) {
  112. my $interactive = -t STDIN;
  113. $options{password} = read_password("New password for '$options{user}': ");
  114. unless ( $options{password} ) {
  115. print STDERR "No password provided.\n";
  116. return 2;
  117. }
  118. # Only worth confirming when a human is typing it. Piped input has no
  119. # second line to read, and typos in a script aren't fixed by asking twice.
  120. if ($interactive) {
  121. my $again = read_password("Confirm: ");
  122. unless ( defined $again && $options{password} eq $again ) {
  123. print STDERR "Passwords did not match.\n";
  124. return 2;
  125. }
  126. }
  127. }
  128. $options{acl} //= [];
  129. $options{acl} = [ $options{acl} ] if $options{acl} && ref $options{acl} ne 'ARRAY';
  130. $options{acl} = ['admin'] unless @{ $options{acl} };
  131. init_logs( $options{user} );
  132. # Find the user's existing post, if they have one.
  133. my $conf = Trog::Config::get();
  134. my $data = Trog::Data->new($conf);
  135. my @userposts = $data->get( tags => ['about'], acls => [qw{admin}] );
  136. my $user_obj = first { ( $_->{user} || '' ) eq $options{user} } @userposts;
  137. # A user we've never seen before has no post to edit, so start from the
  138. # defaults rather than dereferencing undef.
  139. my $is_new = !$user_obj;
  140. $user_obj //= default_user_post();
  141. if ($is_new) {
  142. unless ( $options{password} && $options{display_name} && $options{contact_email} ) {
  143. print STDERR "User '$options{user}' does not exist yet.\n";
  144. print STDERR "Creating one needs --password, --display_name and --contact_email.\n";
  145. return 2;
  146. }
  147. }
  148. # Only the options actually passed should win. Merging %options wholesale
  149. # writes an undef over every field the caller didn't mention, which is how
  150. # resetting a password used to blank out the display name and contact email.
  151. my %provided = map { $_ => $options{$_} } grep { defined $options{$_} } qw{user display_name contact_email};
  152. my %merged = (
  153. %$user_obj,
  154. %provided,
  155. );
  156. # The display name is the title of the post, and the URL it lives at.
  157. $merged{title} = $merged{display_name} if $merged{display_name};
  158. $merged{local_href} = "/users/$merged{display_name}" if $merged{display_name};
  159. Trog::Auth::killsession( $options{user} );
  160. local $@;
  161. eval { Trog::Auth::useradd( $options{user}, $merged{display_name}, $options{password}, $options{acl}, $merged{contact_email} ); 1 } or do {
  162. print STDERR "Could not add user '$options{user}': $@";
  163. return 1;
  164. };
  165. eval { $data->add( \%merged ); 1 } or do {
  166. my @errors = ref $@ eq 'ARRAY' ? @{$@} : ($@);
  167. print STDERR "Saved the credentials for '$options{user}', but their profile post was rejected:\n";
  168. print STDERR join( "\n", @errors ), "\n";
  169. return 1;
  170. };
  171. print "@{[ $is_new ? 'Added' : 'Updated' ]} user '$options{user}'.\n";
  172. return 0;
  173. }
  174. exit main(@ARGV) unless caller;
  175. 1;