More authentication refactoring to also provide "plugable" credentials handling (references #921, needed for #305)

This commit is contained in:
Bernd Bestel
2020-10-19 18:38:12 +02:00
parent 9f88dd3af3
commit 94214b867a
9 changed files with 81 additions and 52 deletions

View File

@@ -2,13 +2,13 @@
namespace Grocy\Controllers;
use Grocy\Services\SessionService;
class LoginController extends BaseController
{
protected $SessionCookieName;
public function GetSessionCookieName()
public function __construct(\DI\Container $container)
{
return $this->SessionCookieName;
parent::__construct($container);
}
public function LoginPage(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
@@ -18,50 +18,20 @@ class LoginController extends BaseController
public function Logout(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{
$this->getSessionService()->RemoveSession($_COOKIE[$this->SessionCookieName]);
$this->getSessionService()->RemoveSession($_COOKIE[SessionService::SESSION_COOKIE_NAME]);
return $response->withRedirect($this->AppContainer->get('UrlManager')->ConstructUrl('/'));
}
public function ProcessLogin(\Psr\Http\Message\ServerRequestInterface $request, \Psr\Http\Message\ResponseInterface $response, array $args)
{
$postParams = $this->GetParsedAndFilteredRequestBody($request);
if (isset($postParams['username']) && isset($postParams['password']))
$authMiddlewareClass = GROCY_AUTH_CLASS;
if ($authMiddlewareClass::ProcessLogin($this->GetParsedAndFilteredRequestBody($request)))
{
$user = $this->getDatabase()->users()->where('username', $postParams['username'])->fetch();
$inputPassword = $postParams['password'];
$stayLoggedInPermanently = $postParams['stay_logged_in'] == 'on';
if ($user !== null && password_verify($inputPassword, $user->password))
{
$sessionKey = $this->getSessionService()->CreateSession($user->id, $stayLoggedInPermanently);
setcookie($this->SessionCookieName, $sessionKey, PHP_INT_SIZE == 4 ? PHP_INT_MAX : PHP_INT_MAX >> 32);
// Cookie expires never, but session validity is up to SessionService
if (password_needs_rehash($user->password, PASSWORD_DEFAULT))
{
$user->update([
'password' => password_hash($inputPassword, PASSWORD_DEFAULT)
]);
}
return $response->withRedirect($this->AppContainer->get('UrlManager')->ConstructUrl('/'));
}
else
{
return $response->withRedirect($this->AppContainer->get('UrlManager')->ConstructUrl('/login?invalid=true'));
}
return $response->withRedirect($this->AppContainer->get('UrlManager')->ConstructUrl('/'));
}
else
{
return $response->withRedirect($this->AppContainer->get('UrlManager')->ConstructUrl('/login?invalid=true'));
}
}
public function __construct(\DI\Container $container, string $sessionCookieName)
{
parent::__construct($container);
$this->SessionCookieName = $sessionCookieName;
}
}