User Class

I'm using:
PHP:
function check_login()
{
/**
* initialize
*/
XenForo_Application::initialize($this->fileDir . '/library', $this->fileDir);
XenForo_Session::startPublicSession();
$this->xfUser = XenForo_Visitor::getInstance();
$this->xfUser_Id = $this->xfUser->getUserId();
if (is_numeric($this->xfUser_Id) && $this->xfUser_Id > 0)
{
$this->get_info($this->xfUser_Id);
$this->set_online();
return true;
}
else
{
return false;
}
}
But like I said, I'm new to developing for this so I don't know if there's a better way or if this isnt' a good way at all
 
Yea looks good, I guess for me that would be part of a Component (for the controller) rather than a Helper (for the view) but that's just CakePHP's terminology lol.

What about logging in? Has anyone tried to do that from the site (i.e. not posting to xen's login.php file).

I think I just got done doing this..

Here is my user_integration class.

PHP:
<?php
class User_Integration extends User
{
function User_Integration(&$parent)
{
$this->parent =& $parent;
$this->user_info = array('ip' => $_SERVER['REMOTE_ADDR']);
$this->auth = new user_auth(&$this);
$this->fileDir = '../../site/';
require ($this->fileDir . '/library/XenForo/Autoloader.php');
XenForo_Autoloader::getInstance()->setupAutoloader($this->fileDir . '/library');
XenForo_Application::initialize($this->fileDir . '/library', $this->fileDir);
}
function is_admin()
{
return false;
}
function check_login()
{
$this->XenForo_User_Object = XenForo_Model::create('XenForo_Model_User');
if (isset($_SESSION['username']))
$username = $_SESSION['username'];
elseif (isset($_POST['username']))
{
$username = $_POST['username'];
$_SESSION['username'] = $username;
}
else
{
return false;
// Put error messages here \\
}
if (isset($_SESSION['password']))
$password = $_SESSION['password'];
elseif (isset($_POST['password']))
{
$password = $_POST['password'];
$_SESSION['password'] = $password;
}
else
{
return false;
// Put error messages here \\
}
$this->XenForo_User = $this->XenForo_User_Object->getUserByName($username);

if ($this->XenForo_User_Object->getUserAuthenticationObjectByUserId($this->XenForo_User['user_id'])->authenticate($this->XenForo_User['user_id'], $password))
{
$this->get_xen_info($this->XenForo_User['user_id']);
return true;
}
else
{
return false;
// Error message here \\
}
}
function get_xenforo_info($id)
{
if (!is_numeric($id))
return false;

$this->user_info = array('id' => $id);

if (isset($this->user_info['id']) && is_numeric($this->user_info['id']))
{
$user = XenForo_Model::create('XenForo_Model_User')->getUserById($this->user_info['id'], array('join' => 17));
}
elseif (isset($this->user_info['username']))
{
$user = XenForo_Model::create('XenForo_Model_User')->getUserByName($this->user_info['username']);
}
$user['group'] = XenForo_Model::create('XenForo_Model_UserGroup')->getUserGroupById($user['user_group_id']);
$this->user_info = array(
'id' => $user['user_id'],
'username' => $user['username'],
'email' => $user['email'],
'avatar' => $this->fileDir . 'data/avatars/m/0/' . $user['user_id'] . '.jpg'
);
if ($user['is_admin'] == 1)
{
foreach ($this->parent->default_auth->auth_array as $item => $permission)
{
$this->auth->auth_array[$item] = 1;
}
$this->auth->array_to_string();
}
$color = '000';
if (!empty($user['group']['username_css']))
{
$get_color = explode('color:', $user['group']['username_css']);
if (!empty($get_color[1]))
$get_color = explode('#', $get_color[1]);
if (!empty($get_color[1]))
$color = $get_color[1];
}
$this->user_info['user_color'] = $color;
$this->user_info['message_color'] = $color;
$this->user_info['auth_string'] = $this->auth->auth_string;
if (!is_numeric($user['user_id']))
{
$this->parent->Errors->error("Could not find the requested user.", 'other');
return false;
}
else
{
return;
}
}
function register()
{
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$xen_dw = XenForo_DataWriter::create('XenForo_DataWriter_User');
$xen_dw->set('username', $username);
$xen_dw->setPassword($password);
$xen_dw->set('email', $email);
$xen_dw->set('user_group_id', 2);
$xen_dw->save();
}
}
 
the startPublicSession method should already be loading the user from the cookie/session even if you haven't been to the forums in that session. My question was just about the post part. What I've got currently after the initialization stuff is below.

Some bits could probably be improved upon but that should cut down the amount of code you need. Especially in respect to the usertitle and avatar url.
PHP:
//load userinfo
XenForo_Session::startPublicSession($request);
$this->user = XenForo_Visitor::getInstance();
$this->userinfo = $this->user->toArray();

//set base forum url - so that Xenforo::Link will refer from the right directory.
$request = new Zend_Controller_Request_Http();
$request->setBasePath('/community');

//update session activity so that the user still appears as online while viewing website
XenForo_Model::create('XenForo_Model_User')->updateSessionActivity(
    $this->user->getUserId(), $request->getClientIp(false),
    "XenForo_ControllerPublic_Index", "Index", "valid", $request->getUserParams()
);

//preload other data - usertitle/avatar
$dependencies = new XenForo_Dependencies_Public();
$dependencies->preLoadData();
$this->userinfo['usertitle'] = XenForo_Template_Helper_Core::helperUserTitle($this->userinfo);
$this->userinfo['avatarurl'] = '/community/'.XenForo_Template_Helper_Core::helperAvatarUrl($this->userinfo, 's');
 
Oh, I get what you're saying. You're wanting to have a login form on your site that logs them into both, right? The reason I have it the way I do without the Session thing is because mine is for a chat system. www.osphpchat.com and sometimes you want to login on another account or you don't want to be logged in on the site etc...

I'm not sure how you would go about doing what you're trying to do.
 
Yeah that's what I was looking to Daniel.

Anyways I've spent some more time looking into it and now have the following two functions (mostly re-using code from Xenforo's own codebase) which serves the login/logout purpose for me. I then just call those functions from my controller. I'm just posting it in-case anyone else comes across needing the same thing.

PHP:
    public function login($data)
    {
        $loginModel = XenForo_Model::create('XenForo_Model_Login');
        $userModel = XenForo_Model::create('XenForo_Model_User');
        $error = "";

        $userid = $userModel->validateAuthentication($data['login'], $data['password'], $error);
        if (!$userid)
        {
            $loginModel->logLoginAttempt($data['login']);
            return $error;
        }

        $loginModel->clearLoginAttempts($data['login']);

        if ($data['remember'])
        {
            $userModel->setUserRememberCookie($userid);
        }

        XenForo_Model_Ip::log($userid, 'user', $userid, 'login');

        $userModel->deleteSessionActivity(0, $this->request->getClientIp(false));

        $session = XenForo_Application::get('session');

        $session->changeUserId($userid);
        XenForo_Visitor::setup($userid);

        return;
    }

    public function logout()
    {
        // remove an admin session if we're logged in as the same person
        if (XenForo_Visitor::getInstance()->get('is_admin'))
        {
            $adminSession = new XenForo_Session(array('admin' => true));
            $adminSession->start();
            if ($adminSession->get('user_id') == XenForo_Visitor::getUserId())
            {
                $adminSession->delete();
            }
        }

        XenForo_Model::create('XenForo_Model_Session')->processLastActivityUpdateForLogOut(XenForo_Visitor::getUserId());

        XenForo_Application::get('session')->delete();
        XenForo_Helper_Cookie::deleteAllCookies(
            array('session'),
            array('user' => array('httpOnly' => false))
        );

        XenForo_Visitor::setup(0);

        return;
    }
 
Expanding on my post from several months ago I'm wondering if anyone has taken it a step further in terms of doing control panel (admincp) logins?

I've got a control panel of my own for controlling the various aspects of the site, I was hoping to use Xenforo's Admin Session to control their session, timeout etc (so storing the session in the xf_session_admin table).

So where I authenticate the user/session and grab the userinfo I have the following in my public script (this works):
PHP:
XenForo_Session::startPublicSession($this->request);
$this->user = XenForo_Visitor::getInstance();
$this->userinfo = $this->user->toArray();
And in my new admin script I have this:
PHP:
$session = XenForo_Session::startAdminSession($this->request);
XenForo_Visitor::setup($session->get('user_id'));
$this->user = XenForo_Visitor::getInstance();
$this->userinfo = $this->user->toArray();

Does that look right or wrong to anyone? I'm not sure whether I need to call that setup function or not.

The other part I'm unsure on is the login function.My admin login function so far is below:

PHP:
    public function login($data)
    {
        $loginModel = XenForo_Model::create('XenForo_Model_Login');
        $userModel = XenForo_Model::create('XenForo_Model_User');
        $error = "";

        $userid = $userModel->validateAuthentication($data['login'], $data['password'], $error);

        if (!$userid)
        {
            $loginModel->logLoginAttempt($data['login']);
            return $error;
        }

        $loginModel->clearLoginAttempts($data['login']);

        XenForo_Model_Ip::log($userid, 'user', $userid, 'login');

        $session = XenForo_Application::get('session');
        //$session = new Xenforo_Session();
        $session->changeUserId($userid);
        $session->save();
        XenForo_Visitor::setup($userid);

        // if guest on front-end, login there too
        $publicSession = new XenForo_Session();
        $publicSession->start();
        if (!$publicSession->get('user_id'))
        {
            $publicSession->changeUserId($userid);
            $publicSession->save();
        }

        //update session activity
        XenForo_Model::create('XenForo_Model_User')->updateSessionActivity(
            $this->user->getUserId(), $this->request->getClientIp(false),
            "XenForo_ControllerPublic_Index", "Index", "valid", $this->request->getUserParams()
        );

        return;
    }

It's very similar to the function I posted previously. I just looked at what had changed in XF's AdminController function and tried to adapt mine the same. Except I took out the is_admin check as that would always fail due to using my own admin user table.

The login itself autheticates fine i.e. it accepts the username/password, however when I echo out the userid from where I authenticate the session (the top bit of code) it comes back as 0.

Using the old authentication code (when I'm using startPublicSession rather than startAdminSession) it returns their userid, but it just doesnt seem to recognise the admin login. Any help would be appreciated.

EDIT: looking at the session_admin table it seems to be populating it but the expiry is set to the current date/time. And obviously I can't seem to get it to recognise the session lol.

EDIT 2: When I log into the forumcp and then use the authentication code above it returns the correct userid. Whereas when I use my own login function (above) the authentication code returns 0. I can't see what I'm doing wrong in my login function though.
 
If you mean from the Login function then no. If I did I know the userid would be correct. The call to validateAuthentication (which validates the login details) works great. That's not the issue.

However something seems to be wrong with how I'm saving the admin session in that login function. The code at the top which should be loading the admin session is instead returning 0 for the userid (I do return the userid in that function but as I showed me getting the userinfo array I didn't see much point posting that line). I know it's not an issue with that bit of code as it recognises when you're logged into the forum's admincp.

My code does create an entry into the session_admin table but it's not being recognised. It doesn't even seem to be setting the public session correctly (if I'm not logged in on the public side it should be logging me in there too). Yet my almost duplicate code works for the public login lol.

EDIT: No worries, it seems to be sorted now. I just re-did the two functions from scratch (well from the public versions I had) and that time it worked. Not quite sure which line/s it were that were wrong but it looks almost identical lol.
 
If you mean from the Login function then no. If I did I know the userid would be correct. The call to validateAuthentication (which validates the login details) works great. That's not the issue.

However something seems to be wrong with how I'm saving the admin session in that login function. The code at the top which should be loading the admin session is instead returning 0 for the userid (I do return the userid in that function but as I showed me getting the userinfo array I didn't see much point posting that line). I know it's not an issue with that bit of code as it recognises when you're logged into the forum's admincp.

My code does create an entry into the session_admin table but it's not being recognised. It doesn't even seem to be setting the public session correctly (if I'm not logged in on the public side it should be logging me in there too). Yet my almost duplicate code works for the public login lol.

EDIT: No worries, it seems to be sorted now. I just re-did the two functions from scratch (well from the public versions I had) and that time it worked. Not quite sure which line/s it were that were wrong but it looks almost identical lol.

Is there a way that you can post your final code, I'm new to XenForo and It would help me alot :D
 
+1 Rjs, Great work - please repost final code. I need a very similar login system
 
Everytime I try to login using Rjs script I get this error: anyone know why? :(

Fatal error: Uncaught exception 'XenForo_Exception' with message 'The session has been saved and is now read-only.'
 
Top Bottom