PHP code example of admad / cakephp-social-auth

1. Go to this page and download the library: Download admad/cakephp-social-auth library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

admad / cakephp-social-auth example snippets


// src/Application.php

// Be sure to add SocialAuthMiddleware after RoutingMiddleware
$middlewareQueue->add(new \ADmad\SocialAuth\Middleware\SocialAuthMiddleware([
    // Request method type use to initiate authentication.
    'requestMethod' => 'POST',
    // Login page URL. In case of auth failure user is redirected to login
    // page with "error" query string var.
    'loginUrl' => '/users/login',
    // URL to redirect to after authentication (string or array).
    'loginRedirect' => '/',
    // Boolean indicating whether user identity should be returned as entity.
    'userEntity' => false,
    // User model.
    'userModel' => 'Users',
    // Social profile model.
    'socialProfileModel' => 'ADmad/SocialAuth.SocialProfiles',
    // Finder type.
    'finder' => 'all',
    // Fields.
    'fields' => [
        'password' => 'password',
    ],
    // Session key to which to write identity record to.
    'sessionKey' => 'Auth',
    // The method in user model which should be called in case of new user.
    // It should return a User entity.
    'getUserCallback' => 'getUser',
    // SocialConnect Auth service's providers config. https://github.com/SocialConnect/auth/blob/master/README.md
    'serviceConfig' => [
        'provider' => [
            'facebook' => [
                'applicationId' => '<application id>',
                'applicationSecret' => '<application secret>',
                'scope' => [
                    'email',
                ],
                'options' => [
                    'identity.fields' => [
                        'email',
                        // To get a full list of all possible values, refer to
                        // https://developers.facebook.com/docs/graph-api/reference/user
                    ],
                ],
            ],
            'google' => [
                'applicationId' => '<application id>',
                'applicationSecret' => '<application secret>',
                'scope' => [
                    'https://www.googleapis.com/auth/userinfo.email',
                    'https://www.googleapis.com/auth/userinfo.profile',
                ],
            ],
        ],
    ],
    // Instance of `\SocialConnect\Auth\CollectionFactory`. If none provided one will be auto created. Default `null`.
    'collectionFactory' => null,
    // Whether social connect errors should be logged. Default `true`.
    'logErrors' => true,
]));

echo $this->Form->postLink(
    'Login with Facebook',
    [
        'prefix' => false,
        'plugin' => 'ADmad/SocialAuth',
        'controller' => 'Auth',
        'action' => 'login',
        'provider' => 'facebook',
        '?' => ['redirect' => $this->request->getQuery('redirect')]
    ]
);

// src/Model/Table/UsersTable.php
use \Cake\Datasource\EntityInterface;
use \Cake\Http\Session;

public function getUser(EntityInterface $profile, Session $session)
{
    // Make sure here that all the     // use the $session argument to get user id and find matching user entity.
    $userId = $session->read('Auth.id');
    if ($userId) {
        return $this->get($userId);
    }

    // Check if user with same email exists. This avoids creating multiple
    // user accounts for different social identities of same user. You should
    // probably skip this check if your system doesn't enforce unique email
    // per user.
    $user = $this->find()
        ->where(['email' => $profile->email])
        ->first();

    if ($user) {
        return $user;
    }

    // Create new user account
    $user = $this->newEntity(['email' => $profile->email]);
    $user = $this->save($user);

    if (!$user) {
        throw new \RuntimeException('Unable to save new user');
    }

    return $user;
}

// src/Event/SocialAuthListener.php

namespace App\Event;

use ADmad\SocialAuth\Middleware\SocialAuthMiddleware;
use Cake\Datasource\EntityInterface;
use Cake\Event\EventInterface;
use Cake\Event\EventListenerInterface;
use Cake\Http\ServerRequest;
use Cake\I18n\FrozenTime;
use Cake\ORM\Locator\LocatorAwareTrait;

class SocialAuthListener implements EventListenerInterface
{
    use LocatorAwareTrait;

    public function implementedEvents(): array
    {
        return [
            SocialAuthMiddleware::EVENT_AFTER_IDENTIFY => 'afterIdentify',
            SocialAuthMiddleware::EVENT_BEFORE_REDIRECT => 'beforeRedirect',
            // Uncomment below if you want to use the event listener to return
            // an entity for a new user instead of directly using `createUser()` table method.
            // SocialAuthMiddleware::EVENT_CREATE_USER => 'createUser',
        ];
    }

    public function afterIdentify(EventInterface $event, EntityInterface $user): EntityInterface
    {
        // Update last login time
        $user->set('last_login', new FrozenTime());

        // You can access the profile using $user->social_profile

        $this->getTableLocator()->get('Users')->saveOrFail($user);

        return $user;
    }

    /**
     * @param \Cake\Event\EventInterface $event
     * @param string|array $url
     * @param string $status
     * @param \Cake\Http\ServerRequest $request
     * @return void
     */
    public function beforeRedirect(EventInterface $event, $url, string $status, ServerRequest $request): void
    {
        // Set flash message
        switch ($status) {
            case SocialAuthMiddleware::AUTH_STATUS_SUCCESS:
                $request->getFlash()->error('You are now logged in.');
                break;

            // Auth through provider failed. Details will be logged in
            // `error.log` if `logErrors` option is set to `true`.
            case SocialAuthMiddleware::AUTH_STATUS_PROVIDER_FAILURE:

            // Table finder failed to return user record. An e.g. of this is a
            // user has been authenticated through provider but your finder has
            // a condition to not return an inactivated user.
            case SocialAuthMiddleware::AUTH_STATUS_FINDER_FAILURE:
                $request->getFlash()->error('Authentication failed.');
                break;

            case SocialAuthMiddleware::AUTH_STATUS_IDENTITY_MISMATCH:
                $request->getFlash()->error('The social profile is already linked to another user.');
                break;
        }

        // You can return a modified redirect URL if needed.
    }

    public function createUser(EventInterface $event, EntityInterface $profile, Session $session): EntityInterface
    {
        // Create and save entity for new user as shown in "createUser()" method above

        return $user;
    }
}

// src/Application.php
use App\Event\SocialAuthListener;
use Cake\Event\EventManager;

// In Application::bootstrap() or Application::middleware()
EventManager::instance()->on(new SocialAuthListener());

$collectionFactory = new \SocialConnect\Auth\CollectionFactory();
$collectionFactory->register(\App\Authenticator\MyProvider::NAME, \App\Authenticator\MyProvider::class);