tcms-useradd 6.9 KB

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