token.cgi 13.8 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 48 49
my $action = $cgi->param('a');
my $token = $cgi->param('t');

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

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

# Throw an error if the form does not contain an "action" field specifying
# what the user wants to do.
58
$action || ThrowCodeError("unknown_action");
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 ($token) {
63
  Bugzilla::Token::CleanTokenTable();
64

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

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

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

96

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

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

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

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

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

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

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

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

142
if ($action eq 'reqpw') {
143
    requestChangePassword($user_account);
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
} 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);
162 163 164 165
} 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.
166
    ThrowCodeError("unknown_action", { action => $action });
167 168 169 170 171 172 173 174 175
}

exit;

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

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

179
    $vars->{'message'} = "password_change_request";
180

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

sub confirmChangePassword {
187 188 189
    my $token = shift;
    $vars->{'token'} = $token;

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

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

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

sub changePassword {
206
    my ($token, $password) = @_;
207 208
    my $dbh = Bugzilla->dbh;

209
    # Create a crypted version of the new password
210
    my $cryptedpassword = bz_crypt($password);
211 212

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

226
    Bugzilla->logout_user_by_id($userid);
227

228
    $vars->{'message'} = "password_changed";
229

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

235
sub confirmChangeEmail {
236 237
    my $token = shift;
    $vars->{'token'} = $token;
238

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

sub changeEmail {
245
    my $token = shift;
246
    my $dbh = Bugzilla->dbh;
247 248

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

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

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

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

    # Return HTTP response headers.
283
    print $cgi->header();
284 285 286

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

287
    $vars->{'message'} = "login_changed";
288 289

    $template->process("global/message.html.tmpl", $vars)
290
      || ThrowTemplateError($template->error());
291 292 293
}

sub cancelChangeEmail {
294
    my $token = shift;
295 296
    my $dbh = Bugzilla->dbh;

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

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

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

            # 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);
324
            $user->derive_regexp_groups;
325

326
            $vars->{'message'} = "email_change_canceled_reinstated";
327 328 329
        } 
    } 
    else {
330
        $vars->{'message'} = 'email_change_canceled'
331 332 333 334
     }

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

337 338 339
    $dbh->do(q{DELETE FROM tokens WHERE userid = ?
               AND tokentype = 'emailold' OR tokentype = 'emailnew'},
             undef, $userid);
340

341
    # Return HTTP response headers.
342
    print $cgi->header();
343

344
    $template->process("global/message.html.tmpl", $vars)
345
      || ThrowTemplateError($template->error());
346
}
347

348
sub request_create_account {
349 350 351 352
    my $token = shift;

    my (undef, $date, $login_name) = Bugzilla::Token::GetTokenData($token);
    $vars->{'token'} = $token;
353 354 355
    $vars->{'email'} = $login_name . Bugzilla->params->{'emailsuffix'};
    $vars->{'date'} = str2time($date);

356 357 358
    # When 'ssl' equals 'always' or 'authenticated sessions', 
    # we want this form to always be over SSL.
    if ($cgi->protocol ne 'https' && Bugzilla->params->{'sslbase'} ne ''
359 360 361 362
        && Bugzilla->params->{'ssl'} ne 'never')
    {
        $cgi->require_https(Bugzilla->params->{'sslbase'});
    }
363 364 365 366 367 368 369
    print $cgi->header();

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

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

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

374 375
    my $password = $cgi->param('passwd1') || '';
    validate_password($password, $cgi->param('passwd2') || '');
376 377 378 379

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

    # Now delete this token.
383
    delete_token($token);
384 385 386 387 388 389 390 391 392 393 394 395 396

    # 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 {
397 398 399
    my $token = shift;

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

401
    $vars->{'message'} = 'account_creation_canceled';
402
    $vars->{'account'} = $login_name;
403
    Bugzilla::Token::Cancel($token, $vars->{'message'});
404 405 406 407 408

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