XF 2.0 Login/logout from another script?

Rodolfo

Active member
I've been able to load XenForo framework from an external script (same website) by doing this:

PHP:
require(XF_ROOT . '/src/XF.php');
XF::start(XF_ROOT);
$XF = XF::setupApp('XF\Pub\App');
$XF->start();
if(XF::visitor()->user_id) {
// Logged user stuff...
}

For login, I'm doing this:
PHP:
$ip = $XF->request->getIp();
$service = $XF->service('XF:User\Login', $input, $ip);
$user = $service->validate($password, $error);
//completeLogin
$XF->session->changeUser($user);
XF::setVisitor($user);
$XF->repository('XF:SessionActivity')->clearUserActivity(0, $ip);
$XF->repository('XF:Ip')->logIp(
  $user->user_id, $ip,
  'user', $user->user_id, 'login'
);
//createVisitorRememberKey
$rememberRepo = $XF->repository('XF:UserRemember');
$key = $rememberRepo->createRememberRecord($user->user_id);
$value = $rememberRepo->getCookieValue($user->user_id, $key);
//$XF->response()->setCookie('user', $value, 365 * 86400); // Uh, didn't work...
setcookie('xf_user', $value, time() + (365 * 86400), '/'); // ugly

Since I wasn't able to load XF:Login as a plugin, I tried to replicate it manually and it works but I'm not sure if this is the right way to achieve this and I think that I'm missing something. I've tried to use XF:Login by doing $XF->plugin('XF:Login') but the method isn't there and I don't know which is the right way to access to it (so I can call completeLogin and logoutUser with every cookie/session/token properly updated).

Unfortunately, I can't figure out how to handle that login controller.
 
Last edited:
PHP:
<?php
const XF_ROOT = __dir__; // change this as needed
require(XF_ROOT . '/src/XF.php');
\XF::start(XF_ROOT);
$XF = \XF::setupApp('XF\Pub\App');
$XF->start();
$class = \XF::app()->extendClass('XF\Pub\Controller\Login');
$loginController = new $class(\XF::app(), \XF::app()->request());
$loginController->actionLogin();
if(\XF::visitor()->user_id) {
    // do your stuff
}
 
Top Bottom