Have you ever thought how nice it would be to send emails with an url that automatically logs you in?
Especially for a messaging system this can be quite handy: One click in the notification email and you can answer right away.
How does it work?
Here an example with a notification email:
$text = 'You got mail!'.PHP_EOL;
if (!isset($this->Qlogin)) {
$this->Qlogin = ClassRegistry::init('Tools.Qlogin');
}
$text .= $this->Qlogin->url(array('admin'=>false, 'plugin'=>false, 'controller'=>'conversations', 'action'=>'view', $conversation['Conversation']['id'])), $user['User']['id']).PHP_EOL;
//send email
We create a quicklink using the url where the user should be redirect to after the login as first param and the actual user_id to authenticate with as second param.
Pretty straight forward.
Let’s say, the generated url is http://domain/qlogin/1234567890
.
Once the user clicks on the link, the "go" action of the QloginController gets triggered and tries to find the corresponding user as well as target url. If found, the user is logged in and directly passed on to the desired page.
Note: If the user is already logged in, he will be redirected immediately (skipping the login).
I added this to my routes.php
Router::connect('/qlogin/*', array('plugin'=>'tools', 'controller' => 'qlogin', 'action'=>'go'));
in order to result in the above url which is pretty short and convenient.
The code
Its available at github (currently only for 2.x): Tools plugin.
You need the model as well as the controller.
Some notes
The Module is still pretty basic. But it works flawlessly with my setup. I would like your feedback on it, though.
AuthComponent::login() should respect the scope you defined as well as the default redirect urls.
Right now I am trying out the Qlogins in combination with AutoLogin – if those cookies don’t intefere. But it seems to work fine.
Dependencies
Model Token (@see article) (to store the tokens) as well as the url validation method and get() of my MyModel (can also be put into your AppModel).
And since it is deeply integrated in my usual everyday apps it also requires at least the CommonComponent of the Tools plugin. For the optional admin backend there are more dependencies.
So basically you need:
//AppController
public $components = array('Tools.Common');
//AppModel
App::uses('MyModel', 'Tools.Lib');
class AppModel extends MyModel {}
Of course you may through out any methods you don’t need.
And you can always cherry-pick the stuff you specifically want to use.