GithubHelp home page GithubHelp logo

makkus183 / cakephp-social-auth Goto Github PK

View Code? Open in Web Editor NEW

This project forked from admad/cakephp-social-auth

0.0 1.0 0.0 31 KB

A CakePHP plugin which allows you to authenticate using social providers like Facebook/Google/Twitter.

License: MIT License

PHP 100.00%

cakephp-social-auth's Introduction

CakePHP SocialAuth Plugin

Total Downloads License

A CakePHP plugin which allows you authenticate using social providers like Facebook/Google/Twitter etc. using SocialConnect/auth social sign on library.

Requirements

  • CakePHP 3.4+.

Installation

Run:

composer require admad/cakephp-social-auth

Setup

Load the plugin by running following command in terminal:

bin/cake plugin load ADmad/SocialAuth -b -r

or by manually adding following line to your app's config/bootstrap.php:

Plugin::load('ADmad/SocialAuth', ['bootstrap' => true, 'routes' => true]);

Database

This plugin requires a migration to generate a social_profiles table, and it can be generated via the official Migrations plugin as follows:

bin/cake migrations migrate -p ADmad/SocialAuth

Usage

The plugin provides a \ADmad\SocialAuth\Middleware\SocialAuthMiddleware which handles authentication process through social providers. You can configure the middleware in your Application::middleware() method as shown:

// src/Application.php

$middleware->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 string or array to redirect to after authentication.
    'loginRedirect' => '/',
    // Boolean indicating whether user identity should be returned as entity.
    'userEntity' => false,
    // User model.
    'userModel' => 'Users',
    // Finder type.
    'finder' => 'all',
    // Fields.
    'fields' => [
        'password' => 'password'
    ],
    // Session key to which to write identity record to.
    'sessionKey' => 'Auth.User',
    // The methods 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'
                ]
            ],
        ]
    ],
]));

On your login page you can create links to initiate authentication using required providers.

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

We use a POST link here instead of a normal link to prevent search bots and other crawlers from following the link. (Adding "nofollow" attribute to link doesn't suffice as it's often ignored by bots/crawlers.) If you prefer using GET you can still do so by configuring the middleware with 'requestMethod' => 'GET'.

Once a user is authenticated through the provider the middleware gets the user profile from the identity provider and using that tries to find the corresponding user record using the user model. If no user is found it calls the getUser method of your user model. The method recieves social profile model entity as argument and return an entity for the user. E.g.

// src/Model/Table/UsersTable.php

public function getUser(\Cake\Datasource\EntityInterface $profile) {
    // Make sure here that all the required fields are actually present
    if (empty($profile->email)) {
        throw new \RuntimeException('Could not find email in social profile.');
    }

    // 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;
}

In case of authentication failure user is redirected back to login URL with error query string variable. It can have one of these values:

  • provider_failure: Auth through provider failed.
  • finder_failure: Finder failed to return user record. An e.g. of this is a user has been authenticated through provider but your finder has condition to not return inactivate user.

Copyright

Copyright 2017 ADmad

License

See LICENSE

cakephp-social-auth's People

Contributors

admad avatar josegonzalez avatar makkus183 avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.