Skip to content

Instantly share code, notes, and snippets.

@nick2687
Created June 17, 2015 01:52
Show Gist options
  • Save nick2687/ee598e2446c3609d73ab to your computer and use it in GitHub Desktop.
Save nick2687/ee598e2446c3609d73ab to your computer and use it in GitHub Desktop.
This controller can be used with the modrestcontroller class to preform basic remote authentication through the modrestservice class (modx rest api). Should only be used over https as it requires the username & pass to be sent along as a url param.
<?php
/**
* Found at: Controllers/Box.php
*
* Handle requests to [URL]/Controllers/Box. Automagically handles CRUD (GET/POST/PUT/DELETE) for the xPDOObject class myBox.
*/
class MyControllerAuth extends modRestController {
public $classKey = 'modUser';
public $defaultSortField = 'id';
public $defaultSortDirection = 'ASC';
public function verifyAuthentication() {
if ($this->request->method != 'get') Throw new Exception('Method Not Allowed', 405); // Only allow GET requests to the AUTH controller
if ($this->modx->user || $this->modx->user->id >= 1) { // If user is logged in & user passes the "logout" param than log them out
if ($_GET['logout']) {
$this->modx->runProcessor('security/logout',array(
'login_context' => $this->getProperty('loginContext', $this->modx->context->get('key')),
'add_contexts' => $this->getProperty('contexts',''),
));
}
}
if (!$this->modx->user || $this->modx->user->id < 1) { // If not logged in & user passes a username & password preform basic auth by running login processor
$c = array(
'username' => $_GET['username'],
'password' => $_GET['password'],
);
$this->modx->runProcessor('security/login',$c);
}
if (!$this->modx->user || $this->modx->user->id < 1) return false; //finally do a check to see if user is logged in or not & either send back a true or false
return true;
}
protected function prepareListQueryBeforeCount(xPDOQuery $c) { // If user is logged in return their basic user info
$c->where(array(
'id' => $this->modx->user->id
));
return $c;
}
}
@eveningcoffee
Copy link

Hi @nick2687, I was hoping you could help with a problem.
I've taken your auth controller and set up the rest api on my site. But whenever I try sending a GET request with the username and password in the URL params (http://domain.co.uk/rest/auth?username=username&password=pword)) it returns an error:
Fatal error: Call to a member function get() on a non-object in /home/site/public_html/core/model/modx/processors/security/login.class.php on line 34

Line 34 is
$this->loginContext = $this->getProperty('login_context', $this->modx->context->get('key'));

I feel this issue is something to do with the context that is being passed to the login processor, any advice?

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment