token.cgi 11.1 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 22 23 24 25 26 27 28 29
# -*- 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>

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

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

30 31
use lib qw(.);

32 33
use vars qw($template $vars);

34 35
use Bugzilla;

36 37 38 39 40
# Include the Bugzilla CGI and general utility library.
require "CGI.pl";

# Establish a connection to the database backend.
ConnectToDatabase();
41
quietly_check_login('permit_anonymous');
42 43 44 45 46

# Use the "Token" module that contains functions for doing various
# token-related tasks.
use Token;

47 48
use Bugzilla::User;

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
$::FORM{'a'} || ThrowCodeError("unknown_action");
56 57 58 59 60 61 62 63 64 65 66 67 68 69

# Assign the action to a global variable.
$::action = $::FORM{'a'};

# 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.
if ($::FORM{'t'}) {
  # Assign the token and its SQL quoted equivalent to global variables.
  $::token = $::FORM{'t'};
  $::quotedtoken = SqlQuote($::token);
  
  # Make sure the token contains only valid characters in the right amount.
  my $validationerror = ValidatePassword($::token);
  if ($validationerror) {
70
      ThrowUserError("token_invalid");
71 72
  }

73 74 75

  Token::CleanTokenTable();

76 77
  # Make sure the token exists in the database.
  SendSQL( "SELECT tokentype FROM tokens WHERE token = $::quotedtoken" );
78
  (my $tokentype = FetchSQLData()) || ThrowUserError("token_inexistent");
79 80 81

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

# If the user is requesting a password change, make sure they submitted
# their login name and it exists in the database.
if ( $::action eq 'reqpw' ) {
    defined $::FORM{'loginname'}
101
      || ThrowUserError("login_needed_for_password_change");
102 103 104 105 106 107 108 109

    # Make sure the login name looks like an email address.  This function
    # displays its own error and stops execution if the login name looks wrong.
    CheckEmailSyntax($::FORM{'loginname'});

    my $quotedloginname = SqlQuote($::FORM{'loginname'});
    SendSQL("SELECT userid FROM profiles WHERE login_name = $quotedloginname");
    FetchSQLData()
110
      || ThrowUserError("account_inexistent");
111 112 113 114 115 116 117
}

# If the user is changing their password, make sure they submitted a new
# password and that the new password is valid.
if ( $::action eq 'chgpw' ) {
    defined $::FORM{'password'}
      && defined $::FORM{'matchpassword'}
118
      || ThrowUserError("require_new_password");
119

120
    ValidatePassword($::FORM{'password'}, $::FORM{'matchpassword'});
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
}

################################################################################
# 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') { 
    requestChangePassword(); 
} elsif ($::action eq 'cfmpw') { 
    confirmChangePassword(); 
} elsif ($::action eq 'cxlpw') { 
    cancelChangePassword(); 
} elsif ($::action eq 'chgpw') { 
    changePassword(); 
139 140 141 142 143 144
} elsif ($::action eq 'cfmem') {
    confirmChangeEmail();
} elsif ($::action eq 'cxlem') {
    cancelChangeEmail();
} elsif ($::action eq 'chgem') {
    changeEmail();
145 146 147 148
} 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.
149
    ThrowCodeError("unknown_action", { action => $::action });
150 151 152 153 154 155 156 157 158 159 160
}

exit;

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

sub requestChangePassword {
    Token::IssuePasswordToken($::FORM{'loginname'});

161
    $vars->{'message'} = "password_change_request";
162

163
    print Bugzilla->cgi->header();
164
    $template->process("global/message.html.tmpl", $vars)
165
      || ThrowTemplateError($template->error());
166 167 168
}

sub confirmChangePassword {
169 170
    $vars->{'token'} = $::token;
    
171
    print Bugzilla->cgi->header();
172 173
    $template->process("account/password/set-forgotten-password.html.tmpl", $vars)
      || ThrowTemplateError($template->error());
174 175
}

176
sub cancelChangePassword {    
177
    $vars->{'message'} = "password_change_canceled";
178
    Token::Cancel($::token, $vars->{'message'});
179

180
    print Bugzilla->cgi->header();
181
    $template->process("global/message.html.tmpl", $vars)
182
      || ThrowTemplateError($template->error());
183 184 185 186 187 188 189 190 191 192 193 194 195
}

sub changePassword {
    # Quote the password and token for inclusion into SQL statements.
    my $cryptedpassword = Crypt($::FORM{'password'});
    my $quotedpassword = SqlQuote($cryptedpassword);

    # Get the user's ID from the tokens table.
    SendSQL("SELECT userid FROM tokens WHERE token = $::quotedtoken");
    my $userid = FetchSQLData();
    
    # Update the user's password in the profiles table and delete the token
    # from the tokens table.
196
    SendSQL("LOCK TABLES profiles WRITE , tokens WRITE");
197 198 199 200 201 202
    SendSQL("UPDATE   profiles
             SET      cryptpassword = $quotedpassword
             WHERE    userid = $userid");
    SendSQL("DELETE FROM tokens WHERE token = $::quotedtoken");
    SendSQL("UNLOCK TABLES");

203 204
    InvalidateLogins($userid);

205
    $vars->{'message'} = "password_changed";
206

207
    print Bugzilla->cgi->header();
208
    $template->process("global/message.html.tmpl", $vars)
209
      || ThrowTemplateError($template->error());
210 211
}

212 213
sub confirmChangeEmail {
    # Return HTTP response headers.
214
    print Bugzilla->cgi->header();
215 216 217

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

218 219
    $template->process("account/email/confirm.html.tmpl", $vars)
      || ThrowTemplateError($template->error());
220 221 222 223 224 225 226 227 228 229 230 231
}

sub changeEmail {

    # Get the user's ID from the tokens table.
    SendSQL("SELECT userid, eventdata FROM tokens 
              WHERE token = $::quotedtoken");
    my ($userid, $eventdata) = FetchSQLData();
    my ($old_email, $new_email) = split(/:/,$eventdata);
    my $quotednewemail = SqlQuote($new_email);

    # Check the user entered the correct old email address
232
    if(lc($::FORM{'email'}) ne lc($old_email)) {
233
        ThrowUserError("email_confirmation_failed");
234 235 236 237
    }
    # The new email address should be available as this was 
    # confirmed initially so cancel token if it is not still available
    if (! ValidateNewUser($new_email,$old_email)) {
238
        $vars->{'email'} = $new_email; # Needed for Token::Cancel's mail
239
        Token::Cancel($::token,"account_exists");
240
        ThrowUserError("account_exists", { email => $new_email } );
241 242 243 244 245 246 247 248 249 250 251 252
    } 

    # Update the user's login name in the profiles table and delete the token
    # from the tokens table.
    SendSQL("LOCK TABLES profiles WRITE , tokens WRITE");
    SendSQL("UPDATE   profiles
         SET      login_name = $quotednewemail
         WHERE    userid = $userid");
    SendSQL("DELETE FROM tokens WHERE token = $::quotedtoken");
    SendSQL("DELETE FROM tokens WHERE userid = $userid 
                                  AND tokentype = 'emailnew'");
    SendSQL("UNLOCK TABLES");
253 254 255 256

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

    # Return HTTP response headers.
259
    print Bugzilla->cgi->header();
260 261 262

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

263
    $vars->{'message'} = "login_changed";
264 265

    $template->process("global/message.html.tmpl", $vars)
266
      || ThrowTemplateError($template->error());
267 268 269 270 271 272 273 274 275 276
}

sub cancelChangeEmail {
    # Get the user's ID from the tokens table.
    SendSQL("SELECT userid, tokentype, eventdata FROM tokens 
             WHERE token = $::quotedtoken");
    my ($userid, $tokentype, $eventdata) = FetchSQLData();
    my ($old_email, $new_email) = split(/:/,$eventdata);

    if($tokentype eq "emailold") {
277
        $vars->{'message'} = "emailold_change_cancelled";
278 279 280 281 282 283 284 285 286 287 288 289 290

        SendSQL("SELECT login_name FROM profiles WHERE userid = $userid");
        my $actualemail = FetchSQLData();
        
        # check to see if it has been altered
        if($actualemail ne $old_email) {
            my $quotedoldemail = SqlQuote($old_email);

            SendSQL("LOCK TABLES profiles WRITE");
            SendSQL("UPDATE   profiles
                 SET      login_name = $quotedoldemail
                 WHERE    userid = $userid");
            SendSQL("UNLOCK TABLES");
291 292 293 294 295 296 297 298 299 300

            # 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);
            $user->derive_groups;

301
            $vars->{'message'} = "email_change_cancelled_reinstated";
302 303 304
        } 
    } 
    else {
305 306 307 308 309
        $vars->{'message'} = 'email_change_cancelled'
     }

    $vars->{'old_email'} = $old_email;
    $vars->{'new_email'} = $new_email;
310 311 312 313 314 315 316
    Token::Cancel($::token, $vars->{'message'});

    SendSQL("LOCK TABLES tokens WRITE");
    SendSQL("DELETE FROM tokens 
             WHERE userid = $userid 
             AND tokentype = 'emailold' OR tokentype = 'emailnew'");
    SendSQL("UNLOCK TABLES");
317

318
    # Return HTTP response headers.
319
    print Bugzilla->cgi->header();
320

321
    $template->process("global/message.html.tmpl", $vars)
322
      || ThrowTemplateError($template->error());
323
}
324