We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 36467
    • 73 Posts
    I am pissed off with this problem from 2 days.
    I am using MODx Revolution 2.2.5 (traditional) and want to login to modx from external server just to fetch some user details.

    1) I know that runprocessor method works only if i am logged in to manager (unfortunately, that's the only way i know to login user in) So i tried IFRAME method to avoid (cross scripting) it worked perfectly but i am not able to read the data from IFRAME using javascript because of same issue, cross domain access policy.

    When i try to post data using some other method like CURL, Ajax using

    header("Access-Control-Allow-Origin: *");


    I am able to login (I see $response->response['success'] == 1) but cant access any data and it says

    Fatal error: Call to a member function get() on a non-object


    Below is the code i am using
    
    if(isset($_POST) && count($_POST)){
        
        require_once '\modx\config.core.php';
        require_once MODX_CORE_PATH.'model/modx/modx.class.php';
        $modx = new modX();
        $modx->initialize('web');
        $modx->getService('error','error.modError', '', '');
    
        $username = $_POST['username'];	
        $password = $_POST['password'];	
    
        $info = array(
            'username' => $username,
            'password' => $password
        );
        $response = $modx->runProcessor('security/login',$info);
        if($response->response['success'] == 1){
            $user['id'] = $modx->user->get('id');
            
            $profile = $modx->user->getOne('Profile');
            $user['fullname'] = $profile->get('fullname');
            $user['email'] = $profile->get('email');
    
            echo json_encode($user);
        }else{
            echo json_encode($response->response); 
        }
    }


    2) I can use login snippet but it doesnt return output what i expect. We have ready site and we are already using login plugin so i cant even modify login plugin to respond with expected data

    How can i login to modx using api or any other method ??

    This question has been answered by frogabog. See the first response.

    [ed. note: amitpatil last edited this post 13 years, 9 months ago.]
      • 28042 ☆ A M B ☆
      • 24,524 Posts
      Do you really need to log in to the remote installation? Can't you just access the remote installation's database and get the date for the user, if you know the username? Or is this an attempt at a single-sign-on?
        Studying MODX in the desert - http://sottwell.com
        Tips and Tricks from the MODX Forums and Slack Channels - http://modxcookbook.com
        Join the Slack Community - http://modx.org
        • 36467
        • 73 Posts
        Yes i really need to login to remote modx install. Because, We have MODx on www.abc.com and we want to run a campaign on www.xyz.com and we want to allow access to only users who have account on abc.com to participate in a campaign. So its must thing that we ask user to login to abc.com to access xyz.com voting polls, comment etc.

        I can directly access the database and users info. But for that i will have to check all the conditions manually like if username and password is correct, if he's blocked, if the date is beyond 'valid till' condition, user groups, etc etc. There is no meaning to code all this things if MODx API already providing it.
          • 28042 ☆ A M B ☆
          • 24,524 Posts
          Ok, that's a different matter then. You might want to consider how Vanilla's jsconnect works. http://vanillaforums.com/blog/help/implementing-jsconnect-single-signon-on/
            Studying MODX in the desert - http://sottwell.com
            Tips and Tricks from the MODX Forums and Slack Channels - http://modxcookbook.com
            Join the Slack Community - http://modx.org
            • 37099
            • 338 Posts
            Temporarily copy the users of abc.com to xyz.com ?
              • 28042 ☆ A M B ☆
              • 24,524 Posts
              You should be able to use AJAX and JSONP to trigger the Login snippet from a remote server.

              http://json-p.org/
                Studying MODX in the desert - http://sottwell.com
                Tips and Tricks from the MODX Forums and Slack Channels - http://modxcookbook.com
                Join the Slack Community - http://modx.org
                • 36467
                • 73 Posts
                @sottwell,@thingstodo : I think i sorted it out, i am able to login to the modx from other server, I am now finishing the code. I will post the code here so other users can see the solution. Problem was not cross domain access but it was more i wasn't able to access user details, So i copied code from security/login.php file. [ed. note: amitpatil last edited this post 13 years, 9 months ago.]
                  • 36467
                  • 73 Posts
                  Ok here is the solution which worked for me, Instead of using modx api i decided to go with normal snippets. So i created resource with a snippet call in it. Below is the snippet code.

                  This is cross site HTTP request so you must define CORS specification with PHP header function.
                  header("Access-Control-Allow-Origin: http://www.xyz.com");

                  this will give cross site access to this page from only domain defined (in our example its "http://www.xyz.com" )

                  header("Access-Control-Allow-Origin: http://www.xyz.com");
                  if(isset($_POST['username']) && isset($_POST['password'])){
                  		
                  	// get username and password from POST array
                  	$username = $modx->sanitizeString($_POST['username']); 
                  	$password = $modx->sanitizeString($_POST['password']); 
                      if(trim($username) != "" and trim($password) != ""){
                  		// Load lexicons to show proper error messages
                  		if (!isset($modx->lexicon) || !is_object($modx->lexicon)) {
                  			$modx->getService('lexicon','modLexicon');
                  		}
                  		$modx->lexicon->load('login');
                  
                  		$loginContext= isset ($scriptProperties['login_context']) ? $scriptProperties['login_context'] : 
                  		$modx->context->get('key');
                  
                  		$addContexts= isset ($scriptProperties['add_contexts']) && !empty($scriptProperties['add_contexts']) ? explode(',', $scriptProperties['add_contexts']) : array();
                  
                  		$mgrEvents = ($loginContext == 'mgr');
                  
                  		$givenPassword = $password;
                  
                  		/** @var $user modUser */
                  		$user= $modx->getObjectGraph('modUser', '{"Profile":{},"UserSettings":{}}', array ('modUser.username' => $username));
                  
                  		if (!$user) {
                  			$ru = $modx->invokeEvent("OnUserNotFound", array(
                  				'user' => &$user,
                  				'username' => $username,
                  				'password' => $password,
                  				'attributes' => array(
                  					'loginContext' => $loginContext,
                  				)
                  			));
                  
                  			if (!empty($ru)) {
                  				foreach ($ru as $obj) {
                  					if (is_object($obj) && $obj instanceof modUser) {
                  						$user = $obj;
                  						break;
                  					}
                  				}
                  			}
                  			
                  			if (!is_object($user) || !($user instanceof modUser)) {
                  				//echo "cant locate account";
                  				echo $modx->toJSON($modx->error->failure($modx->lexicon('login_cannot_locate_account')));
                  				exit;
                  			}
                  		}
                  
                  		if (!$user->get('active')) {
                  			//echo "inactivated accout";
                  			echo $modx->toJSON($modx->error->failure($modx->lexicon('login_user_inactive')));
                  				exit;
                  			}
                  
                  		if (!$user->passwordMatches($givenPassword)) {
                  			if (!array_key_exists('login_failed', $_SESSION)) {
                  				$_SESSION['login_failed'] = 0;
                  			}
                  			if ($_SESSION['login_failed'] == 0) {
                  				$flc = ((integer) $user->Profile->get('failedlogincount')) + 1;
                  				$user->Profile->set('failedlogincount', $flc);
                  				$user->Profile->save();
                  				$_SESSION['login_failed']++;
                  			} else {
                  				$_SESSION['login_failed'] = 0;
                  			}
                  			//echo "wrong username pass";
                  			echo $modx->toJSON($modx->error->failure($modx->lexicon('login_username_password_incorrect')));
                  				exit;
                  			}
                  		
                  			$fullname =  $user->Profile->get('fullname');
                  			echo '{"success":true,"message":"Welcome '.$fullname.'!"}';
                       }else{
                  			echo '{"success":false,"message":"Please enter username and password"}';
                  	 }
                  }


                  And my login page is located at other server which calls resource page located at some other server using normal jquery ajax function.

                  	$.ajax({
                  		type : "POST",
                  		url  :"http://www.abc.com/login-check",
                          data : "username="+$("#uname").val()+"&password="+$("#upass").val(),
                  		success: function(responce){
                  			var responce = jQuery.parseJSON(responce);
                  			if(!responce.success){
                  				$(".msg").html("<font color='red'>"+responce.message+"</font>");
                  			}else if(responce.success){
                  				$(".msg").html("<font color='green'>"+responce.message+"</font>");
                  			}
                  		}
                  	});
                  

                  • discuss.answer
                    • 10208 ☆ A M B ☆
                    • 1,780 Posts
                    response works when it's spelled responce?

                    ??
                      Frogabog- MODX Websites in Portland Oregon
                      "Do yourself a favor and get a copy of "MODX - The Official Guide" by Bob Ray. Read it.
                      Having server issues? These guys have MODX Hosting perfected - SkyToaster
                      • 36467
                      • 73 Posts
                      Quote from: frogabog at Dec 23, 2012, 02:25 PM
                      response works when it's spelled responce?

                      ??
                      You mean in the javascript ? If so then, yes its wrong spelled wink but whatever you use it must e consistent all over.