Jump to content
  • 0

How To Integrate Blesta In My Project To Share Information About Currently Logged In User?


MartyIX

Question

Hello,

 

I'm trying to integrate Blesta to my project and I would like to know if I'm doing it correctly.

 

Setup:

 

 

Problem:

 

I need to share information about the user who is signed in so that the currently signed in user can buy something via Blesta and he can also do some actions in my project. A user should sign in only once to be signed in my project and in Blesta at the same time.

 

Difficulties:

 

 

1) First problem is that Blesta and my project both uses SESSIONs. 

 

Resolution:

  • I disabled in Blesta/Components/session/session.php (see the change below) some code that setup sessions to use database (it means that file storage is used for sessions now)
  • I set session.cookie-domain to ".example.com" so that the session cookie is shared among ALL subdomains of example.com (i.e. www.example.com and shop.example.com) and therefore I can work with the same $_SESSION array in Blesta and in my project.

 

 

2) Sign a user in Blesta and my project at the same time in MyProject/User/Login.php

 

Resolution:

  • I changed authentication in my project to use Blesta API to verify credentials (please see MyProject/User/Login.php source code below) where I set two SESSION variables:

    $_SESSION['blesta_id'] = $user->id;  and

    $_SESSION['blesta_client_id'] = $client->id;

    (Is it OK? Or should I set more variables in $_SESSION array?)
     
  • The second step (that I didn't solve yet) is to redirect to my login page (http://www.example.com/user/login) whenever a user visits https://shop.example.com/client/login/.
     

Question

 

Is this correct way how to share login information between a custom made project and Blesta?

 

 

Source codes:

 

MyProject/User/Login.php (not Blesta!)

 

<?php


public function authenticate(array $credentials)
{
        Logger::addDebug("Project\User\LoginModel::authenticate(credentials: >>>)", [$credentials]);
        $email = $credentials[self::USERNAME];
        $password = $credentials[self::PASSWORD];


        $user = $this->getContainer()->parameters['blesta']['api']['user'];
        $key = $this->getContainer()->parameters['blesta']['api']['key'];
        $url = $this->getContainer()->parameters['blesta']['api']['url'];
        $verifySSL = $this->getContainer()->parameters['blesta']['api']['verifySSL'];

        // https://github.com/phillipsdata/blesta_sdk/tree/master/api (BlestaApi class)
        $api = new \BlestaApi($url, $user, $key, $verifySSL);


        #
        #  Retrieve user
        #


        Logger::addDebug("Project\User\LoginModel::authenticate(): Issuing users::getByUsername request on Blesta");
        $response = $api->get("users", "getByUsername", array('username' => $email));

        if ($response->errors()) {
                Logger::addError("Project\User\LoginModel::authenticate(): getByUsername failed", [$response->errors()]);
                Logger::notify(10, "users::getByUsername: \$response->errors(): " . var_export($response, true));
                throw new Project\Security\AuthenticationException("Invalid server error.", self::NOT_APPROVED);
        }

        $user = $response->response();

        // $user is an array like this:
            // ["id"]=> string(1) "5"
            // ["username"]=> string(25) "some-username (e.g. somebody@example.com"
            // ["password"]=> string(60) "some-pasword"
            // ["two_factor_mode"]=> string(4) "none"
            // ["two_factor_key"]=> NULL
            // ["two_factor_pin"]=> NULL
            // ["date_added"]=> string(19) "2013-10-04 09:18:55"

        if (!$user) {
                Logger::addError("Project\User\LoginModel::authenticate(): User was not found.", [$user]);
                throw new Project\Security\AuthenticationException("The account does not exist.", self::IDENTITY_NOT_FOUND);
        }

        #
        #  Check password
        #


        Logger::addDebug("Project\User\LoginModel::authenticate(): Issuing 'users::checkPassword' request on Blesta");
        $response = $api->get("users", "checkPassword", array('password' => $password, 'stored_hash' => $user->password));

        if ($response->errors()) {
                Logger::addError("Project\User\LoginModel::authenticate(): checkPassword failed", [$response->errors()]);
                Logger::notify(10, "users::checkPassword: \$response->errors(): " . var_export($response, true));
                throw new Project\Security\AuthenticationException("Invalid server error.", self::NOT_APPROVED);
        }

        $isCorrectPassword = $response->response();
        Logger::addDebug("Project\User\LoginModel::authenticate(): Is password correct for ID #{$user->id}? ", [$isCorrectPassword]);

        if ($isCorrectPassword !== true) {
                Logger::addDebug("Project\User\LoginModel::authenticate(): Password is NOT correct!", [$isCorrectPassword]);
                throw new Project\Security\AuthenticationException("The combination of email and password is not right.", self::NOT_APPROVED);
        }

        Logger::addDebug("Project\User\LoginModel::authenticate(): Username and password are CORRECT!");

        #
        #  Retrieve client
        #

        Logger::addDebug("Project\User\LoginModel::authenticate(): Issuing 'clients::getByUserId' request on Blesta");
        $response = $api->get("clients", "getByUserId", array('user_id' => $user->id));

        if ($response->errors()) {
                Logger::addError("Project\User\LoginModel::authenticate(): clients::getByUserId failed", [$response->errors()]);
                Logger::notify(10, "clients::getByUserId: \$response->errors(): " . var_export($response, true));
                throw new Project\Security\AuthenticationException("Invalid server error.", self::NOT_APPROVED);
        }

        $client = $response->response();

        if (!$client) {
                Logger::addWarning("Project\User\LoginModel::authenticate(): No client is assignd to the account!", [$client]);
                throw new Project\Security\AuthenticationException("No client is assignd to the account.", self::NOT_APPROVED);
        }

        $_SESSION['blesta_id'] = $user->id;
        $_SESSION['blesta_client_id'] = $client->id;


        $user = (array)$user;
        Logger::addDebug("Project\User\LoginModel::authenticate(): Providing identity", [$user]);

        Logger::addDebug("Project\User\LoginModel::authenticate(-)");
        return $user;
}

 

 

 

Blesta/Components/session/session.php

 

 

 

    private function sessionSet($ttl, $tbl, $tblid, $tblexpire, $tblvalue, $session_name) {        $this->ttl = $ttl;
        $this->tbl = $tbl;
        $this->tblid = $tblid;
        $this->tblexpire = $tblexpire;
        $this->tblvalue = $tblvalue;


        if (Session::$instances == 0) {
            // session_name($session_name);
            // session_set_save_handler(
            //     array(&$this, "sessionOpen"),
            //     array(&$this, "sessionClose"),
            //     array(&$this, "sessionSelect"),
            //     array(&$this, "sessionWrite"),
            //     array(&$this, "sessionDestroy"),
            //     array(&$this, "sessionGarbageCollect")
            // );


            // // If a cookie is available, attempt to use that session and reset
            // // the ttl to use the cookie ttl, but only if we don't have a current session cookie as well
            // if (isset($_COOKIE[Configure::get("Session.cookie_name")]) && !isset($_COOKIE[session_name()])) {
            //     if ($this->setKeepAlive($_COOKIE[Configure::get("Session.cookie_name")])) {
            //         $this->setCsid($_COOKIE[Configure::get("Session.cookie_name")]);
            //         $this->ttl = Configure::get("Session.cookie_ttl");
            //     }
            // }
            // elseif (isset($_COOKIE[Configure::get("Session.cookie_name")]) && isset($_COOKIE[session_name()]) && $_COOKIE[Configure::get("Session.cookie_name")] == $_COOKIE[session_name()]) {
            //     $this->ttl = Configure::get("Session.cookie_ttl");
            // }
            


            // Start the session
            session_start();
        }
        Session::$instances++;
    }

Link to comment
Share on other sites

5 answers to this question

Recommended Posts

  • 0

You shouldn't haven't to make any code changes in Blesta. In fact, I'd strongly recommend that you don't.

 

What I would do is perform an AJAX request from the user's browser to https://shop.example.com/client/login/ using the user's credentials.  To do this, all you need to do is update /config/blesta.php and change

Configure::set("Blesta.csrf_bypass", array());

to

Configure::set("Blesta.csrf_bypass", array("client_login::index"));

If you're feeling fancy, you could create a plugin that you contact via the API that will invoke Users::login() and return the Session ID (Session::getSid()). Then from your caller, you could simply call set_cookie("blesta_sid", "the_session_id", 0, "/", "shop.example.com");

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...