Token.pm 9.16 KB
Newer Older
1 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
# -*- 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>

################################################################################
# Module Initialization
################################################################################

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

29
# Bundle the functions in this file together into the "Bugzilla::Token" package.
30
package Bugzilla::Token;
31

32
use Bugzilla::Config;
33
use Bugzilla::Error;
34
use Bugzilla::BugMail;
35

36 37
use Date::Format;

38 39 40
# This module requires that its caller have said "require CGI.pl" to import
# relevant functions from that script and its companion globals.pl.

41 42 43 44 45 46 47
################################################################################
# Constants
################################################################################

# The maximum number of days a token will remain valid.
my $maxtokenage = 3;

48 49 50 51
################################################################################
# Functions
################################################################################

52 53 54
sub IssueEmailChangeToken {
    my ($userid, $old_email, $new_email) = @_;

55 56 57
    my $token_ts = time();
    my $issuedate = time2str("%Y-%m-%d %H:%M", $token_ts);

58 59 60 61 62 63 64 65 66
    # Generate a unique token and insert it into the tokens table.
    # We have to lock the tokens table before generating the token, 
    # since the database must be queried for token uniqueness.
    &::SendSQL("LOCK TABLES tokens WRITE");
    my $token = GenerateUniqueToken();
    my $quotedtoken = &::SqlQuote($token);
    my $quoted_emails = &::SqlQuote($old_email . ":" . $new_email);
    &::SendSQL("INSERT INTO tokens ( userid , issuedate , token , 
                                     tokentype , eventdata )
67
                VALUES             ( $userid , '$issuedate' , $quotedtoken , 
68 69 70 71 72
                                     'emailold' , $quoted_emails )");
    my $newtoken = GenerateUniqueToken();
    $quotedtoken = &::SqlQuote($newtoken);
    &::SendSQL("INSERT INTO tokens ( userid , issuedate , token , 
                                     tokentype , eventdata )
73
                VALUES             ( $userid , '$issuedate' , $quotedtoken , 
74 75 76 77 78 79 80 81
                                     'emailnew' , $quoted_emails )");
    &::SendSQL("UNLOCK TABLES");

    # Mail the user the token along with instructions for using it.

    my $template = $::template;
    my $vars = $::vars;

82 83
    $vars->{'oldemailaddress'} = $old_email . Param('emailsuffix');
    $vars->{'newemailaddress'} = $new_email . Param('emailsuffix');
84 85 86
    
    $vars->{'max_token_age'} = $maxtokenage;
    $vars->{'token_ts'} = $token_ts;
87

88
    $vars->{'token'} = $token;
89
    $vars->{'emailaddress'} = $old_email . Param('emailsuffix');
90 91

    my $message;
92
    $template->process("account/email/change-old.txt.tmpl", $vars, \$message)
93
      || ThrowTemplateError($template->error());
94

95
    Bugzilla::BugMail::MessageToMTA($message);
96

97
    $vars->{'token'} = $newtoken;
98
    $vars->{'emailaddress'} = $new_email . Param('emailsuffix');
99 100

    $message = "";
101
    $template->process("account/email/change-new.txt.tmpl", $vars, \$message)
102
      || ThrowTemplateError($template->error());
103

104
    Bugzilla::BugMail::MessageToMTA($message);
105 106
}

107 108 109 110 111 112 113 114
sub IssuePasswordToken {
    # Generates a random token, adds it to the tokens table, and sends it
    # to the user with instructions for using it to change their password.

    my ($loginname) = @_;

    # Retrieve the user's ID from the database.
    my $quotedloginname = &::SqlQuote($loginname);
115 116 117 118 119 120 121 122 123 124 125
    &::SendSQL("SELECT profiles.userid, tokens.issuedate FROM profiles 
                    LEFT JOIN tokens
                    ON tokens.userid = profiles.userid
                    AND tokens.tokentype = 'password'
                    AND tokens.issuedate > DATE_SUB(NOW(), INTERVAL 10 MINUTE)
                    WHERE login_name = $quotedloginname");
    my ($userid, $toosoon) = &::FetchSQLData();

    if ($toosoon) {
        ThrowUserError('too_soon_for_new_token');
    };
126

127 128
    my $token_ts = time();

129 130 131
    # Generate a unique token and insert it into the tokens table.
    # We have to lock the tokens table before generating the token, 
    # since the database must be queried for token uniqueness.
132
    &::SendSQL("LOCK TABLES tokens WRITE");
133 134 135 136
    my $token = GenerateUniqueToken();
    my $quotedtoken = &::SqlQuote($token);
    my $quotedipaddr = &::SqlQuote($::ENV{'REMOTE_ADDR'});
    &::SendSQL("INSERT INTO tokens ( userid , issuedate , token , tokentype , eventdata )
137
                VALUES      ( $userid , NOW() , $quotedtoken , 'password' , $quotedipaddr )");
138 139 140
    &::SendSQL("UNLOCK TABLES");

    # Mail the user the token along with instructions for using it.
141 142 143 144 145
    
    my $template = $::template;
    my $vars = $::vars;

    $vars->{'token'} = $token;
146
    $vars->{'emailaddress'} = $loginname . Param('emailsuffix');
147

148 149 150
    $vars->{'max_token_age'} = $maxtokenage;
    $vars->{'token_ts'} = $token_ts;

151
    my $message = "";
152 153
    $template->process("account/password/forgotten-password.txt.tmpl", 
                                                               $vars, \$message)
154
      || ThrowTemplateError($template->error());
155

156
    Bugzilla::BugMail::MessageToMTA($message);
157 158 159
}


160 161 162
sub CleanTokenTable {
    &::SendSQL("LOCK TABLES tokens WRITE");
    &::SendSQL("DELETE FROM tokens 
163
                WHERE TO_DAYS(NOW()) - TO_DAYS(issuedate) >= " . $maxtokenage);
164 165 166 167
    &::SendSQL("UNLOCK TABLES");
}


168 169 170 171 172 173 174 175 176 177 178 179 180
sub GenerateUniqueToken {
    # Generates a unique random token.  Uses &GenerateRandomPassword 
    # for the tokens themselves and checks uniqueness by searching for
    # the token in the "tokens" table.  Gives up if it can't come up
    # with a token after about one hundred tries.

    my $token;
    my $duplicate = 1;
    my $tries = 0;
    while ($duplicate) {

        ++$tries;
        if ($tries > 100) {
181
            ThrowCodeError("token_generation_error");
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
        }

        $token = &::GenerateRandomPassword();
        &::SendSQL("SELECT userid FROM tokens WHERE token = " . &::SqlQuote($token));
        $duplicate = &::FetchSQLData();
    }

    return $token;

}


sub Cancel {
    # Cancels a previously issued token and notifies the system administrator.
    # This should only happen when the user accidentally makes a token request
    # or when a malicious hacker makes a token request on behalf of a user.
    
    my ($token, $cancelaction) = @_;

    # Quote the token for inclusion in SQL statements.
    my $quotedtoken = &::SqlQuote($token);
    
    # Get information about the token being cancelled.
    &::SendSQL("SELECT  issuedate , tokentype , eventdata , login_name , realname
                FROM    tokens, profiles 
                WHERE   tokens.userid = profiles.userid
                AND     token = $quotedtoken");
    my ($issuedate, $tokentype, $eventdata, $loginname, $realname) = &::FetchSQLData();

    # Get the email address of the Bugzilla maintainer.
212
    my $maintainer = Param('maintainer');
213

214 215
    my $template = $::template;
    my $vars = $::vars;
216

217
    $vars->{'emailaddress'} = $loginname . Param('emailsuffix');
218 219
    $vars->{'maintainer'} = $maintainer;
    $vars->{'remoteaddress'} = $::ENV{'REMOTE_ADDR'};
220
    $vars->{'token'} = $token;
221 222 223 224
    $vars->{'tokentype'} = $tokentype;
    $vars->{'issuedate'} = $issuedate;
    $vars->{'eventdata'} = $eventdata;
    $vars->{'cancelaction'} = $cancelaction;
225

226
    # Notify the user via email about the cancellation.
227

228
    my $message;
229
    $template->process("account/cancel-token.txt.tmpl", $vars, \$message)
230
      || ThrowTemplateError($template->error());
231

232
    Bugzilla::BugMail::MessageToMTA($message);
233 234

    # Delete the token from the database.
235
    &::SendSQL("LOCK TABLES tokens WRITE");
236 237 238 239
    &::SendSQL("DELETE FROM tokens WHERE token = $quotedtoken");
    &::SendSQL("UNLOCK TABLES");
}

240 241 242 243 244 245 246 247 248
sub DeletePasswordTokens {
    my ($userid, $reason) = @_;

    my $dbh = Bugzilla->dbh;
    my $sth = $dbh->prepare("SELECT token " .
                            "FROM tokens " .
                            "WHERE userid=? AND tokentype='password'");
    $sth->execute($userid);
    while (my $token = $sth->fetchrow_array) {
249
        Bugzilla::Token::Cancel($token, $reason);
250
    }
251 252
}

253 254 255 256 257
sub HasEmailChangeToken {
    # Returns an email change token if the user has one. 
    
    my ($userid) = @_;
    
258 259 260
    &::SendSQL("SELECT token FROM tokens WHERE userid = $userid " . 
               "AND (tokentype = 'emailnew' OR tokentype = 'emailold') " . 
               "LIMIT 1");
261 262 263 264 265 266
    my ($token) = &::FetchSQLData();
    
    return $token;
}


267
1;