Sign In With Twitter For MODX

Share this on:

How to set up your MODX web pages so users can log in with their Twitter accounts

assets/images/modx-twitteroauth-files.png

In a previous article we explained how to implement the twitteroauth library by Abraham Williams and described how it works. In this article we explain how to implement it in MODX.

By the end of this article a user will be able to log in using their Twitter account, an equivalent MODX user will be created and we will add that user to a group that can then be managed by MODX. When the Twitter user again logs in he will be associated with that MODX user.

It's mostly about putting the files in the right place and making sure everything points to what it is supposed to be pointing to, and changing a few settings.

This is the step by step instructions of how you can do that:

1) If you haven't already got it download the twitteroauth files from the github repository.

2) In your MODX installation create two new directories

  • assets/components/twitteroauth
  • core/components/twitteroauth

3) Copy all the downloaded files and folders except sample-config.php to assets/components/twitteroauth

4) Copy sample-config.php to core/components/twitteroauth and change its name to config.php

5) Go to https://dev.twitter.com click the down arrow next to your Twitter avatar and choose "My Applications"

6) Create a new application with the following values:

  • Name: A name for your application ( 'Twitter' is not allowed in the name)
  • Description: A description of your application
  • Website: http://website-name.com
  • Callback URL: http://website-name.com/callback.html

Agree to the terms and conditions and be prepared to cut and paste the long strings of digits that are the Consumer key and the Consumer secret

7) Now edit core/components/twitteroauth/config.php so that it looks something like this:

	define('CONSUMER_KEY', '9uhg3hy28jh6Ko9ilwwqr4');
	define('CONSUMER_SECRET', '2s3RYYa77hgoPOk9TfdgNl6KaMURSwrey7k8LaTP7vF');
	define('OAUTH_CALLBACK', 'http://website-name.com/callback.html');

8) Now in MODX go to System => System Settings filter by area Friendly URL and set automatic_alias to Yes and friendly_urls to Yes

9) Create a new snippet called include

<?php
if (file_exists($file)) {
   $o = include $file;
} else { $o = 'File not found at: '.$file; }
return $o;

10) In MODX package manager download Wayfinder and Ace

11) Edit the Base Template, use this code:

<html> 
<head> 
<title>[ [++site_name] ] - [ [*pagetitle] ]</title> 
<base href="[ [++site_url] ]" /> 
</head> 
<body> 
[ [!Wayfinder? &startId=`0` &level=`0`] ] 
[ [*content] ] 
</body> 
</html>

12) Now we need to create some resources to use. All the resources we create will have an emprty template except loggedin. Create the following resources, make them all published and uncacheable (I created them in a container resource for tidiness but you can create them in the root if you want):

a)

  • Title: connect
  • Template: empty
  • Content: [ [!include? &file=`assets/components/twitteroauth/connect.php`] ]

b)

  • Title: callback
  • Template: empty
  • Content: [ [!include? &file=`assets/components/twitteroauth/callback.php`] ]

c)

  • Title: loggedin
  • Template: Base Template
  • Content: [ [!loggedin] ]

d)

  • Title: clearsessions
  • Template: empty
  • Content:

e)

  • Title: redirect
  • Template: empty
  • Content: [ [!include? &file=`assets/components/twitteroauth/redirect.php`] ]

13) Create a new snippet called loggedin with this code

<?php
session_start();
require_once('assets/components/twitteroauth/twitteroauth/twitteroauth.php');
require_once('core/components/twitteroauth/config.php');
/* If access tokens are not available redirect to connect page. */
if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) {
    header('Location: <span  style="font-family: Arial, Helvetica, Verdana, Tahoma, sans-serif;"><a href="http://tweetswinprizes.thingstodo.modxcloud.com/clearsessions.html">http://tweetswinprizes.thingstodo.modxcloud.com/clearsessions.html</a></span>');<br>}
/* Get user access tokens out of the session. */
$access_token = $_SESSION['access_token'];
/* Create a TwitterOauth object with consumer/user tokens. */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$o = "Session[access_token]: ". print_r($_SESSION['access_token'],true);
$o .= "Session[status}]: ". print_r($_SESSION['status'],true);
$screen_name = $_SESSION['access_token']['screen_name'];
echo "screen name: ".$screen_name.'<br>';
if ($user = $modx->getObject('modUser', array('username'=>$screen_name))){
   //do something with existing user
   echo "User exists <br>";
}
else{
    //add new user
    $user = $modx->newObject('modUser', array('username'=> $screen_name));
    $userProfile = $modx->newObject('modUserProfile');
    $userProfile->set('fullname',$screen_name);
    $userProfile->set('email',$screen_name.'@onsitenow.co.uk');
    $success = $user->addOne($userProfile);
    if($success){
        $user->save();
        $o .= '<p>User object and profile created</p>';
    }
    else {
        $o .=  '<p>Failed to add profile. User not saved.</p>';
    }
    $user->joinGroup('TwitterUsers', 1);
    if($user->isMember('TwitterUsers')){
        $o .=  '<p>User is now in TwitterUsers.</p>';
    }
    else {
        $o .=  '<p>User is NOT in TwitterUsers.</p>';
    }
}
// Log user in
// get user
$modx->user =& $user;
// set session context(s) to log into
$contexts = !empty($scriptProperties['authenticateContexts']) ? $scriptProperties['authenticateContexts'] : $modx->context->get('key');
$contexts = explode(',',$contexts);
foreach ($contexts as $ctx) {
    $modx->user->addSessionContext($ctx);
}
if($modx->user->hasSessionContext('web')){
    $o .= "<br>User is logged in as MODX user<br>";
}
else{
    $o .= "<br>User is NOT logged in as MODX user<br>";
}
return $o;

14) Now we need to edit the twitteroauth files that we downloaded from github, so that they reflect the new arrangement that they are in.

a) In callback.php

Change

	require_once('twitteroauth/twitteroauth.php');
	require_once('config.php');

to

	require_once(__DIR__.'/twitteroauth/twitteroauth.php')
	require_once('core/components/twitterOAuth/config.php');

and (in two places) change

	header('Location: ./clearsessions.php');

to

	header('Location: clearsessions.html');

and

	header('Location: ./index.php');

to

	header('Location: /loggedin.html');

b) In clearsessions.php

change

	header('Location: ./connect.php');

to

	header('Location: connect.html');

c) In connect.php

change

	require_once('config.php');

to

	require_once('core/components/twitteroauth/config.php');

and change

	$content = '<a href="./redirect.php"><img src="./images/lighter.png" alt="Sign in with Twitter"/></a>';

to

	$content = '<a href="redirect.html"><img src="assets/components/twitteroauth/images/lighter.png" alt="Sign in with Twitter"/></a>';

d) In index.php

change

	require_once('twitteroauth/twitteroauth.php'); 
	require_once('config.php');

to

	require_once(__DIR__.'/twitteroauth/twitteroauth.php');
	require_once('../../../core/components/twitteroauth/config.php');

and

	header('Location: ./clearsessions.php');

to

	header('Location: clearsessions.html');

e) In redirect.php

change

	require_once('twitteroauth/twitteroauth.php');
	require_once('config.php');

to

	require_once(__DIR__.'/twitteroauth/twitteroauth.php');             		
	require_once('core/components/twitteroauth/config.php');

15) In the MODX manager create the group TwitterUsers

OK, you should now be able to go to your web pages and sign in with Twitter. If you put your resources in a container make sure it is published so that you can see your resources. Select connect and you should see the "sign in with Twitter" button.

When you sign in for the first time you will get some feedback telling you that a user object has been created, that the user is in the TwitterUsers group and that the user is logged in as a MODX user. When you subsequently log in the feed back will tell you you are an existing user, and you will be logged in as such.

All the feedback comes from the loggedin snippet. Edit this to make it do something useful, like redirect to a welcome page.

The next step is to make it into a usable extra!

There may well be better ways of doing this, i'd welcome suggestions. For a start It probably makes sense to put the Consumer key and Consumer secret in the system settings....

Can anyone tell me the best way to make it into a package?

Share this on:
Mike Nuttall

Author: Mike Nuttall

Mike has been web designing, programming and building web applications in Leeds for many years. He founded Onsitenow in 2009 and has been helping clients turn business ideas into on-line reality ever since. Mike can be followed on Twitter and has a profile on Google+.

1 comments
  1. Chisangu

    Chisangu
    Jun 10, 2015 at 01:13 PM

    Thanks, this has been very useful. I'm using Facebook SDK for PHP but the same applies I believe.

    Thanks