Last active
November 4, 2020 15:27
-
-
Save cgi-caesar/7c3b2c0e10cd981dd1d237ee1b033617 to your computer and use it in GitHub Desktop.
aMember (site.php): Add CSRF token to login form
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function _csrf_hash($tm) | |
{ | |
$sesid = Am_Di::getInstance()->session->getId(); | |
$id = 'login'; | |
return Am_Di::getInstance()->security->hash("{$tm}:{$id}:{$sesid}", 10); | |
} | |
function _csrf_token() | |
{ | |
$tm = Am_Di::getInstance()->time; | |
$hash = _csrf_hash($tm); | |
return "{$tm}:{$hash}"; | |
} | |
function _csrf_check($token) | |
{ | |
@list($_tm, $_hash) = explode(':', $token); | |
return $_hash | |
&& _csrf_hash($_tm) == $_hash | |
&& (Am_Di::getInstance()->time - $_tm) < 60*15; | |
} | |
Am_Di::getInstance()->hook->add(Am_Event::BEFORE_RENDER, function(Am_Event $e) { | |
if (stripos($e->getTemplateName(), '_login-form.phtml')!== false) { | |
$h = $e->getView()->hidden ?: []; | |
$h['_csrf'] = _csrf_token(); | |
$e->getView()->hidden = $h; | |
} | |
}); | |
Am_Di::getInstance()->hook->add(Am_Event::AUTH_CONTROLLER_HANDLER, function(Am_Event $e) { | |
if (defined('AM_ADMIN') && AM_ADMIN) return; | |
$handler = $e->getReturn(); | |
$e->setReturn(function(Am_Auth_Abstract $auth, Am_Mvc_Request $r) use ($handler) { | |
if (!$r->getParam('_csrf') || !_csrf_check($r->getParam('_csrf'))) { | |
return new Am_Auth_Result(Am_Auth_Result::INVALID_INPUT, | |
___('Session expired, please refresh page and login')); | |
} | |
return $handler($auth, $r); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment