MoneyExchange

MonyChange, MacSystem

MoneyExchange es un software de gestión para medianas y grandes Empresas que permite automatizar la operatividad global de las Casas de Cambio. Integra las operaciones de todas las sucursales de forma sencilla y segura.

Leer mas

Alfresco

Alfresco, MacSystem

Alfresco proporciona todos los servicios de gestión de documentos esenciales necesarios para permitir a las organizaciones capturar y gestionar archivos electrónicos y automatizar procesos que se centran en la gestión de documentos.

Microcompany

Microcompany, MacSystem

Moderno Sistema de Gestion Integrado disenado para simplificar la administracion de pequenas empresas, tiendas mayoristas, minimarkets, empresas de servicios y todo tipo de negocio..

bdswiss

 

Integración de Doctrine 1 con Zend Framework

 

Bajar Doctrine
http://www.doctrine-project.org/downloads/Doctrine-1.2.4.tgz

*descomprimir y copiar archivos que estan en lib a
/projects/planillas/library

Crear siguiente estructura de directorios
/projects/planillas/doctrine/data/fixtures
                                                       /sql
                                               /migrations
                                               /schema
                                /bin

Editar el /projects/planillas/application/configs/application.ini

doctrine.connection_string = "mysql://root:alumno@127.0.0.1/planilla"
doctrine.data_fixtures_path = APPLICATION_PATH "/../doctrine/data/fixtures"
doctrine.models_path = APPLICATION_PATH "/models"
doctrine.migrations_path = APPLICATION_PATH "/../doctrine/migrations"
doctrine.sql_path = APPLICATION_PATH "/../doctrine/data/sql"
doctrine.yaml_schema_path = APPLICATION_PATH "/../doctrine/schema"
autoloaderNamespaces[] = "Doctrine"  


Editar el BootStrap de ZendFramework para integrar Doctrine en la aplicación
/projects/planillas/application/Bootstrap.php
<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
   protected function _initDoctrine()
    {
        require_once 'Doctrine.php';        

        $loader = Zend_Loader_Autoloader::getInstance();
        //$loader->pushAutoloader(array('Doctrine', 'autoload'));
        $loader->registerNamespace('Doctrine')->pushAutoloader(array('Doctrine', 'modelsAutoload'), '');
        $doctrineConfig = $this->getOption('doctrine');
        $manager = Doctrine_Manager::getInstance();

        $manager->setAttribute(
            Doctrine::ATTR_MODEL_LOADING,
            Doctrine::MODEL_LOADING_CONSERVATIVE
        );    
 
        // Add models and generated base classes to Doctrine autoloader
        Doctrine::loadModels($doctrineConfig['models_path']);
        $manager->openConnection($doctrineConfig['connection_string']);    
        return $manager;
    }    
}

Crear script para doctrine (sirve para crear las clases del modelo, generar el sql, yaml, etc)

/projects/planillas/bin/doctrine
#!/usr/bin/env php
<?php
/**
 * Doctrine CLI script
 */
 
define('APPLICATION_ENV', 'development');
 
define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
set_include_path(implode(PATH_SEPARATOR, array(
    realpath(APPLICATION_PATH . '/../library'),
    realpath(APPLICATION_PATH . '/../library/vendor'),
    get_include_path(),
)));
 
require_once 'Zend/Application.php';

require_once APPLICATION_PATH ."/../library/Doctrine/Parser/sfYaml/sfYaml.php";
// Create application, bootstrap, and run
$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/configs/application.ini'
);

$application->getBootstrap()->bootstrap('doctrine');

if(!isset($argv[1])){
        echo "./doctrine importdata /path/to/yaml\n";
}

// Opcion para importar data de YAML
if(isset($argv[1]) && $argv[1]=="importdata"){
        if(is_file($argv[2])){
                Doctrine_Core::loadData($argv[2]);
                echo "Data Importada\n";
                exit();
        }else{
                echo "No existe el archivo ".$argv[2]."\n";
        }
}

$cli = new Doctrine_Cli($application->getOption('doctrine'));
$cli->run($_SERVER['argv']);
                           
$> cd /projects/planillas/bin
$> chmod 755 doctrine
$> ./doctrine

 

Crear Archivo YAML para las tablas del sistema

/projects/planillas/doctrine/schema/schema.yml

Usuario:
  connection: 0
  tableName: usuario
  columns:
    id_usuario:
      type: integer(4)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: true
    username:
      type: string(50)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    pass:
      type: string(32)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    nombres:
      type: string(250)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
    apellidos:
      type: string(250)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false

    perfil:
      type: string(30)
      fixed: false
      unsigned: false
      primary: false
      default: usuario
      notnull: false
      autoincrement: false
    fecha_creacion:
      type: timestamp(25)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false

 

Crear archivo YAML para la insercion inicial de data

/projects/planillas/doctrine/data/fixtures/data.yml
Usuario:
  Usuario_1:
    username: admin
    pass: c6865cf98b133f1f3de596a4a2894630
    nombres: Tuxito
    apellidos: Developer

    perfil: admin
    fecha_creacion: '2011-07-09 16:06:56'


Crear la base de Datos
$> cd /projects/planillas/bin

$>./doctrine create-db

 

Generar clases del modelo a partir del archivo YAML

$> ./doctrine generate-models-yaml

 

Crear las Tablas de la Aplicacion leyendo el archivo yaml

$>./doctrine create-tables

 

Importar los datos Iniciales a la Aplicación

$> ./doctrine importdata /projects/planillas/doctrine/data/fixtures/data.yml

 

Verificar las clases de modelo

$> ls /projects/planillas/application/models

 

 

Autenticación y Sesiones con Zend Framework  y Doctrine

 

Creamos el controlador login

create controller login

 

Editamos el formulario

/projects/planillas/application/modules/admin/views/scripts/login/index.phtml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<form action="" method="post" name="formlogin" id="formlogin">
    <table width="362" align="center">
    <tr>
      <td colspan="2"><div align="center"><strong><font size="4">Login</font></strong></div></td>
    </tr>
    <tr>
      <td width="112">User</td>
      <td width="372"><input name="username" type="text" id="username"></td>
    </tr>
    <tr>
      <td>Password</td>
      <td><input name="pass" type="password" id="pass"></td>
    </tr>
    <tr>
      <td> </td>
      <td><input type="submit" value="Aceptar" id="aceptar"></td>
    </tr>
  </table>
  <div align="center" id="mensaje">
  </div>
<div align="center"><h3><font color="#990000"><?php echo $this->mensaje;?></font></h3></div>
</form>

 

Deshabilitamos el Layout para que el formulario del Login se muestre antes de acceder al sistema

/projects/planillas/application/controllers/LoginController.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class LoginController extends Zend_Controller_Action
{
 
    public function init()
    {
        /* Initialize action controller here */
    }
 
    public function indexAction()
    {
       $this->_helper->layout()->disableLayout();
    }
 
 
}

 

Ahora editaremos el controlador para realizar la autenticación, usaremos el proveedor de Doctrine ZendX_Doctrine_Auth_Adapter

http://framework.zend.com/svn/framework/extras/incubator/library/ZendX/Doctrine/Auth/Adapter.php
 

/projects/planillas/library/ZendX/Doctrine/Auth/Adapter.php

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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to Esta dirección de correo electrónico está protegida contra spambots. Usted necesita tener Javascript activado para poder verla. so we can send you a copy immediately.
 *
 * @category   ZendX
 * @package    ZendX_Doctrine
 * @subpackage ZendX_Doctrine_Auth_Adapter
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id: $
 */
 
 
/**
 * @see Zend_Auth_Adapter_Interface
 */
require_once 'Zend/Auth/Adapter/Interface.php';
 
/**
 * @see Doctrine_Connection
 */
require_once 'Doctrine/Connection.php';
 
/**
 * @see Zend_Auth_Result
 */
require_once 'Zend/Auth/Result.php';
 
 
/**
 * @category   Zend
 * @package    Zend_Auth
 * @subpackage Zend_Auth_Adapter
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class ZendX_Doctrine_Auth_Adapter implements Zend_Auth_Adapter_Interface
{
    /**
     * Database Connection
     *
     * @var Doctrine_Connection
     */
    protected $_conn = null;
 
    /**
     * $_tableName - the table name to check
     *
     * @var string
     */
    protected $_tableName = null;
 
    /**
     * $_identityColumn - the column to use as the identity
     *
     * @var string
     */
    protected $_identityColumn = null;
 
    /**
     * $_credentialColumns - columns to be used as the credentials
     *
     * @var string
     */
    protected $_credentialColumn = 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;
     
    /**
     * $_resultRow - Results of database authentication query
     *
     * @var array
     */
    protected $_resultRow = null;
 
    /**
     * __construct() - Sets configuration options
     *
     * @param  Doctrine_Connection      $zendDb
     * @param  string                   $tableName
     * @param  string                   $identityColumn
     * @param  string                   $credentialColumn
     * @param  string                   $credentialTreatment
     * @return void
     */
    public function __construct(Doctrine_Connection $conn = null, $tableName = null, $identityColumn = null,
                                $credentialColumn = null, $credentialTreatment = null)
    {
        if (null !== $conn) {
            $this->setConnection($conn);
        }
 
        if (null !== $tableName) {
            $this->setTableName($tableName);
        }
 
        if (null !== $identityColumn) {
            $this->setIdentityColumn($identityColumn);
        }
 
        if (null !== $credentialColumn) {
            $this->setCredentialColumn($credentialColumn);
        }
 
        if (null !== $credentialTreatment) {
            $this->setCredentialTreatment($credentialTreatment);
        }
    }
     
    /**
     * setConnection() - set the connection to the database
     *
     * @param  Doctrine_Connection $conn
     * @return ZendX_Doctrine_Auth_Adapter Provides a fluent interface
     */
    public function setConnection(Doctrine_Connection $conn)
    {
        $this->_conn = $conn;
        return $this;
    }
     
    /**
     * getConnection() - get the connection to the database
     *
     * @return Doctrine_Connection|null
     */
    public function getConnection()
    {
        if (null === $this->_conn &&
            null !== $this->_tableName) {
             
            $this->_conn = Doctrine::getConnectionByTableName($this->_tableName);
        }
         
        return $this->_conn;
    }
 
    /**
     * setTableName() - set the table name to be used in the select query
     *
     * @param  string $tableName
     * @return ZendX_Doctrine_Auth_Adapter Provides a fluent interface
     */
    public function setTableName($tableName)
    {
        $this->_tableName = $tableName;
        return $this;
    }
 
    /**
     * setIdentityColumn() - set the column name to be used as the identity column
     *
     * @param  string $identityColumn
     * @return ZendX_Doctrine_Auth_Adapter Provides a fluent interface
     */
    public function setIdentityColumn($identityColumn)
    {
        $this->_identityColumn = $identityColumn;
        return $this;
    }
 
    /**
     * setCredentialColumn() - set the column name to be used as the credential column
     *
     * @param  string $credentialColumn
     * @return ZendX_Doctrine_Auth_Adapter Provides a fluent interface
     */
    public function setCredentialColumn($credentialColumn)
    {
        $this->_credentialColumn = $credentialColumn;
        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 ZendX_Doctrine_Auth_Adapter 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 ZendX_Doctrine_Auth_Adapter 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 ZendX_Doctrine_Auth_Adapter Provides a fluent interface
     */
    public function setCredential($credential)
    {
        $this->_credential = $credential;
        return $this;
    }
 
    /**
     * getResultRowObject() - Returns the result row as a stdClass object
     *
     * @param  string|array $returnColumns
     * @param  string|array $omitColumns
     * @return stdClass|boolean
     */
    public function getResultRowObject($returnColumns = null, $omitColumns = null)
    {
        if (!$this->_resultRow) {
            return false;
        }
         
        $returnObject = new stdClass();
 
        if (null !== $returnColumns) {
 
            $availableColumns = array_keys($this->_resultRow);
            foreach ( (array) $returnColumns as $returnColumn) {
                if (in_array($returnColumn, $availableColumns)) {
                    $returnObject->{$returnColumn} = $this->_resultRow[$returnColumn];
                }
            }
            return $returnObject;
 
        } elseif (null !== $omitColumns) {
 
            $omitColumns = (array) $omitColumns;
            foreach ($this->_resultRow as $resultColumn => $resultValue) {
                if (!in_array($resultColumn, $omitColumns)) {
                    $returnObject->{$resultColumn} = $resultValue;
                }
            }
            return $returnObject;
 
        } else {
 
            foreach ($this->_resultRow as $resultColumn => $resultValue) {
                $returnObject->{$resultColumn} = $resultValue;
            }
            return $returnObject;
 
        }
    }
 
    /**
     * 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
     * table 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();
        $dbSelect = $this->_authenticateCreateSelect();
        $resultIdentities = $this->_authenticateQuerySelect($dbSelect);
         
        if ( ($authResult = $this->_authenticateValidateResultset($resultIdentities)) instanceof Zend_Auth_Result) {
            return $authResult;
        }
         
        $authResult = $this->_authenticateValidateResult(array_shift($resultIdentities));
        return $authResult;
    }
 
    /**
     * _authenticateSetup() - This method abstracts the steps involved with making sure
     * that this adapter was indeed setup properly with all required peices 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->getConnection() === null) {
            $exception = 'A database connection was not set, nor could one be created.';
        } elseif ($this->_tableName == '') {
            $exception = 'A table must be supplied for the ZendX_Doctrine_Auth_Adapter authentication adapter.';
        } elseif ($this->_identityColumn == '') {
            $exception = 'An identity column must be supplied for the ZendX_Doctrine_Auth_Adapter authentication adapter.';
        } elseif ($this->_credentialColumn == '') {
            $exception = 'A credential column must be supplied for the ZendX_Doctrine_Auth_Adapter authentication adapter.';
        } elseif ($this->_identity == '') {
            $exception = 'A value for the identity was not provided prior to authentication with ZendX_Doctrine_Auth_Adapter.';
        } elseif ($this->_credential === null) {
            $exception = 'A credential value was not provided prior to authentication with ZendX_Doctrine_Auth_Adapter.';
        }
 
        if (null !== $exception) {
            /**
             * @see Zend_Auth_Adapter_Exception
             */
            require_once 'Zend/Auth/Adapter/Exception.php';
            throw new Zend_Auth_Adapter_Exception($exception);
        }
         
        $this->_authenticateResultInfo = array(
            'code'     => Zend_Auth_Result::FAILURE,
            'identity' => $this->_identity,
            'messages' => array()
            );
             
        return true;
    }
 
    /**
     * _authenticateCreateSelect() - This method creates a Zend_Db_Select object that
     * is completely configured to be queried against the database.
     *
     * @return Doctrine_Query
     */
    protected function _authenticateCreateSelect()
    {
        // build credential expression
        if (empty($this->_credentialTreatment) || (strpos($this->_credentialTreatment, "?") === false)) {
            $this->_credentialTreatment = '?';
        }
         
        $dbSelect = Doctrine_Query::create($this->getConnection())
                    ->from($this->_tableName)
                    ->select('*, ('.$this->_credentialColumn.' = '.str_replace('?',
                        $this->getConnection()->quote($this->_credential), $this->_credentialTreatment).') AS zend_auth_credential_match')
                    ->addWhere($this->_identityColumn .' = ?', $this->_identity);
 
        return $dbSelect;
    }
 
    /**
     * _authenticateQuerySelect() - This method accepts a Doctrine_Query object and
     * performs a query against the database with that object.
     *
     * @param Doctrine_Query $dbSelect
     * @throws Zend_Auth_Adapter_Exception - when a invalid select object is encoutered
     * @return array
     */
    protected function _authenticateQuerySelect(Doctrine_Query $dbSelect)
    {
        try {
            $resultIdentities = $dbSelect->execute()->toArray();
        } catch (Exception $e) {
            /**
             * @see Zend_Auth_Adapter_Exception
             */
            require_once 'Zend/Auth/Adapter/Exception.php';
            throw new Zend_Auth_Adapter_Exception('The supplied parameters to Zend_Auth_Adapter_Doctrine_Record failed to '
                                                . 'produce a valid sql statement, please check table and column names '
                                                . 'for validity.');
        }
        return $resultIdentities;
    }
 
    /**
     * _authenticateValidateResultSet() - This method attempts to make certian that only one
     * record was returned in the result set
     *
     * @param array $resultIdentities
     * @return true|Zend_Auth_Result
     */
    protected function _authenticateValidateResultSet(array $resultIdentities)
    {
 
 
        if (count($resultIdentities) < 1) {
            $this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND;
            $this->_authenticateResultInfo['messages'][] = 'A record with the supplied identity could not be found.';
            return $this->_authenticateCreateAuthResult();
        } elseif (count($resultIdentities) > 1) {
            $this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_IDENTITY_AMBIGUOUS;
            $this->_authenticateResultInfo['messages'][] = 'More than one record matches the supplied identity.';
            return $this->_authenticateCreateAuthResult();
        }
 
        return true;
    }
 
    /**
     * _authenticateValidateResult() - This method attempts to validate that the record in the
     * result set is indeed a record that matched the identity provided to this adapter.
     *
     * @param array $resultIdentity
     * @return Zend_Auth_Result
     */
    protected function _authenticateValidateResult($resultIdentity)
    {
        if ($resultIdentity['zend_auth_credential_match'] != '1') {
            $this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID;
            $this->_authenticateResultInfo['messages'][] = 'Supplied credential is invalid.';
            return $this->_authenticateCreateAuthResult();
        }
 
        unset($resultIdentity['zend_auth_credential_match']);
        $this->_resultRow = $resultIdentity;
 
        $this->_authenticateResultInfo['code'] = Zend_Auth_Result::SUCCESS;
        $this->_authenticateResultInfo['messages'][] = 'Authentication successful.';
        return $this->_authenticateCreateAuthResult();
    }
     
    /**
     * _authenticateCreateAuthResult() - This method 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']
            );
    }
 }

 

Luego editamos el controlador del Login

/projects/planillas/application/controllers/LoginController.php

 

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
class LoginController extends Zend_Controller_Action {
 
    public function init()
    {              
         // Iniciando la sesion
         $this->_session = new Zend_Session_Namespace('planilla');
         $this->auth = Zend_Auth::getInstance();            
    }
 
    public function indexAction() {
        $this->_helper->layout()->disableLayout();
        // Verificando si el usuario ya se logueo
        if (!$this->auth->hasIdentity()) {
            $this->view->mensaje = "";
            // verificando si se envio el formulario
            if ($this->getRequest()->getParam('username') && $this->getRequest()->getParam('pass')) {
                $loginUsername = $this->getRequest()->getParam('username', '');
                $loginPassword = $this->getRequest()->getParam('pass', '');
                // verificando si los campos del formulario no esten vacios
                if (empty($loginUsername) || empty($loginPassword)) {
                    $this->view->mensaje = "Llene todos los campos de user y Password";
                } else {
                    // Proceso de Autenticación;
                    require "ZendX/Doctrine/Auth/Adapter.php";
                    $myAuth = Zend_Auth::getInstance();
                    // do the authentication
                    $authAdapter = $this->_getAuthAdapter($loginUsername, $loginPassword);
                    $result = $myAuth->authenticate($authAdapter);
                    if (!$result->isValid()) {
                        $this->view->mensaje = "Usuario o Password Incorrecto";
                    } else {
                        // borranbdo el password de la sesion
                        $identity = $authAdapter->getResultRowObject(null, 'pass');
                        $myAuth->getStorage()->write($identity);
                        // Registrado variables de sesion
                        $this->_session->nombre = "Gran Administrador";
                        $this->_session->username = $loginUsername;
                        $this->_session->rol = "admin";
                        // Redireccionando al index del modulo admin
                        $this->_redirect('/admin');
                    }
                }
            }
        } else {
            // Si el usuario ya esta logueado se le redirecciona al modulo admin
            $this->_redirect('/admin');
        }
    }
 
    protected function _getAuthAdapter($username, $password) {
        $authAdapter = new ZendX_Doctrine_Auth_Adapter(Doctrine::getConnectionByTableName('usuario'));
        $authAdapter->setTableName('Usuario u')
                ->setIdentityColumn('u.username')
                ->setCredentialColumn('u.pass')
                ->setCredentialTreatment('md5(?)')
                ->setIdentity($username)
                ->setCredential($password);
        return $authAdapter;
    }
}
Saturday the 19th - - HostAfford.com