Coder Social home page Coder Social logo

marcosrioj / lfjopauth Goto Github PK

View Code? Open in Web Editor NEW

This project forked from lorenzoferrarajr/lfjopauth

0.0 1.0 0.0 179 KB

LfjOpauth is a Zend Framework 2 module that enables support for many authentication providers through the Opauth framework

License: MIT License

lfjopauth's Introduction

LfjOpauth

Created By Lorenzo Ferrara Junior

Introduction

LfjOpauth is a Zend Framework 2 module that enables support for many authentication providers through the Opauth framework.

Installation

To use the module you need to:

  • Install the LfjOpauth module using using composer
  • Install at least one of the Opauth strategies
  • Enable the LfjOpauth module

To install the LfjOpauth module, you need to add "lorenzoferrarajr/lfj-opauth": "dev-master" to the require list of your project's composer.json file.

To install the Opauth strategy, you need find the required package on Packagist or on GitHub and add it to the require list of your project's composer.json file.

This is an example of a modified composer.json which includes the LfjOpauth module and the Facebook strategy:

{
    "name": "zendframework/skeleton-application",
    "description": "Skeleton Application for ZF2",
    "require": {
        "php": ">=5.3.3",
        "zendframework/zendframework": ">2.2.0rc1",
        "lorenzoferrarajr/lfj-opauth": "dev-master",
        "opauth/facebook": "0.2.1"
   }
}

The example includes the installation of the Facebook Opauth strategy. More info on Opauth strategies can be found on GitHub:

Installing LfjOpauth using composer, the Opauth dependecy is automatically resolved, but you still must provide at least one strategy.

Next, you need to add LfjOpauth to the modules list in the config/application.config.php file of your Zend Framework 2 project.

This is an example:

<?php
return array(
    'modules' => array(
        'LfjOpauth',
        'Application',
    ),
    // more code
);

Configuration

Once LfjOpauth is installed you must create a file named lfjopauth.global.php in your config/autoload directory. This is the configuration file where you specify the LfjOpauth options.

An example of the lfjopauth.global.php file:

$settings = array(
    'security_salt' => 'Some random text',
    'Strategy' => array(
        'Facebook' => array(
            'app_id' => 'facebook application id',
            'app_secret' => 'facebook application secret',
            'scope' => 'email,user_relationships',
        ),
        'second_facebook_app' => array(
            'app_id' => 'another facebook application id',
            'app_secret' => 'another facebook application secret',
            'scope' => 'email,user_relationships',
            'strategy_class' => 'Facebook',
            'strategy_url_name' => 'second_facebook_app'
        )
    ),
    'check_controller_enabled' => false
);

return array('lfjopauth' => $settings);

The configuration is pretty much the same as the Opauth configuration, without the path and callback_url options, which are handled by the module.

The check_controller_enabled flag enables or disables access to CheckController.

Login and callback urls

Given the above configuration (and the corresponding Facebook applications), you will be able to login using:

and to logout using:

For the two demo Facebook application described in the example configuration, you should use

as value of the Website with Facebook Login, Site URL option.

Events

The LfjOpauth\Service\OpauthService triggers the LfjOpauth\LfjOpauthEvent::EVENT_LOGIN_CALLBACK event after the callback is processed. Be aware that the LfjOpauth\LfjOpauthEvent::EVENT_LOGIN_CALLBACK event is alwais triggered, even when the login process fails. Use the available event parameters to implement result checking.

The event contains three parameters:

  • authenticationService: a Zend\Authentication\Result instance
  • authenticationResult: a Zend\Authentication\AuthenticationService instance
  • provider: is the provider used to try the login (example: facebook, google)

and its target is an instance of LfjOpauth\Service\OpauthService.

As en example on how to attach to the event, please refer to the following code.

namespace Application;

use Zend\EventManager\EventInterface;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;

class Module
{
    public function onBootstrap(MvcEvent $e)
    {
        $eventManager        = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);

        $sharedEventManager = $eventManager->getSharedManager();

        $sharedEventManager->attach('LfjOpauth\Service\OpauthService', \LfjOpauth\LfjOpauthEvent::EVENT_LOGIN_CALLBACK, function(EventInterface $e) {

            /** @var \Zend\Authentication\Result $result */
            $authenticationResult = $e->getParam('authenticationResult');

            /** @var \Zend\Authentication\AuthenticationService $authenticationService */
            $authenticationService = $e->getParam('authenticationService');

            /** @var \LfjOpauth\Service\OpauthService $target */
            $target = $e->getTarget();

            $provider = $e->getParam('provider');

            /*
            var_dump(get_class($e->getTarget()));
            var_dump($e->getParam('provider'));
            var_dump('$authenticationResult->isValid()', $authenticationResult->isValid());
            var_dump('$authenticationService->hasIdentity()', $authenticationService->hasIdentity());
            var_dump('$authenticationService->getIdentity()', $authenticationService->getIdentity());
            var_dump('$authenticationResult->getCode()', $authenticationResult->getCode());
            var_dump('$authenticationResult->getIdentity()', $authenticationResult->getIdentity());
            var_dump('$authenticationResult->getMessages()', $authenticationResult->getMessages());
            */

        }, 100);
    }

Custom callback urls

If you need custom login and/or callback urls (for example containing more parameters), you can code custom routes and controller.

This is the code that defines the custom_lfjopauth_login and custom_lfjopauth_callback routes (custom-auth is the controller alias):

return array(
    'router' => array(
        'routes' => array(
            'custom_lfjopauth_login' => array(
                'type'    => 'Segment',
                'options' => array(
                    'route'    => '/custom/login/[:provider[/:oauth_callback]]',
                    'constraints' => array(
                        'provider'       => '[a-zA-Z][a-zA-Z0-9_-]*',
                        'oauth_callback' => '[a-zA-Z][a-zA-Z0-9_-]*'
                    ),
                    'defaults' => array(
                        'controller'    => 'custom-auth',
                        'action'        => 'redirectAndReturn'
                    )
                )
            ),
            'custom_lfjopauth_callback' => array(
                'type'    => 'Segment',
                'options' => array(
                    'route'    => '/custom/callback/[:provider]',
                    'constraints' => array(
                        'provider'  => '[a-zA-Z][a-zA-Z0-9_-]*'
                    ),
                    'defaults' => array(
                        'controller'    => 'custom-auth',
                        'action'        => 'callback'
                    )
                )
            ),
            // more code
        )
    )
);

This is the code of the hypothetical controller that manages login and callback actions:

// [...]
class AuthController extends AbstractActionController
{
    public function redirectAndReturnAction()
    {
        // if user is not logged in
        if (!$this->auth()->hasIdentity())
        {
       	    $provider = $this->params()->fromRoute('provider');
       	    $oauth_callback = $this->params()->fromRoute('oauth_callback');
            $opauth_service = $this->getServiceLocator()->get('opauth_service');

            // set custom login and callback routes
            $opauth_service->setLoginUrlName('custom_lfjopauth_login');
            $opauth_service->setCallbackUrlName('custom_lfjopauth_callback');

            return $opauth_service->redirect($provider, $oauth_callback);
        }

        return $this->redirect()->toRoute('somewhere_over_the_rainbow');
    }

    public function callbackAction()
    {
        // if user is not logged in
        if (!$this->auth()->hasIdentity())
        {
       	    $provider = $this->params()->fromRoute('provider');
       	    $opauth_service = $this->getServiceLocator()->get('opauth_service');

            // set custom login and callback routes
            $opauth_service->setLoginUrlName('custom_lfjopauth_login');
            $opauth_service->setCallbackUrlName('custom_lfjopauth_callback');

            $opauth_service->callback($provider);
        }
	
        return $this->redirect()->toRoute('somewhere_else_over_the_rainbow');
    }
}

Checking login status

If the check_controller_enabled flag is enabled, you will be able to print current session info at this url:

The default value of check_controller_enabled is false.

Other info

LfjOpauth uses Zend\Authentication\AuthenticationService (alias lfjopauth_auth_service) to manage authentication.

The LfjOpauth\Service\OpauthService (alias: opauth_service) class exposes the redirect and callback methods which can be used in any controller. An example can be found in the LfjOpauth\Controller\LoginController class.

LICENSE

The files in this archive are released under the MIT license. You can find a copy of this license in LICENSE.txt.

lfjopauth's People

Contributors

lorenzoferrarajr 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.