I need a function to logout a craft user and delete the session of that user. This must take place in the element API plugin as an endpoint. Something like this:

function userLogout(){
    if (craft()->userSession->isLoggedIn()){
        // if user loggedin
        // how to logout?

'api/logout' => array(
    'elementType' => 'User',
    'criteria' => ['id' => craft()->userSession->user->id, 'limit' => 1 ],
    'paginate' => false,
    'transformer' => function(\Craft\UserModel $user) {

You can end a user's session with the craft()->userSession->logout(), method, which the UserSessionService class inherits from the CWebUser class.

So, your userLogout function would look like this:

function userLogout(){
    if (craft()->userSession->isLoggedIn()){

Additional information

Passing false to the logout method tells Yii not to "destroy" the session, and mimics the call in Craft's UsersController::logout method.

According to the Yii documentation, destroy "frees all session variables and destroys all data registered to a session." I'm unclear why Craft chooses not to destroy the session.

The UsersController::logout method also includes a few cleanup tasks, but those seem to be duplicates of the tasks performed in the UserSessionService::afterLogout method.

The afterLogout method is called from the craft()->userSession->logout() method, so you shouldn't have to worry about this manual cleanup.

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.