token.cgi 14 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
use Date::Format;
41 42
use Date::Parse;

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

48 49 50
my $action = $cgi->param('a');
my $token = $cgi->param('t');

51
Bugzilla->login(LOGIN_OPTIONAL);
52 53 54 55 56 57 58

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

# Throw an error if the form does not contain an "action" field specifying
# what the user wants to do.
59
$action || ThrowCodeError("unknown_action");
60 61 62

# 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.
63
if ($token) {
64
  Bugzilla::Token::CleanTokenTable();
65

66 67 68
  # It's safe to detaint the token as it's used in a placeholder.
  trick_taint($token);

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

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

97

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

106
    # check verification methods
107
    unless (Bugzilla->user->authorizer->can_change_password) {
108 109 110
        ThrowUserError("password_change_requests_not_allowed");
    }

111 112
    validate_email_syntax($login_name)
        || ThrowUserError('illegal_email_address', {addr => $login_name});
113

114
    $user_account = Bugzilla::User->check($login_name);
115 116 117 118 119 120

    # Make sure the user account is active.
    if ($user_account->is_disabled) {
        ThrowUserError('account_disabled',
                       {disabled_reason => get_text('account_disabled', {account => $login_name})});
    }
121 122 123 124
}

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

132
    validate_password($password, $cgi->param('matchpassword'));
133 134
    # Make sure that these never show up in the UI under any circumstances.
    $cgi->delete('password', 'matchpassword');
135 136 137 138 139 140 141 142 143 144
}

################################################################################
# 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.

145
if ($action eq 'reqpw') {
146
    requestChangePassword($user_account);
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
} elsif ($action eq 'cfmpw') {
    confirmChangePassword($token);
} elsif ($action eq 'cxlpw') {
    cancelChangePassword($token);
} elsif ($action eq 'chgpw') {
    changePassword($token, $password);
} elsif ($action eq 'cfmem') {
    confirmChangeEmail($token);
} elsif ($action eq 'cxlem') {
    cancelChangeEmail($token);
} elsif ($action eq 'chgem') {
    changeEmail($token);
} elsif ($action eq 'request_new_account') {
    request_create_account($token);
} elsif ($action eq 'confirm_new_account') {
    confirm_create_account($token);
} elsif ($action eq 'cancel_new_account') {
    cancel_create_account($token);
165 166 167 168
} 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.
169
    ThrowCodeError("unknown_action", { action => $action });
170 171 172 173 174 175 176 177 178
}

exit;

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

sub requestChangePassword {
179 180
    my ($user) = @_;
    Bugzilla::Token::IssuePasswordToken($user);
181

182
    $vars->{'message'} = "password_change_request";
183

184
    print $cgi->header();
185
    $template->process("global/message.html.tmpl", $vars)
186
      || ThrowTemplateError($template->error());
187 188 189
}

sub confirmChangePassword {
190 191 192
    my $token = shift;
    $vars->{'token'} = $token;

193
    print $cgi->header();
194 195
    $template->process("account/password/set-forgotten-password.html.tmpl", $vars)
      || ThrowTemplateError($template->error());
196 197
}

198 199
sub cancelChangePassword {
    my $token = shift;
200
    $vars->{'message'} = "password_change_canceled";
201
    Bugzilla::Token::Cancel($token, $vars->{'message'});
202

203
    print $cgi->header();
204
    $template->process("global/message.html.tmpl", $vars)
205
      || ThrowTemplateError($template->error());
206 207 208
}

sub changePassword {
209
    my ($token, $password) = @_;
210 211
    my $dbh = Bugzilla->dbh;

212
    # Create a crypted version of the new password
213
    my $cryptedpassword = bz_crypt($password);
214 215

    # Get the user's ID from the tokens table.
216
    my ($userid) = $dbh->selectrow_array('SELECT userid FROM tokens
217
                                          WHERE token = ?', undef, $token);
218 219 220
    
    # Update the user's password in the profiles table and delete the token
    # from the tokens table.
221
    $dbh->bz_start_transaction();
222 223 224 225
    $dbh->do(q{UPDATE   profiles
               SET      cryptpassword = ?
               WHERE    userid = ?},
             undef, ($cryptedpassword, $userid) );
226
    $dbh->do('DELETE FROM tokens WHERE token = ?', undef, $token);
227
    $dbh->bz_commit_transaction();
228

229
    Bugzilla->logout_user_by_id($userid);
230

231
    $vars->{'message'} = "password_changed";
232

233
    print $cgi->header();
234
    $template->process("global/message.html.tmpl", $vars)
235
      || ThrowTemplateError($template->error());
236 237
}

238
sub confirmChangeEmail {
239 240
    my $token = shift;
    $vars->{'token'} = $token;
241

242
    print $cgi->header();
243 244
    $template->process("account/email/confirm.html.tmpl", $vars)
      || ThrowTemplateError($template->error());
245 246 247
}

sub changeEmail {
248
    my $token = shift;
249
    my $dbh = Bugzilla->dbh;
250 251

    # Get the user's ID from the tokens table.
252 253
    my ($userid, $eventdata) = $dbh->selectrow_array(
                                 q{SELECT userid, eventdata FROM tokens
254
                                   WHERE token = ?}, undef, $token);
255 256 257
    my ($old_email, $new_email) = split(/:/,$eventdata);

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

    # Update the user's login name in the profiles table and delete the token
    # from the tokens table.
271
    $dbh->bz_start_transaction();
272 273 274 275
    $dbh->do(q{UPDATE   profiles
               SET      login_name = ?
               WHERE    userid = ?},
             undef, ($new_email, $userid));
276
    $dbh->do('DELETE FROM tokens WHERE token = ?', undef, $token);
277 278
    $dbh->do(q{DELETE FROM tokens WHERE userid = ?
               AND tokentype = 'emailnew'}, undef, $userid);
279 280 281

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

284 285
    $dbh->bz_commit_transaction();

286
    # Return HTTP response headers.
287
    print $cgi->header();
288 289 290

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

291
    $vars->{'message'} = "login_changed";
292 293

    $template->process("global/message.html.tmpl", $vars)
294
      || ThrowTemplateError($template->error());
295 296 297
}

sub cancelChangeEmail {
298
    my $token = shift;
299 300
    my $dbh = Bugzilla->dbh;

bbaetz%acm.org's avatar
bbaetz%acm.org committed
301
    $dbh->bz_start_transaction();
302

303
    # Get the user's ID from the tokens table.
304 305
    my ($userid, $tokentype, $eventdata) = $dbh->selectrow_array(
                              q{SELECT userid, tokentype, eventdata FROM tokens
306
                                WHERE token = ?}, undef, $token);
307 308 309
    my ($old_email, $new_email) = split(/:/,$eventdata);

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

312 313 314
        my $actualemail = $dbh->selectrow_array(
                            q{SELECT login_name FROM profiles
                              WHERE userid = ?}, undef, $userid);
315 316 317
        
        # check to see if it has been altered
        if($actualemail ne $old_email) {
318 319 320
            # XXX - This is NOT safe - if A has change to B, another profile
            # could have grabbed A's username in the meantime.
            # The DB constraint will catch this, though
321 322 323 324
            $dbh->do(q{UPDATE   profiles
                       SET      login_name = ?
                       WHERE    userid = ?},
                     undef, ($old_email, $userid));
325 326 327 328

            # email has changed, so rederive groups

            my $user = new Bugzilla::User($userid);
329
            $user->derive_regexp_groups;
330

331
            $vars->{'message'} = "email_change_canceled_reinstated";
332 333 334
        } 
    } 
    else {
335
        $vars->{'message'} = 'email_change_canceled'
336 337 338 339
     }

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

342 343 344
    $dbh->do(q{DELETE FROM tokens WHERE userid = ?
               AND tokentype = 'emailold' OR tokentype = 'emailnew'},
             undef, $userid);
345

346 347
    $dbh->bz_commit_transaction();

348
    # Return HTTP response headers.
349
    print $cgi->header();
350

351
    $template->process("global/message.html.tmpl", $vars)
352
      || ThrowTemplateError($template->error());
353
}
354

355
sub request_create_account {
356 357 358 359
    my $token = shift;

    my (undef, $date, $login_name) = Bugzilla::Token::GetTokenData($token);
    $vars->{'token'} = $token;
360
    $vars->{'email'} = $login_name . Bugzilla->params->{'emailsuffix'};
361
    $vars->{'expiration_ts'} = ctime(str2time($date) + MAX_TOKEN_AGE * 86400);
362 363 364 365 366 367 368

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

sub confirm_create_account {
369 370 371
    my $token = shift;

    my (undef, undef, $login_name) = Bugzilla::Token::GetTokenData($token);
372

373 374
    my $password = $cgi->param('passwd1') || '';
    validate_password($password, $cgi->param('passwd2') || '');
375 376
    # Make sure that these never show up anywhere in the UI.
    $cgi->delete('passwd1', 'passwd2');
377 378 379 380

    my $otheruser = Bugzilla::User->create({
        login_name => $login_name, 
        realname   => $cgi->param('realname'), 
381
        cryptpassword => $password});
382 383

    # Now delete this token.
384
    delete_token($token);
385 386 387 388

    # Let the user know that his user account has been successfully created.
    $vars->{'message'} = 'account_created';
    $vars->{'otheruser'} = $otheruser;
389 390 391 392 393

    # Log in the new user using credentials he just gave.
    $cgi->param('Bugzilla_login', $otheruser->login);
    $cgi->param('Bugzilla_password', $password);
    Bugzilla->login(LOGIN_OPTIONAL);
394 395 396

    print $cgi->header();

397
    $template->process('index.html.tmpl', $vars)
398 399 400 401
      || ThrowTemplateError($template->error());
}

sub cancel_create_account {
402 403 404
    my $token = shift;

    my (undef, undef, $login_name) = Bugzilla::Token::GetTokenData($token);
405

406
    $vars->{'message'} = 'account_creation_canceled';
407
    $vars->{'account'} = $login_name;
408
    Bugzilla::Token::Cancel($token, $vars->{'message'});
409 410 411 412 413

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