CakeDC / users

Users Plugin for CakePHP
https://www.cakedc.com
Other
522 stars 296 forks source link

Facebook Login don't working. Show Message "You are not authorized to access that location." #504

Closed Marcosul closed 7 years ago

Marcosul commented 7 years ago

Hello,

I installed the CakeDC Users Plugin and it works fine except for the Facebook login. Clicking the login button returns a non-permission message. "You are not authorized to access that location."

I've done a lot of tests, without success. I noticed that by clicking on the Facebook login button, the action does not go through config/pemissions.php.

I need some help, please.

Below, my configuration files and print the screens.

Thank you so much. Marco

========================

::::: Config/bootstrap.php

<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @since         0.10.8
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * Configure paths required to find CakePHP + general filepath
 * constants
 */
require __DIR__ . '/paths.php';

// Use composer to load the autoloader.
require ROOT . 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.
 */
require CORE_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);
}

use Cake\Cache\Cache;
use Cake\Console\ConsoleErrorHandler;
use Cake\Core\App;
use Cake\Core\Configure;
use Cake\Core\Configure\Engine\PhpConfig;
use Cake\Core\Plugin;
use Cake\Database\Type;
use Cake\Datasource\ConnectionManager;
use Cake\Error\ErrorHandler;
use Cake\Log\Log;
use Cake\Mailer\Email;
use Cake\Network\Request;
use Cake\Routing\DispatcherFactory;
use Cake\Utility\Inflector;
use Cake\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', new PhpConfig());
    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');

/**
 * 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', 'pt_BR');

/**
 * Register application error and exception handlers.
 */
$isCli = PHP_SAPI === 'cli';
if ($isCli) {
    (new ConsoleErrorHandler(Configure::read('Error')))->register();
} else {
    (new ErrorHandler(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']);
 */

/**
 * 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
 *
 */

// Only try to load DebugKit in development mode
// Debug Kit should not be installed on a production system
if (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();

Plugin::load('Bootstrap') ; // instead of Plugin::load('Bootstrap3') ;

Plugin::load('Migrations');

Plugin::load('Cake/Localized');

Configure::write('Users.config', ['users']);
Plugin::load('CakeDC/Users', ['routes' => true, 'bootstrap' => true]);
Configure::write('Users.Social.login', true); //to enable social login
Configure::write('Auth.authenticate.Form.fields.username', 'email');

Configure::write('OAuth.providers.facebook.options.clientId', '251460195277031');
Configure::write('OAuth.providers.facebook.options.clientSecret', 'secret');

=========== ::::: config/users.php

<?php

/**
 * Copyright 2010 - 2015, Cake Development Corporation (http://cakedc.com)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright Copyright 2010 - 2015, Cake Development Corporation (http://cakedc.com)
 * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
use Cake\Core\Configure;
use Cake\Routing\Router;

$config = [
    'Users' => [
        //Table used to manage users
        'table' => 'CakeDC/Users.Users',
        //configure Auth component
        'auth' => true,
        //Password Hasher
        'passwordHasher' => '\Cake\Auth\DefaultPasswordHasher',
        //token expiration, 1 hour
        'Token' => ['expiration' => 3600],
        'Email' => [
            //determines if the user should include email
            'required' => true,
            //determines if registration workflow includes email validation
            'validate' => true,
        ],
        'Registration' => [
            //determines if the register is enabled
            'active' => true,
            //determines if the reCaptcha is enabled for registration
            'reCaptcha' => false,
        ],
        'Tos' => [
            //determines if the user should include tos accepted
            'required' => true,
        ],
        'Social' => [
            //enable social login
            'login' => true,
        ],
        'Profile' => [
            //Allow view other users profiles
            'viewOthers' => true,
            'route' => ['plugin' => 'CakeDC/Users', 'controller' => 'Users', 'action' => 'profile'],
        ],
        'Key' => [
            'Session' => [
                //session key to store the social auth data
                'social' => 'Users.social',
                //userId key used in reset password workflow
                'resetPasswordUserId' => 'Users.resetPasswordUserId',
            ],
            //form key to store the social auth data
            'Form' => [
                'social' => 'social'
            ],
            'Data' => [
                //data key to store the users email
                'email' => 'email',
                //data key to store email coming from social networks
                'socialEmail' => 'info.email',
                //data key to check if the remember me option is enabled
                'rememberMe' => 'remember_me',
            ],
        ],
        //Avatar placeholder
        'Avatar' => ['placeholder' => 'CakeDC/Users.avatar_placeholder.png'],
        'RememberMe' => [
            //configure Remember Me component
            'active' => true,
            'Cookie' => [
                'name' => 'remember_me',
                'Config' => [
                    'expires' => '1 month',
                    'httpOnly' => true,
                ]
            ]
        ],
    ],
//default configuration used to auto-load the Auth Component, override to change the way Auth works
    'Auth' => [
        'loginAction' => [
            'plugin' => 'CakeDC/Users',
            'controller' => 'Users',
            'action' => 'login',
            'prefix' => false
        ],
        'authenticate' => [
            'all' => [
                'scope' => ['active' => 1]
            ],
            'CakeDC/Users.ApiKey',
            'CakeDC/Users.RememberMe',
            'Form',
        ],
        'authorize' => [
            'CakeDC/Users.Superuser',
            'CakeDC/Users.SimpleRbac',
        ],
    ],
    'OAuth' => [
        'path' => ['plugin' => 'CakeDC/Users', 'controller' => 'Users', 'action' => 'socialLogin', 'prefix' => false],
        'providers' => [
            'facebook' => [
                'className' => 'League\OAuth2\Client\Provider\Facebook',
                'options' => [
                    'graphApiVersion' => 'v2.5',
                    'redirectUri' => Router::url('/auth/facebook', true)
                ]
            ],
            'twitter' => [
                'options' => [
                    'redirectUri' => Router::url('/auth/twitter', true)
                ]
            ],
            'linkedIn' => [
                'className' => 'League\OAuth2\Client\Provider\LinkedIn',
                'options' => [
                    'redirectUri' => Router::url('/auth/linkedIn', true)
                ]
            ],
            'instagram' => [
                'className' => 'League\OAuth2\Client\Provider\Instagram',
                'options' => [
                    'redirectUri' => Router::url('/auth/instagram', true)
                ]
            ],
            'google' => [
                'className' => 'League\OAuth2\Client\Provider\Google',
                'options' => [
                    'userFields' => ['url', 'aboutMe'],
                    'redirectUri' => Router::url('/auth/google', true)
                ]
            ],
        ],
    ]
];

return $config;

======= :::: src/Controller/AppController.php

<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link      http://cakephp.org CakePHP(tm) Project
 * @since     0.2.9
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace App\Controller;

use Cake\Controller\Controller;
use Cake\Event\Event;
use Cake\Database\Type;
// Habilita o parseamento de datas localizadas
Type::build('date')
 ->useLocaleParser()
 ->setLocaleFormat('dd/MM/yyyy');
Type::build('datetime')
 ->useLocaleParser()
 ->setLocaleFormat('dd/MM/yyyy HH:mm:ss');
Type::build('timestamp')
 ->useLocaleParser()
 ->setLocaleFormat('dd/MM/yyyy HH:mm:ss');

// Habilita o parseamento de decimal localizaddos
Type::build('decimal')
 ->useLocaleParser();
Type::build('float')
 ->useLocaleParser();

/**
 * 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
 */
class AppController extends Controller
{

    /**
     * Initialization hook method.
     *
     * Use this method to add common initialization code like loading components.
     *
     * e.g. `$this->loadComponent('Security');`
     *
     * @return void
     */

    public function initialize() {
        parent::initialize();
        $this->loadComponent('Flash');
        $this->loadComponent('CakeDC/Users.UsersAuth');
        $this->loadComponent('RequestHandler');        
        $this->Auth->config('loginRedirect', 'dashboard');
        // $this->loadComponent('Auth', [
        //     'authorize' => 'Controller',
        //     'authenticate' => [
        //         'Form' => [
        //             'fields' => [
        //                 'username' => 'email',
        //                 'password' => 'password'
        //             ]
        //         ]
        //     ],
        //     'loginAction' => [
        //         'controller' => 'Users',
        //         'action' => 'login'
        //     ],
        //     'loginRedirect' => [
        //         'controller' => 'Dashboard',
        //         'action' => 'index'
        //     ],
        //     'logoutRedirect' => [
        //         'controller' => 'Pages',
        //         'action' => 'display',
        //         'home'
        //     ]
        // ]);

        // Permite a ação display, assim nosso pages controller
        // continua a funcionar.
        $this->Auth->allow(['display']);

        if (!empty($this->Auth->user())) {
            $this->viewBuilder()->layout('loggedin');
        }

        $user = $this->Auth->user();
        $this->set('user', $user);

        $config['Auth']['authorize']['Users.SimpleRbac'] = [
        //autoload permissions.php
        'autoload_config' => 'permissions',
        //role field in the Users table
        'role_field' => 'role',
        //default role, used in new users registered and also as role matcher when no role is available
        'default_role' => 'user',
        /*
         * This is a quick roles-permissions implementation
         * Rules are evaluated top-down, first matching rule will apply
         * Each line define
         *      [
         *          'role' => 'admin',
         *          'plugin', (optional, default = null)
         *          'controller',
         *          'action',
         *          'allowed' (optional, default = true)
         *      ]
         * You could use '*' to match anything
         * Suggestion: put your rules into a specific config file
         */
        'permissions' => [], // you could set an array of permissions or load them using a file 'autoload_config'
    ];

    $config['Auth']['authorize']['Users.Superuser'] = [
        //superuser field in the Users table
        'superuser_field' => 'is_superuser',
    ];

    }

    /**
     * Before render callback.
     *
     * @param \Cake\Event\Event $event The beforeRender event.
     * @return void
     */
    public function beforeRender(Event $event)
    {
        if (!array_key_exists('_serialize', $this->viewVars) &&
            in_array($this->response->type(), ['application/json', 'application/xml'])
        ) {
            $this->set('_serialize', true);
        }
    }

    public function isAuthorized($user) {
        return false;
    }

    public $helpers = [
    'Html' => [
        'className' => 'Bootstrap.BootstrapHtml'
    ],
    'Form' => [
        'className' => 'Bootstrap.BootstrapForm'
    ],
    'Paginator' => [
        'className' => 'Bootstrap.BootstrapPaginator'
    ],
    'Modal' => [
        'className' => 'Bootstrap.BootstrapModal'
    ]
];
}

========== ::: src/Template/Plugin/CakeDC/Users/Users/login.ctp

<?php
/**
* Copyright 2010 - 2015, Cake Development Corporation (http://cakedc.com)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2010 - 2015, Cake Development Corporation (http://cakedc.com)
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/

use Cake\Core\Configure;

?>

<body class="contrast-sea-blue login contrast-background">
  <div class="middle-container">
    <div class="middle-row">
      <div class="middle-wrapper">
        <div class="login-container-header">
          <div class="container">
            <div class="row">
              <div class="col-sm-12">
                <div class="text-center">
                  <img style="filter:brightness(220%);" id="logo-nav" src="/logo.png"/>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="login-container">
          <div class="container">
            <div class="row">
              <?= $this->Flash->render() ?>
              <?= $this->Form->create() ?>
              <div class="col-sm-4 col-sm-offset-3">
                <h1 class="text-center title">Acesso</h1>
                <div class="form-group">
                  <div class="controls with-icon-over-input">
                    <!-- <input type="text" name="email" value="" placeholder="E-mail" class="form-control" data-rule-required="true" aria-required="true"> -->
                    <?= $this->Form->input('email', ['required' => true,'label'=>false,'placeholder'=>__('Seu email')]) ?>
                    <i class="fa fa-user text-muted"></i>
                  </div>
                </div>
                <div class="form-group">
                  <div class="controls with-icon-over-input">
                    <?= $this->Form->input('password', ['required' => true,'label'=>false,'placeholder'=>'Senha']) ?>
                    <i class="fa fa-lock text-muted"></i>
                  </div>
                </div>
                <?php
                if (Configure::check('Users.RememberMe.active')) {
                  echo $this->Form->input(Configure::read('Users.Key.Data.rememberMe'), [
                    'type' => 'checkbox',
                    'label' => __d('Users', 'Remember me'),
                    'checked' => 'checked'
                  ]);
                }
                ?>

                <?= $this->Form->button(__d('Users', 'Login'),['class'=>'btn btn-block']); ?>
                <div class="text-center">
                  <hr class="hr-normal">
                  <?php
                  if (Configure::read('Users.Email.required')) {
                    echo $this->Html->link(__d('users', 'Esqueceu a senha?'), ['action' => 'requestResetPassword']);
                  }
                  ?>
                </div>
              </div>
              <div class="col-sm-4">
                <?= implode(' ', $this->User->socialLoginList()); ?>
              </div>
              <?= $this->Form->end() ?>
            </div>
          </div>
        </div>
        <div class="login-container-footer">
          <div class="container">
            <div class="row">
              <div class="col-sm-12">
                <div class="text-center">
                  <?php
                  $registrationActive = Configure::read('Users.Registration.active');
                  if ($registrationActive) {
                    echo $this->Html->link('<i class="fa fa-user"></i> '.__d('users', 'Você é novo por aqui?'), ['action' => 'register'],['escape'=>false]);
                  }
                  ?>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>

captura de tela de 2017-02-23 10-16-25 captura de tela de 2017-02-23 10-16-00 captura de tela de 2017-02-23 09-48-55

Marcosul commented 7 years ago

Hello,

Resolved: D You must use graphApiVersion 2.8 or higher.

I pasted the following in config / bootstrap.php

Configure :: write ('OAuth.providers.facebook.options.graphApiVersion', 'v2.8');

OBS: I recommend leaving the graphApiVersion version as default or in the Setup instructions.

In cases where the e-mail address already exists in the database, the user will receive an e-mail and will be asked to validate the social account in the application. Well, in tests I did for account creation for user with and without email in the database, and in no case was sent email. That's right?

Thanks!

ajibarra commented 7 years ago

Hi @Marcosul For Social Networks where email is already validated (like Google and FB) the plugin does not send email because it assumes if you authenticated using FB you are the actual owner of the email returned.

disu commented 5 years ago

Hello,

Resolved: D You must use graphApiVersion 2.8 or higher.

I pasted the following in config / bootstrap.php

Configure :: write ('OAuth.providers.facebook.options.graphApiVersion', 'v2.8');

OBS: I recommend leaving the graphApiVersion version as default or in the Setup instructions.

  • ONE QUESTION:

In cases where the e-mail address already exists in the database, the user will receive an e-mail and will be asked to validate the social account in the application. Well, in tests I did for account creation for user with and without email in the database, and in no case was sent email. That's right?

Thanks!

Hi, I have your error too: "You are not authorized to access that location." message when i Click to the Facebook login button. My CakeDC version have already the 2.8 graphApiVersion by default. Have you got any other suggestion to make it work?