3

How can I create a RESTful role and consumer during the installation of an extension (module) using a data-install script located at:

app/code/community/Namespace/Module/data/namespace_module_setup/data-install-1.0.0.php

  • I've achieved this (and will post answer later), but curious to see other possible methods and figure this is a good informative post as I could not find this info. anywhere. – Tim Hallman Jun 3 '15 at 15:06
  • How long do you want to wait? – Fabian Schmengler Jul 15 '15 at 20:31
4

I was spent many hours searching and finally, I got the solution from Magento core. Magento itself provide code for create rest role programmatically and assign this role to the user. we can also programmatically generate rest oAuth consumer secrete and api key. please see the following code.

try {
         // REST API ROLE CREATE

         $role = Mage::getModel('api2/acl_global_role')
            ->setRoleName("resttest")
            ->setCurrentPassword("admin123")
            ->setResources(array('all'))
            ->save();
          $rule = Mage::getModel('api2/acl_global_rule');
          $id = $role->getId();
          $rule->setRoleId($id)
                 ->setResourceId("all")
                 ->setPrivilege(null)
                 ->save();


         //create new user write you firstname,lastname

         $user = Mage::getModel('admin/user')
          ->setData(array(
           'username'  => $username,
           'firstname' => $username,
           'lastname' => $username,
           'email'     => $username.'email@gmail.com',
           'password'  => $password,
           'current_password' => $password,
           'api2_roles'=> array($role->getId()),
           'is_active' => 1
          ))->save();

          // Assign Role to user

            $uRoles = array(1);
              $user->setRoleIds(array($uRoles))
              ->setRoleUserId($user->getUserId())
              ->saveRelations();

          //oAuth consumer
                  $helper = Mage::helper('oauth');
                  $model = Mage::getModel('oauth/consumer')
                  ->setData(array(
                   'key'  => $helper->generateConsumerKey(),
                   'secret' => $helper->generateConsumerSecret(),
                   'name' => 'restuserapp',
                  'current_password' => $password
                  ));

                  $insertId = $model->save()->getId();




    } catch (Exception $e) 
    {

     echo $e->getMessage();
     exit;

    }

This code is work for me. Hope it helps someone.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.