<?php/** * CakePHP(tm) Path File: \App\Controller\AppController.php */namespaceApp\Controller;useCake\Controller\Controller;useCake\Event\Event;/** * Application Controller * Add your application-wide methods in the class below, your controllers * will inherit them. * @link http://book.cakephp.org/3.0/en/controllers.html#the-app-controller */classAppControllerextendsController{/** * Initialization hook method. * Use this method to add common initialization code like loading components. * e.g. `$this->loadComponent('Security');` * @return void */publicfunctioninitialize(){parent::initialize();$this->loadComponent('RequestHandler');$this->loadComponent('Flash');// Set Full Auth via Form$this->loadComponent('Auth',['authorize'=>['Controller'],'loginRedirect'=>['controller'=>'Pages',// @todo Mi Controller segun PROYECTO a modo de demo'action'=>'display','home'],'logoutRedirect'=>['controller'=>'Usuarios',// @todo Mi Controller segun PROYECTO'action'=>'login'],'loginAction'=>['controller'=>'Usuarios',// @todo Mi Controller segun PROYECTO'action'=>'login'],'authenticate'=>['Form'=>[//'passwordHasher' => 'Blowfish','userModel'=>'Usuarios',// @todo Mi TABLA segun DB'fields'=>['username'=>'email','password'=>'password'],// @todo mis campos personalizados segun DB'scope'=>['Usuarios.habilitado'=>1]// @todo Filtro para bloquiar ingresos de usuarios activos segun DB]],'authError'=>'¿De verdad crees que se le permita ver eso?','storage'=>'Session']);}/** * @param $usuario * * @return bool */publicfunctionisAuthorized($usuario=array()){// Tipo de permiso es Admin..?if(true===isset($usuario['perfiles_id'])&&$usuario['perfiles_id']==='1'){// @todo Codigo a cambiar segun DB y PROYECTO// Permitirreturntrue;}else{// Denegarreturnfalse;}}/** * @param Event $event An Event instance * * @return void */publicfunctionbeforeFilter(Event$event){parent::beforeFilter($event);// Bloquiar todo$this->Auth->deny();// Es Admin..?if($this->Auth->user('perfiles_id')===1){// @todo Codigo a cambiar segun DB y PROYECTO// Permitir todo al Admin$this->Auth->allow();}else{// Es anonimo..?$this->Auth->allow(['index','view','display','contactarnos','registrarce','logout']);// @todo Codigo a cambiar segun DB y PROYECTO}}/** * Before render callback. * * @param \Cake\Event\Event $event The beforeRender event. * * @return void */publicfunctionbeforeRender(Event$event){if(!array_key_exists('_serialize',$this->viewVars)&&in_array($this->response->type(),['application/json','application/xml'])){$this->set('_serialize',true);}}}
<?php// Path File: \App\src\Model\Entity\Usuario.phpnamespaceApp\Model\Entity;useCake\ORM\Entity;useCake\Auth\DefaultPasswordHasher;/** * Usuario Entity. * @property int $id * @property string $email * @property string $password * @property string $nombre * @property int $perfiles_id * @property \App\Model\Entity\Perfile $perfile * @property bool $habilitado * @property \Cake\I18n\Time $created * @property \Cake\I18n\Time $modified */classUsuarioextendsEntity{/** * Fields that can be mass assigned using newEntity() or patchEntity(). * Note that when '*' is set to true, this allows all unspecified fields to * be mass assigned. For security purposes, it is advised to set '*' to false * (or remove it), and explicitly make individual fields accessible as needed. * @var array */protected$_accessible=['*'=>true,'id'=>false,];protectedfunction_setPassword($password){return(newDefaultPasswordHasher)->hash($password);}}
<?phpnamespaceApp\Controller;useApp\Controller\AppController;useCake\Event\Event;/** * Path File: \App\Controller\UsuariosController.php * Usuarios Controller * * @property \App\Model\Table\UsuariosTable $Usuarios */classUsuariosControllerextendsAppController{publicfunctionlogout(){$session=$this->request->session();$session->destroy();$this->Flash->success(__('El usuario cerro session correctamente!'));return$this->redirect($this->Auth->logout());}publicfunctionlogin(){if($this->request->is('post')){// Existe el usuario ..?$user=$this->Auth->identify();if($user!=false){// Set Storage$this->Auth->setUser($user);if($this->Auth->authenticationProvider()->needsPasswordRehash()){$user=$this->Users->get($this->Auth->user('id'));$user->password=$this->request->data('password');// Save Usuario$this->Users->save($user);}return$this->redirect($this->Auth->redirectUrl());}else{// Set Flash Auth$this->Flash->error(__('Usuario o Clave es incorrecta'),['key'=>'auth']);}}}/** * Index method * * @return void */publicfunctionindex(){$this->paginate=['contain'=>['Perfiles']];$this->set('usuarios',$this->paginate($this->Usuarios));$this->set('_serialize',['usuarios']);}/** * View method * * @param string|null $id Usuario id. * @return void * @throws \Cake\Network\Exception\NotFoundException When record not found. */publicfunctionview($id=null){$usuario=$this->Usuarios->get($id,['contain'=>['Perfiles']]);$this->set('usuario',$usuario);$this->set('_serialize',['usuario']);}/** * Add method * * @return void Redirects on successful add, renders view otherwise. */publicfunctionadd(){$usuario=$this->Usuarios->newEntity();if($this->request->is('post')){$usuario=$this->Usuarios->patchEntity($usuario,$this->request->data);if($this->Usuarios->save($usuario)){$this->Flash->success(__('The usuario has been saved.'));return$this->redirect(['action'=>'index']);}else{$this->Flash->error(__('The usuario could not be saved. Please, try again.'));}}$perfiles=$this->Usuarios->Perfiles->find('list',['limit'=>200]);$this->set(compact('usuario','perfiles'));$this->set('_serialize',['usuario']);}/** * Edit method * * @param string|null $id Usuario id. * @return void Redirects on successful edit, renders view otherwise. * @throws \Cake\Network\Exception\NotFoundException When record not found. */publicfunctionedit($id=null){$usuario=$this->Usuarios->get($id,['contain'=>[]]);if($this->request->is(['patch','post','put'])){$usuario=$this->Usuarios->patchEntity($usuario,$this->request->data);if($this->Usuarios->save($usuario)){$this->Flash->success(__('The usuario has been saved.'));return$this->redirect(['action'=>'index']);}else{$this->Flash->error(__('The usuario could not be saved. Please, try again.'));}}$perfiles=$this->Usuarios->Perfiles->find('list',['limit'=>200]);$this->set(compact('usuario','perfiles'));$this->set('_serialize',['usuario']);}/** * Delete method * * @param string|null $id Usuario id. * @return void Redirects to index. * @throws \Cake\Network\Exception\NotFoundException When record not found. */publicfunctiondelete($id=null){$this->request->allowMethod(['post','delete']);$usuario=$this->Usuarios->get($id);if($this->Usuarios->delete($usuario)){$this->Flash->success(__('The usuario has been deleted.'));}else{$this->Flash->error(__('The usuario could not be deleted. Please, try again.'));}return$this->redirect(['action'=>'index']);}}
<?php// Path File: \App\config\bootstrap.php/** * Bootstrap custom for Spanish in Inflector::rules(*******) * Create all tables in DB for plural. *//** * Configure paths required to find CakePHP + general filepath * constants */require__DIR__.'/paths.php';// Use composer to load the autoloader.requireROOT.DS.'vendor'.DS.'autoload.php';/** * Bootstrap CakePHP. * * Does the various bits of setup that CakePHP needs to do. * This includes: * * - Registering the CakePHP autoloader. * - Setting the default application paths. */requireCORE_PATH.'config'.DS.'bootstrap.php';// You can remove this if you are confident you have intl installed.if(!extension_loaded('intl')){trigger_error('You must enable the intl extension to use CakePHP.',E_USER_ERROR);}useCake\Cache\Cache;useCake\Console\ConsoleErrorHandler;useCake\Core\App;useCake\Core\Configure;useCake\Core\Configure\Engine\PhpConfig;useCake\Core\Plugin;useCake\Database\Type;useCake\Datasource\ConnectionManager;useCake\Error\ErrorHandler;useCake\Log\Log;useCake\Mailer\Email;useCake\Network\Request;useCake\Routing\DispatcherFactory;useCake\Utility\Inflector;useCake\Utility\Security;/** * Read configuration file and inject configuration into various * CakePHP classes. * * By default there is only one configuration file. It is often a good * idea to create multiple configuration files, and separate the configuration * that changes from configuration that does not. This makes deployment simpler. */try{Configure::config('default',newPhpConfig());Configure::load('app','default',false);}catch(\Exception$e){die($e->getMessage()."\n");}// Load an environment local configuration file.// You can use a file like app_local.php to provide local overrides to your// shared configuration.//Configure::load('app_local', 'default');// When debug = false the metadata cache should last// for a very very long time, as we don't want// to refresh the cache while users are doing requests.if(!Configure::read('debug')){Configure::write('Cache._cake_model_.duration','+1 years');Configure::write('Cache._cake_core_.duration','+1 years');}/** * Set server timezone to UTC. You can change it to another timezone of your * choice but using UTC makes time calculations / conversions easier. */date_default_timezone_set('UTC');//date_default_timezone_set('America/Buenos_Aires');/** * Configure the mbstring extension to use the correct encoding. */mb_internal_encoding(Configure::read('App.encoding'));/** * Set the default locale. This controls how dates, number and currency is * formatted and sets the default language to use for translations. */ini_set('intl.default_locale','es_AR');/** * Register application error and exception handlers. */$isCli=php_sapi_name()==='cli';if($isCli){(newConsoleErrorHandler(Configure::read('Error')))->register();}else{(newErrorHandler(Configure::read('Error')))->register();}// Include the CLI bootstrap overrides.if($isCli){require__DIR__.'/bootstrap_cli.php';}/** * Set the full base URL. * This URL is used as the base of all absolute links. * * If you define fullBaseUrl in your config file you can remove this. */if(!Configure::read('App.fullBaseUrl')){$s=null;if(env('HTTPS')){$s='s';}$httpHost=env('HTTP_HOST');if(isset($httpHost)){Configure::write('App.fullBaseUrl','http'.$s.'://'.$httpHost);}unset($httpHost,$s);}Cache::config(Configure::consume('Cache'));ConnectionManager::config(Configure::consume('Datasources'));Email::configTransport(Configure::consume('EmailTransport'));Email::config(Configure::consume('Email'));Log::config(Configure::consume('Log'));Security::salt(Configure::consume('Security.salt'));/** * The default crypto extension in 3.0 is OpenSSL. * If you are migrating from 2.x uncomment this code to * use a more compatible Mcrypt based implementation */// Security::engine(new \Cake\Utility\Crypto\Mcrypt());/** * Setup detectors for mobile and tablet. */Request::addDetector('mobile',function($request){$detector=new\Detection\MobileDetect();return$detector->isMobile();});Request::addDetector('tablet',function($request){$detector=new\Detection\MobileDetect();return$detector->isTablet();});/** * Custom Inflector rules, can be set to correctly pluralize or singularize * table, model, controller names or whatever other string is passed to the * inflection functions. * * Inflector::rules('plural', ['/^(inflect)or$/i' => '\1ables']); * Inflector::rules('irregular', ['red' => 'redlings']); * Inflector::rules('uninflected', ['dontinflectme']); * Inflector::rules('transliteration', ['/å/' => 'aa']); */Inflector::rules('plural',['/^(.*)$/i'=>'\1']);//Inflector::rules('singular', ['/^(.*)$/i' => '\1']);Inflector::rules('uninflected',[]);Inflector::rules('irregular',[]);/** * Plugins need to be loaded manually, you can either load them one by one or all of them in a single call * Uncomment one of the lines below, as you need. make sure you read the documentation on Plugin to use more * advanced ways of loading plugins * * Plugin::loadAll(); // Loads all plugins at once * Plugin::load('Migrations'); //Loads a single plugin named Migrations * */Plugin::load('Migrations');// Only try to load DebugKit in development mode// Debug Kit should not be installed on a production systemif(Configure::read('debug')){Plugin::load('DebugKit',['bootstrap'=>true]);}/** * Connect middleware/dispatcher filters. */DispatcherFactory::add('Asset');DispatcherFactory::add('Routing');DispatcherFactory::add('ControllerFactory');/** * Enable default locale format parsing. * This is needed for matching the auto-localized string output of Time() class when parsing dates. */Type::build('date')->useLocaleParser();Type::build('datetime')->useLocaleParser();
Hola Gente acá comparto un simple código, donde se muestra lo que hay que modificar para poder tener a CakePHP 3.1 funcionando con un sistema de login con Auth, con un modelos personalisado sin utilizar la tabla Users y ajustando el Bootstrap.php de CakePHP para que puedas tener todas las tablas con nombre en castellano. Como buena práctica te recomiendo que siempre las tablas las escribas en plural ejemplo Clientes, Usuarios, Pagos, etc.. También el Login esta creado con BootStrap 3.x y la estructura de la Tabla MySQL, que es importante tener en cuenta que siempre el campos password o donde se va a guarda el Hash de la clave tiene que ser un varchar de 255, porque el Hash es muy largo y se podria corta al guardarlo y nunca podríamos entrar al sistema.
Hola Gente acá comparto un simple código, donde se muestra lo que hay que modificar para poder tener a CakePHP 3.1 funcionando con un sistema de login con Auth, con un modelos personalisado sin utilizar la tabla Users y ajustando el Bootstrap.php de CakePHP para que puedas tener todas las tablas con nombre en castellano. Como buena práctica te recomiendo que siempre las tablas las escribas en plural ejemplo Clientes, Usuarios, Pagos, etc.. También el Login esta creado con BootStrap 3.x y la estructura de la Tabla MySQL, que es importante tener en cuenta que siempre el campos password o donde se va a guarda el Hash de la clave tiene que ser un varchar de 255, porque el Hash es muy largo y se podria corta al guardarlo y nunca podríamos entrar al sistema.
Saludos EOM Design Group | www.e-om.com.ar
PD: Compartilo o comentas si lo ves útil.
Thanks bro!
De nada Saludos @eomwebmaster
Excelente!!!! Se te agradece un vergo
De nada, no me quedo claro lo de 'vergo'
Saludos @eomwebmaster