File: Auth.php

package info (click to toggle)
php-mongo 1.4.5-1~bpo70%2B1
  • links: PTS
  • area: main
  • in suites: wheezy-backports
  • size: 9,828 kB
  • sloc: ansic: 13,275; xml: 1,702; php: 1,625; pascal: 255; makefile: 106; sh: 27
file content (222 lines) | stat: -rw-r--r-- 6,517 bytes parent folder | download | duplicates (2)
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
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
212
213
214
215
216
217
218
219
220
221
222
<?php
/**
 *  Copyright 2009 10gen, Inc.
 * 
 *  Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 * PHP version 5 
 *
 * @category Database
 * @package  Mongo
 * @author   Kristina Chodorow <kristina@10gen.com>
 * @license  http://www.apache.org/licenses/LICENSE-2.0  Apache License 2
 * @version  CVS: 000000
 * @link     http://www.mongodb.org
 */

require_once "Mongo/Util.php";

/**
 * Gets an authenticated database connection.
 *
 * A typical usage would be:
 * <code>
 * // initial login
 * $auth_connection = new MongoAuth();
 * $auth->login("mydb", "joe", "mypass");
 * if (!$auth_connection->loggedIn) {
 *    return $auth_connection->error;
 * }
 * setcookie("username", "joe");
 * setcookie("password", MongoAuth::getHash("joe", "mypass"));
 * </code>
 *
 * Then, for subsequent sessions, the cookies can be used to log in:
 * <code>
 * $username = $_COOKIE['username'];
 * $password = $_COOKIE['password'];
 * $auth_connection = new MongoAuth();
 * $auth_connection->login("mydb", $username, $password, false);
 * </code>
 *
 * @category Database
 * @package  Mongo
 * @author   Kristina Chodorow <kristina@10gen.com>
 * @license  http://www.apache.org/licenses/LICENSE-2.0  Apache License 2
 * @link     http://www.mongodb.org
 */
class MongoAuth extends Mongo
{

    public $db;

    /**
     * Communicates with the database to log in a user.
     * 
     * @param MongoDB $db       database
     * @param string  $username username
     * @param string  $pwd      plaintext password
     *
     * @return array the database response
     */
    protected static function getUser($db, $username, $pwd) 
    {
        $ns = "${db}.system.users";

        // get the nonce
        $result = $db->command(array(MongoUtil::NONCE => 1 ));
        if (!$result["ok"]) {
            return $result;
        }
        $nonce = $result[ "nonce" ];

        // create a digest of nonce/username/pwd
        $digest = md5($nonce . $username . $pwd);
        $data   = array(MongoUtil::AUTHENTICATE => 1, 
                        "user" => $username, 
                        "nonce" => $nonce,
                        "key" => $digest);

        // send everything to the db and pray
        return $db->command($data);
    }

    /**
     * Creates a hashed string from the username and password.
     * This string can be passed to MongoAuth->__construct as the password
     * with $plaintext set to false in order to login.
     *
     * @param string $username the username
     * @param string $password the password
     *
     * @return string the md5 hash of the username and password
     */
    public static function getHash($username, $password) 
    {
        return md5("${username}:mongo:${password}");
    }

    /**
     * Logs in to a given database.
     *
     * @param string $db        the name of the db
     * @param string $username  the username
     * @param string $password  the password
     * @param string $plaintext if the password is encrypted     
     *
     * @return bool if login was successful
     */
    public function login($db, 
                          $username, 
                          $password, 
                          $plaintext=true) 
    {
        $this->db = $this->selectDB((string)$db);

        if ($plaintext) {
            $hash = MongoAuth::getHash($username, $password);
        } else {
            $hash = $password;
        }

        $result = MongoAuth::getUser($this->db, $username, $hash);

        if ($result['ok'] != 1) {
            $this->error = 'couldn\'t log in';
            $this->code  = -3;
        }
        return $this->loggedIn = (bool)$result['ok'];
    }


    /**
     * Creates a new user.
     * This will not overwrite existing users, use MongoAuth::changePassword
     * to change a user's password.
     *
     * @param string $username the new user's username
     * @param string $password the new user's password
     * 
     * @return boolean if the new user was successfully created
     */
    public function addUser($username, $password) 
    {
        $c      = $this->db->selectCollection('system.users');
        $exists = $c->findOne(array('user' => $username));
        if ($exists) {
            return false;
        }
        $newUser = array('user' => $username,
                         'pwd' => MongoAuth::getHash($username, $password));
        $c->insert($newUser);
        return true;
    }



    /**
     * Changes a user's password.
     *
     * @param string $username the username
     * @param string $oldpass  the old password
     * @param string $newpass  the new password
     *
     * @return array whether the change was successful
     */
    public function changePassword($username, $oldpass, $newpass) 
    {
        $c    = $this->db->selectCollection('system.users');
        $user = $c->findOne(array('user' => $username));
        if (!$user) {
            return array('ok' => -2.0,
                         'errmsg' => 'no user with username $username found');
        }
        if ($user['pwd'] == MongoAuth::getHash($username, $oldpass)) {
            $user['pwd'] = MongoAuth::getHash($username, $newpass);
            $c->update(array('user'=>$username), $user);
            return array('ok' => 1.0);
        }
        return array('ok' => -1.0,
                     'errmsg' => 'incorrect old password');
    }


    /**
     * Delete a user.
     *
     * @param string $username the user to delete
     *
     * @return boolean if the user was deleted
     */
    public function deleteUser($username) 
    {
        $c = $this->db->selectCollection('system.users');
        $b = $c->remove(array('user' => (string)$username), true);
        // force the database to do the remove asap
        $c->findOne();
        return $b;
    }


    /**
     * Ends authenticated session.
     *
     * @return array database response
     */
    public function logout() 
    {
        return $this->db->command(array(MongoUtil::LOGOUT => 1));
    }

}