Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sebastian-marinescu/c335f8877152d039f9e1d9811d8ef557 to your computer and use it in GitHub Desktop.
Save sebastian-marinescu/c335f8877152d039f9e1d9811d8ef557 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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment