token.cgi 13.6 KB
Newer Older
1
#!/usr/bin/perl -wT
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# -*- Mode: perl; indent-tabs-mode: nil -*-
#
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Original Code is the Bugzilla Bug Tracking System.
#
# The Initial Developer of the Original Code is Netscape Communications
# Corporation. Portions created by Netscape are
# Copyright (C) 1998 Netscape Communications Corporation. All
# Rights Reserved.
#
# Contributor(s): Myk Melez <myk@mozilla.org>
22
#                 Frédéric Buclin <LpSolit@gmail.com>
23 24 25 26 27 28 29 30

############################################################################
# Script Initialization
############################################################################

# Make it harder for us to do dangerous things in Perl.
use strict;

31
use lib qw(. lib);
32

33
use Bugzilla;
34
use Bugzilla::Constants;
35
use Bugzilla::Util;
36 37 38
use Bugzilla::Error;
use Bugzilla::Token;
use Bugzilla::User;
39

40 41
use Date::Parse;

42
my $dbh = Bugzilla->dbh;
43 44 45
local our $cgi = Bugzilla->cgi;
local our $template = Bugzilla->template;
local our $vars = {};
46

47
Bugzilla->login(LOGIN_OPTIONAL);
48 49 50 51 52 53 54

################################################################################
# Data Validation / Security Authorization
################################################################################

# Throw an error if the form does not contain an "action" field specifying
# what the user wants to do.
55
$cgi->param('a') || ThrowCodeError("unknown_action");
56 57

# Assign the action to a global variable.
58
$::action = $cgi->param('a');
59 60 61

# If a token was submitted, make sure it is a valid token that exists in the
# database and is the correct type for the action being taken.
62
if ($cgi->param('t')) {
63
  # Assign the token and its SQL quoted equivalent to global variables.
64
  $::token = $cgi->param('t');
65 66
  
  # Make sure the token contains only valid characters in the right amount.
67
  # validate_password will throw an error if token is invalid
68
  validate_password($::token);
69

70
  Bugzilla::Token::CleanTokenTable();
71

72
  # Make sure the token exists in the database.
73 74
  my ($tokentype) = $dbh->selectrow_array('SELECT tokentype FROM tokens
                                           WHERE token = ?', undef, $::token);
75
  $tokentype || ThrowUserError("token_does_not_exist");
76 77 78

  # Make sure the token is the correct type for the action being taken.
  if ( grep($::action eq $_ , qw(cfmpw cxlpw chgpw)) && $tokentype ne 'password' ) {
79
    Bugzilla::Token::Cancel($::token, "wrong_token_for_changing_passwd");
80
    ThrowUserError("wrong_token_for_changing_passwd");
81
  }
82 83
  if ( ($::action eq 'cxlem') 
      && (($tokentype ne 'emailold') && ($tokentype ne 'emailnew')) ) {
84
    Bugzilla::Token::Cancel($::token, "wrong_token_for_cancelling_email_change");
85
    ThrowUserError("wrong_token_for_cancelling_email_change");
86 87 88
  }
  if ( grep($::action eq $_ , qw(cfmem chgem)) 
      && ($tokentype ne 'emailnew') ) {
89
    Bugzilla::Token::Cancel($::token, "wrong_token_for_confirming_email_change");
90
    ThrowUserError("wrong_token_for_confirming_email_change");
91
  }
92 93 94 95 96 97
  if (($::action =~ /^(request|confirm|cancel)_new_account$/)
      && ($tokentype ne 'account'))
  {
      Bugzilla::Token::Cancel($::token, 'wrong_token_for_creating_account');
      ThrowUserError('wrong_token_for_creating_account');
  }
98 99
}

100

101
# If the user is requesting a password change, make sure they submitted
102
# their login name and it exists in the database, and that the DB module is in
103
# the list of allowed verification methods.
104
my $user_account;
105
if ( $::action eq 'reqpw' ) {
106 107
    my $login_name = $cgi->param('loginname')
                       || ThrowUserError("login_needed_for_password_change");
108

109
    # check verification methods
110
    unless (Bugzilla->user->authorizer->can_change_password) {
111 112 113
        ThrowUserError("password_change_requests_not_allowed");
    }

114 115
    validate_email_syntax($login_name)
        || ThrowUserError('illegal_email_address', {addr => $login_name});
116

117
    $user_account = Bugzilla::User->check($login_name);
118 119 120 121
}

# If the user is changing their password, make sure they submitted a new
# password and that the new password is valid.
122
my $password;
123
if ( $::action eq 'chgpw' ) {
124 125
    $password = $cgi->param('password');
    defined $password
126
      && defined $cgi->param('matchpassword')
127
      || ThrowUserError("require_new_password");
128

129
    validate_password($password, $cgi->param('matchpassword'));
130 131 132 133 134 135 136 137 138 139 140
}

################################################################################
# Main Body Execution
################################################################################

# All calls to this script should contain an "action" variable whose value
# determines what the user wants to do.  The code below checks the value of
# that variable and runs the appropriate code.

if ($::action eq 'reqpw') { 
141
    requestChangePassword($user_account);
142 143 144 145 146
} elsif ($::action eq 'cfmpw') { 
    confirmChangePassword(); 
} elsif ($::action eq 'cxlpw') { 
    cancelChangePassword(); 
} elsif ($::action eq 'chgpw') { 
147
    changePassword($password);
148 149 150 151 152 153
} elsif ($::action eq 'cfmem') {
    confirmChangeEmail();
} elsif ($::action eq 'cxlem') {
    cancelChangeEmail();
} elsif ($::action eq 'chgem') {
    changeEmail();
154 155 156 157 158 159
} elsif ($::action eq 'request_new_account') {
    request_create_account();
} elsif ($::action eq 'confirm_new_account') {
    confirm_create_account();
} elsif ($::action eq 'cancel_new_account') {
    cancel_create_account();
160 161 162 163
} else { 
    # If the action that the user wants to take (specified in the "a" form field)
    # is none of the above listed actions, display an error telling the user 
    # that we do not understand what they would like to do.
164
    ThrowCodeError("unknown_action", { action => $::action });
165 166 167 168 169 170 171 172 173
}

exit;

################################################################################
# Functions
################################################################################

sub requestChangePassword {
174 175
    my ($user) = @_;
    Bugzilla::Token::IssuePasswordToken($user);
176

177
    $vars->{'message'} = "password_change_request";
178

179
    print $cgi->header();
180
    $template->process("global/message.html.tmpl", $vars)
181
      || ThrowTemplateError($template->error());
182 183 184
}

sub confirmChangePassword {
185 186
    $vars->{'token'} = $::token;
    
187
    print $cgi->header();
188 189
    $template->process("account/password/set-forgotten-password.html.tmpl", $vars)
      || ThrowTemplateError($template->error());
190 191
}

192
sub cancelChangePassword {    
193
    $vars->{'message'} = "password_change_canceled";
194
    Bugzilla::Token::Cancel($::token, $vars->{'message'});
195

196
    print $cgi->header();
197
    $template->process("global/message.html.tmpl", $vars)
198
      || ThrowTemplateError($template->error());
199 200 201
}

sub changePassword {
202
    my ($password) = @_;
203 204
    my $dbh = Bugzilla->dbh;

205
    # Create a crypted version of the new password
206
    my $cryptedpassword = bz_crypt($password);
207 208

    # Get the user's ID from the tokens table.
209 210
    my ($userid) = $dbh->selectrow_array('SELECT userid FROM tokens
                                          WHERE token = ?', undef, $::token);
211 212 213
    
    # Update the user's password in the profiles table and delete the token
    # from the tokens table.
214
    $dbh->bz_start_transaction();
215 216 217 218 219
    $dbh->do(q{UPDATE   profiles
               SET      cryptpassword = ?
               WHERE    userid = ?},
             undef, ($cryptedpassword, $userid) );
    $dbh->do('DELETE FROM tokens WHERE token = ?', undef, $::token);
220
    $dbh->bz_commit_transaction();
221

222
    Bugzilla->logout_user_by_id($userid);
223

224
    $vars->{'message'} = "password_changed";
225

226
    print $cgi->header();
227
    $template->process("global/message.html.tmpl", $vars)
228
      || ThrowTemplateError($template->error());
229 230
}

231 232
sub confirmChangeEmail {
    # Return HTTP response headers.
233
    print $cgi->header();
234 235 236

    $vars->{'token'} = $::token;

237 238
    $template->process("account/email/confirm.html.tmpl", $vars)
      || ThrowTemplateError($template->error());
239 240 241
}

sub changeEmail {
242
    my $dbh = Bugzilla->dbh;
243 244

    # Get the user's ID from the tokens table.
245 246 247
    my ($userid, $eventdata) = $dbh->selectrow_array(
                                 q{SELECT userid, eventdata FROM tokens
                                   WHERE token = ?}, undef, $::token);
248 249 250
    my ($old_email, $new_email) = split(/:/,$eventdata);

    # Check the user entered the correct old email address
251
    if(lc($cgi->param('email')) ne lc($old_email)) {
252
        ThrowUserError("email_confirmation_failed");
253 254 255
    }
    # The new email address should be available as this was 
    # confirmed initially so cancel token if it is not still available
256
    if (! is_available_username($new_email,$old_email)) {
257
        $vars->{'email'} = $new_email; # Needed for Bugzilla::Token::Cancel's mail
258
        Bugzilla::Token::Cancel($::token, "account_exists", $vars);
259
        ThrowUserError("account_exists", { email => $new_email } );
260 261 262 263
    } 

    # Update the user's login name in the profiles table and delete the token
    # from the tokens table.
264
    $dbh->bz_start_transaction();
265 266 267 268 269 270 271
    $dbh->do(q{UPDATE   profiles
               SET      login_name = ?
               WHERE    userid = ?},
             undef, ($new_email, $userid));
    $dbh->do('DELETE FROM tokens WHERE token = ?', undef, $::token);
    $dbh->do(q{DELETE FROM tokens WHERE userid = ?
               AND tokentype = 'emailnew'}, undef, $userid);
272
    $dbh->bz_commit_transaction();
273 274 275

    # The email address has been changed, so we need to rederive the groups
    my $user = new Bugzilla::User($userid);
276
    $user->derive_regexp_groups;
277 278

    # Return HTTP response headers.
279
    print $cgi->header();
280 281 282

    # Let the user know their email address has been changed.

283
    $vars->{'message'} = "login_changed";
284 285

    $template->process("global/message.html.tmpl", $vars)
286
      || ThrowTemplateError($template->error());
287 288 289
}

sub cancelChangeEmail {
290 291
    my $dbh = Bugzilla->dbh;

292
    # Get the user's ID from the tokens table.
293 294 295
    my ($userid, $tokentype, $eventdata) = $dbh->selectrow_array(
                              q{SELECT userid, tokentype, eventdata FROM tokens
                                WHERE token = ?}, undef, $::token);
296 297 298
    my ($old_email, $new_email) = split(/:/,$eventdata);

    if($tokentype eq "emailold") {
299
        $vars->{'message'} = "emailold_change_canceled";
300

301 302 303
        my $actualemail = $dbh->selectrow_array(
                            q{SELECT login_name FROM profiles
                              WHERE userid = ?}, undef, $userid);
304 305 306
        
        # check to see if it has been altered
        if($actualemail ne $old_email) {
307 308 309 310
            $dbh->do(q{UPDATE   profiles
                       SET      login_name = ?
                       WHERE    userid = ?},
                     undef, ($old_email, $userid));
311 312 313 314 315 316 317 318

            # email has changed, so rederive groups
            # Note that this is done _after_ the tables are unlocked
            # This is sort of a race condition (given the lack of transactions)
            # but the user had access to it just now, so it's not a security
            # issue

            my $user = new Bugzilla::User($userid);
319
            $user->derive_regexp_groups;
320

321
            $vars->{'message'} = "email_change_canceled_reinstated";
322 323 324
        } 
    } 
    else {
325
        $vars->{'message'} = 'email_change_canceled'
326 327 328 329
     }

    $vars->{'old_email'} = $old_email;
    $vars->{'new_email'} = $new_email;
330
    Bugzilla::Token::Cancel($::token, $vars->{'message'}, $vars);
331

332 333 334
    $dbh->do(q{DELETE FROM tokens WHERE userid = ?
               AND tokentype = 'emailold' OR tokentype = 'emailnew'},
             undef, $userid);
335

336
    # Return HTTP response headers.
337
    print $cgi->header();
338

339
    $template->process("global/message.html.tmpl", $vars)
340
      || ThrowTemplateError($template->error());
341
}
342

343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
sub request_create_account {
    my (undef, $date, $login_name) = Bugzilla::Token::GetTokenData($::token);
    $vars->{'token'} = $::token;
    $vars->{'email'} = $login_name . Bugzilla->params->{'emailsuffix'};
    $vars->{'date'} = str2time($date);

    # We require a HTTPS connection if possible.
    if (Bugzilla->params->{'sslbase'} ne ''
        && Bugzilla->params->{'ssl'} ne 'never')
    {
        $cgi->require_https(Bugzilla->params->{'sslbase'});
    }
    print $cgi->header();

    $template->process('account/email/confirm-new.html.tmpl', $vars)
      || ThrowTemplateError($template->error());
}

sub confirm_create_account {
    my (undef, undef, $login_name) = Bugzilla::Token::GetTokenData($::token);

364 365
    my $password = $cgi->param('passwd1') || '';
    validate_password($password, $cgi->param('passwd2') || '');
366 367 368 369

    my $otheruser = Bugzilla::User->create({
        login_name => $login_name, 
        realname   => $cgi->param('realname'), 
370
        cryptpassword => $password});
371 372

    # Now delete this token.
373
    delete_token($::token);
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388

    # Let the user know that his user account has been successfully created.
    $vars->{'message'} = 'account_created';
    $vars->{'otheruser'} = $otheruser;
    $vars->{'login_info'} = 1;

    print $cgi->header();

    $template->process('global/message.html.tmpl', $vars)
      || ThrowTemplateError($template->error());
}

sub cancel_create_account {
    my (undef, undef, $login_name) = Bugzilla::Token::GetTokenData($::token);

389
    $vars->{'message'} = 'account_creation_canceled';
390 391 392 393 394 395 396
    $vars->{'account'} = $login_name;
    Bugzilla::Token::Cancel($::token, $vars->{'message'});

    print $cgi->header();
    $template->process('global/message.html.tmpl', $vars)
      || ThrowTemplateError($template->error());
}