Zend Framework Source Code Snippets

Zend_Auth_Adapter_MongoDb

Bookmark and Share
1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
27
28
29
3031
32
33
34
3536
37
38
39
4041
42
43
44
4546
47
48
49
5051
52
53
54
5556
57
58
59
6061
62
63
64
6566
67
68
69
7071
72
73
74
7576
77
78
79
8081
82
83
84
8586
87
88
89
9091
92
93
94
9596
97
98
99
100101
102
103
104
105106
107
108
109
110111
112
113
114
115116
117
118
119
120121
122
123
124
125126
127
128
129
130131
132
133
134
135136
137
138
139
140141
142
143
144
145146
147
148
149
150151
152
153
154
155156
157
158
159
160161
162
163
164
165166
167
168
169
170171
172
173
174
175176
177
178
179
180181
182
183
184
185186
187
188
189
190191
192
193
194
195196
197
198
199
200201
202
203
204
205206
207
208
209
210211
212
213
214
215216
217
218
219
220221
222
223
224
225226
227
228
229
230231
232
233
234
235236
237
238
239
240241
242
243
244
245246
247
248
249
250251
252
253
254
255256
257
258
259
260261
262
263
264
265266
267
268
269
270271
272
273
274
275276
277
278
279
280281
282
283
284
285286
287
288
289
290291
292
293
294
295296
297
298
299
300301
302
303
304
305306
307
308
309
310311
312
313
314
315316
317
318
319
320321
322
323
324
325326
327
328
329
<?php
 
class Zend_Auth_Adapter_MongoDb implements Zend_Auth_Adapter_Interface
{
     /**
     * Database collection
     *
     * @var MongoCollection
     */    protected $_collection = null;
 
    /**
     * $_identityKeyPath - the column to use as the identity
     *     * @var string
     */
    protected $_identityKeyPath = null;
 
    /**     * $_credentialKeyPaths - columns to be used as the credentials
     *
     * @var string
     */
    protected $_credentialKeyPath = null; 
    /**
     * $_identity - Identity value
     *
     * @var string     */
    protected $_identity = null;
 
    /**
     * $_credential - Credential values     *
     * @var string
     */
    protected $_credential = null;
     /**
     * $_credentialTreatment - Treatment applied to the credential, such as MD5() or PASSWORD()
     *
     * @var string
     */    protected $_credentialTreatment = null;
 
    /**
     * $_authenticateResultInfo
     *     * @var array
     */
    protected $_authenticateResultInfo = null;
 
    /**     * $_resultDoc - Results of database authentication query
     *
     * @var array
     */
    protected $_resultDoc = null; 
    /**
     * $_ambiguityIdentity - Flag to indicate same Identity can be used with
     * different credentials. Default is FALSE and need to be set to true to
     * allow ambiguity usage.     *
     * @var boolean
     */
    protected $_ambiguityIdentity = false;
     /**
     * __construct() - Sets configuration options
     *
     * @param  MongoCollection $collection If null, default database adapter assumed
     * @param  string                   $identityKeyPath     * @param  string                   $credentialKeyPath
     * @param  string                   $credentialTreatment
     * @return void
     */
    public function __construct(MongoCollection $collection = null, $identityKeyPath = null,                                $credentialKeyPath = null, $credentialTreatment = null)
    {
        $this->_setCollection($collection);
 
        if (null !== $identityKeyPath) {            $this->setIdentityKeyPath($identityKeyPath);
        }
 
        if (null !== $credentialKeyPath) {
            $this->setCredentialKeyPath($credentialKeyPath);        }
 
        if (null !== $credentialTreatment) {
            $this->setCredentialTreatment($credentialTreatment);
        }    }
 
    /**
     * _setCollection() - set the database adapter to be used for quering
     *     * @param MongoCollection
     * @throws Zend_Auth_Adapter_Exception
     * @return Ik_Auth_Adapter_MongoDb
     */
    protected function _setCollection(MongoCollection $collection = null)    {
        $this->_collection = $collection;
 
        /**
         * If no adapter is specified, fetch default database adapter.         */
        if(null === $this->_collection) {
            $this->_collection = Zend_Db_Collection_Abstract::getDefaultAdapter();
            if (null === $this->_collection) {
                throw new Zend_Auth_Adapter_Exception('No database adapter present');            }
        }
 
        return $this;
    } 
    /**
     * setIdentityKeyPath() - set the column name to be used as the identity column
     *
     * @param  string $identityKeyPath     * @return Ik_Auth_Adapter_MongoDb Provides a fluent interface
     */
    public function setIdentityKeyPath($identityKeyPath)
    {
        $this->_identityKeyPath = $identityKeyPath;        return $this;
    }
 
    /**
     * setCredentialKeyPath() - set the column name to be used as the credential column     *
     * @param  string $credentialKeyPath
     * @return Ik_Auth_Adapter_MongoDb Provides a fluent interface
     */
    public function setCredentialKeyPath($credentialKeyPath)    {
        $this->_credentialKeyPath = $credentialKeyPath;
        return $this;
    }
     /**
     * setCredentialTreatment() - allows the developer to pass a parameterized string that is
     * used to transform or treat the input credential data.
     *
     * In many cases, passwords and other sensitive data are encrypted, hashed, encoded,     * obscured, or otherwise treated through some function or algorithm. By specifying a
     * parameterized treatment string with this method, a developer may apply arbitrary SQL
     * upon input credential data.
     *
     * Examples:     *
     *  'PASSWORD(?)'
     *  'MD5(?)'
     *
     * @param  string $treatment     * @return Ik_Auth_Adapter_MongoDb Provides a fluent interface
     */
    public function setCredentialTreatment($treatment)
    {
        $this->_credentialTreatment = $treatment;        return $this;
    }
 
    /**
     * setIdentity() - set the value to be used as the identity     *
     * @param  string $value
     * @return Ik_Auth_Adapter_MongoDb Provides a fluent interface
     */
    public function setIdentity($value)    {
        $this->_identity = $value;
        return $this;
    }
     /**
     * setCredential() - set the credential value to be used, optionally can specify a treatment
     * to be used, should be supplied in parameterized form, such as 'MD5(?)' or 'PASSWORD(?)'
     *
     * @param  string $credential     * @return Ik_Auth_Adapter_MongoDb Provides a fluent interface
     */
    public function setCredential($credential)
    {
        $this->_credential = $credential;        return $this;
    }
 
    /**
     * setAmbiguityIdentity() - sets a flag for usage of identical identities     * with unique credentials. It accepts integers (0, 1) or boolean (true,
     * false) parameters. Default is false.
     *
     * @param  int|bool $flag
     * @return Ik_Auth_Adapter_MongoDb     */
    public function setAmbiguityIdentity($flag)
    {
        if (is_integer($flag)) {
            $this->_ambiguityIdentity = (1 === $flag ? true : false);        } elseif (is_bool($flag)) {
            $this->_ambiguityIdentity = $flag;
        }
        return $this;
    }    /**
     * getAmbiguityIdentity() - returns TRUE for usage of multiple identical
     * identies with different credentials, FALSE if not used.
     *
     * @return bool     */
    public function getAmbiguityIdentity()
    {
        return $this->_ambiguityIdentity;
    } 
    /**
     * getResultDocObject() - Returns the result row as a stdClass object
     *
     * @param  string|array $returnColumns     * @param  string|array $omitColumns
     * @return stdClass|boolean
     */
    public function getResultDocObject($returnColumns = null, $omitColumns = null)
    {        if (!$this->_resultDoc) {
            return false;
        }
        
        return $this->_resultDoc;     }
 
    /**
     * authenticate() - defined by Zend_Auth_Adapter_Interface.  This method is called to
     * attempt an authentication.  Previous to this call, this adapter would have already     * been configured with all necessary information to successfully connect to a database
     * collection and attempt to find a record matching the provided identity.
     *
     * @throws Zend_Auth_Adapter_Exception if answering the authentication query is impossible
     * @return Zend_Auth_Result     */
    public function authenticate()
    {
        $this->_authenticateSetup();
                $cursor = $this->_collection->find(array(
            $this->_identityKeyPath => $this->_identity
        ));
 
        $count = $cursor->count();         if ($count == 0) {
            $this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND;
            $this->_authenticateResultInfo['messages'][] = 'A record with the supplied identity could not be found.';
        } elseif ($count == 1) {
            $resultIdentity = $cursor->getNext();            $this->_resultDoc = $resultIdentity;
            if ($resultIdentity[$this->_credentialKeyPath] == $this->_credential) {
                $this->_authenticateResultInfo['code'] = Zend_Auth_Result::SUCCESS;
                $this->_authenticateResultInfo['messages'][] = 'Authentication successful.';
            } else {                $this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID;
                $this->_authenticateResultInfo['messages'][] = 'Supplied credential is invalid.';
            }   
        } elseif ($count > 1) {
            $this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS;            $this->_authenticateResultInfo['messages'][] = 'More than one record matches the supplied identity.';
        }
        
        $authResult = $this->_authenticateCreateAuthResult();        
         return $authResult;
    }
 
    /**
     * _authenticateSetup() - This method abstracts the steps involved with     * making sure that this adapter was indeed setup properly with all
     * required pieces of information.
     *
     * @throws Zend_Auth_Adapter_Exception - in the event that setup was not done properly
     * @return true     */
    protected function _authenticateSetup()
    {
        $exception = null;
         if ($this->_identityKeyPath == '') {
            $exception = 'An identity column must be supplied for the Ik_Auth_Adapter_MongoDb authentication adapter.';
        } elseif ($this->_credentialKeyPath == '') {
            $exception = 'A credential column must be supplied for the Ik_Auth_Adapter_MongoDb authentication adapter.';
        } elseif ($this->_identity == '') {            $exception = 'A value for the identity was not provided prior to authentication with Ik_Auth_Adapter_MongoDb.';
        } elseif ($this->_credential === null) {
            $exception = 'A credential value was not provided prior to authentication with Ik_Auth_Adapter_MongoDb.';
        }
         if (null !== $exception) {
            throw new Zend_Auth_Adapter_Exception($exception);
        }
 
        $this->_authenticateResultInfo = array(            'code'     => Zend_Auth_Result::FAILURE,
            'identity' => $this->_identity,
            'messages' => array()
            );
         return true;
    }
 
    /**
     * _authenticateCreateAuthResult() - Creates a Zend_Auth_Result object from     * the information that has been collected during the authenticate() attempt.
     *
     * @return Zend_Auth_Result
     */
    protected function _authenticateCreateAuthResult()    {
        return new Zend_Auth_Result(
            $this->_authenticateResultInfo['code'],
            $this->_authenticateResultInfo['identity'],
            $this->_authenticateResultInfo['messages']            );
    }
 
}

Comments

serverul serverul
3 years ago

Great snippet, but there is one thing missing: $_credentialTreatment is never used and the password is always checked using the plain $_credential.

Thanks for the code though :)

Jose F Jose F
3 years ago

Good ! Actually, I was creating a snippet for the same task, but this is great ! thanks

AndDM AndDM
2 years ago

Hi, i'm Zend's new user and i'm trying to use this class to get document information without password columns with:

$doc = $adapter->getResultDocObject(null, 'password');
$auth->getStorage()->write($doc);
$ns = new Zend_Session_Namespace('ciaoMondo');
$ns->user = $doc;

It return all colums with password too. I've tryed with array and other, without result.

Could someone give me some informations about that?

Thanks, regards.

magnums magnums
1 year ago

Hi.
I am new user of ZF but i want to create login page authen user in mongodb. I think your class will meet my requirement. So i want to use this class with ZF 1.12.0. but i don't know how to use it. Do you have some example? or
how can i do that? Please advice.

Thank you in advance.

Satit P.

You must login before commenting on a snippet. If you do not have an account, please register.

Snippet description

Zend Auth Adapter for MongoDB

Snippet details

Created:
ZedroXyMur ZedroXyMur
3 years ago
Edited:
ZedroXyMur ZedroXyMur
3 years ago
Revision Id:
187
Edit Message:
Initial Release
ZF Version
1.8.3
Tags:
auth mongo mongodb zend adapter collection
Comments:
4
Views:
8736
Points:
2 (2 votes)

History

r187

Initial Release

ZedroXyMur ZedroXyMur
3 years ago