• DE
  • ES
  • EN
  • NL
Google+twitterfacebook

Blog

Hoe klant-authenticatie toe te voegen aan de Magento API


This article originally appeared on the Magentron Blog as 'How to add customer authentication to your Magento API'.

Published on Tuesday May 22, 2012 by Jeroen Derks.

In dit artikel zal ik een eenvoudige oplossing beschrijven voor het toevoegen van klant-authenticatie aan de Magento API. Hoe functionaliteit toe te voegen aan de Magento API is al voldoende gedocumenteerd in de Magento wiki-pagina Creating a custom API or extending the Core API, zodat we hier niet verder op ingaan.

Het idee is om eenvoudig dezelfde functie voor de login() aan te roepen die gebruikt wordt in de frontend en dan controleren of er authenticatie van klanten in alle API-oproep die klant verificatie vereist.

NB: Houd er rekening mee dat dit artikel een werk-in-progress is, de toepasbaarheid en het resultaat kunnen variëren, dus goed testen voordat je deze oplossing in een productieomgeving plaatst.

Update: aangepast om de klant sessie te gebruiken voor het opslaan van de huidige website en winkel.

Laat het weten als je problemen ondervindt met deze oplossing. Bedankt!

<?php
/**
 * Maatwerk API model
 */
class MyCompany_MyModule_Model_Api extends Mage_Api_Model_Resource_Abstract
{
    /** @var Mage_Customer_Model_Session */
    protected $_customerSession = null;

    /**
     * Klant authenticatie.
     *
     * @param   string  $website Website code of website to authenticate customer against
     * @param   string  $username Username of customer to authenticate
     * @param   string  $password Password of customer to authenticate
     * @return  boolean True, if successfully authenticated customer for supplied website; false, otherwise.
     */
    public function login( $website, $email, $password )
    {
        // bepaal winkel waarop ingelogd dient te worden 
        $store = $this->_getStore($website);

        // haal klant sessie object op
        $session = $this->_getCustomerSession();

        // authentiseer klant
        $authenticated = $session->login($email, $password);

        // retourneer resultaat van authenticatie
        return $authenticated;
    }

    /**
     * Log geauthentiseerde klant uit, indien aanwezig.
     * @return boolean True.
     */
    public function logout()
    {
        // haal klant sessie object op
        $session = $this->_getCustomerSession();
        
        // log klant uit
        $session->logout();

        return true;
    }

Daarna moet er gecontroleerd worden dat de gebruiker authentiseerd is in API functies die dit vereisen:

    /**
     * Do something for an authenticated customer.
     */
    public function doSomethingThatRequiresCustomerAuthentication()
    {
        // check whether customer is actually authenticated
        $this->_checkCustomerAuthentication();

        // retrieve customer object
        $customer = $this->_getAuthenticatedCustomer()

        // do something for authenticated customer
        ...
    }

Uiteindelijk moeten de hulp functies die we gebruikt hebben, gedefinieerd worden:

    /**
     * Check whether a customer has been authenticated in this session.
     * 
     * @return void
     * @throws Mage_Core_Exception If customer is not authenticated.
     */
    protected function _checkCustomerAuthentication()
    {
        // get customer session object
        $session = $this->_getCustomerSession();
        
        // check whether customer is logged in
        if ( !$session->isLoggedIn() ) {
            // if customer is not logged in throw an exception
            Mage::throwException(Mage::helper('mymodule')->__('Not logged in'));
        }
    }

    /**
     * Get authenticated customer object.
     * 
     * @return Mage_Customer_Model_Customer Authenticated customer object.
     * @throws Mage_Core_Exception If customer is not authenticated or does not exist.
     */
    protected function _getAuthenticatedCustomer()
    {
        // retrieve authenticated customer ID
        $customerId = $this->_getAuthenticatedCustomerId();
        if ( $customerId )
        {
            // load customer
            /** @var Mage_Customer_Model_Customer $customer */
            $customer = Mage::getModel('customer/customer')
                            ->load($customerId);
            if ( $customer->getId() ) {
                // if customer exists, return customer object
                return $customer;
            }
        }
        
        // customer not authenticated or does not exist, so throw exception
        Mage::throwException(Mage::helper('mymodule')->__('Unknown Customer'));
    }

    /**
     * Get authenticated customer ID.
     * 
     * @return integer Authenticated customer ID, if any; null, otherwise.
     */
    protected function _getAuthenticatedCustomerId()
    {
        // get customer session object
        $session = $this->_getCustomerSession();
        
        // return authenticated customer ID, if any
        return $session->getCustomerId();
    }

    /**
     * Get store object from supplied website code or from register or session.
     * 
     * @param string $code Code
     */
    protected function _getStore( $code = null )
    {
        // get customer session
        $session = $this->_getCustomerSession();

        // if website code not supplied, check for selected store in register or selected website in session
        if ( null === $code ) {
            // try to get selected store from register
            $store = Mage::registry('current_store');
            if ( $store ) {
                return $store;
            }
                
            // try to get selected website code from session
            $code = $session->getCurrentWebsiteCode();
            if ( !$code ) {
                // if no store in register or website code in session, throw an exception
                Mage::throwException(Mage::helper('mymodule')->__('No Store set'));
            }
        }

        // load website from code
        /** @var Mage_Core_Model_Website $website */
        $website = Mage::getModel('core/website')
                        ->load($code, 'code');
        if ( !$website->getId() ) {
            // if unknown website, throw an exception
            Mage::throwException(Mage::helper('mymodule')->__('Invalid Store') . $code);
        }
        
        // get the default store of the website
        $store = $website->getDefaultStore();
        
        // register the current store
        Mage::app()->setCurrentStore($store);
        Mage::register('current_store', $store, true);
        
        // set the current website code in the session
        $session->setCurrentWebsiteCode($website->getCode());
        
        // return store object
        return $store;
    }

    /**
     * @return Mage_Customer_Model_Session
     */
    protected function _getCustomerSession()
    {
        if ( !$this->_customerSession ) {
            $this->_customerSession = Mage::getSingleton('customer/session');
        }
        return $this->_customerSession;
    }

    ...
}

Please let me know if this article has been useful to you! (or not)