webcron/src/Repository/User.php

70 lines
2.1 KiB
PHP
Raw Normal View History

2021-04-08 12:54:49 +02:00
<?php
namespace JeroenED\Webcron\Repository;
use Doctrine\DBAL\Connection;
2021-05-27 11:46:30 +02:00
use JeroenED\Framework\Repository;
2021-04-08 12:54:49 +02:00
2021-05-27 11:46:30 +02:00
class User extends Repository
2021-04-08 12:54:49 +02:00
{
2021-04-09 15:14:35 +02:00
/**
* @param string $user
* @param string $password
* @param bool $autologin
* @return int|bool
* @throws \Doctrine\DBAL\Driver\Exception
* @throws \Doctrine\DBAL\Exception
*/
public function checkAuthentication(string $user, string $password, bool $autologin = false): int|bool
2021-04-08 12:54:49 +02:00
{
$userSql = "SELECT * from user WHERE email = :user";
$userStmt = $this->dbcon->prepare($userSql);
$userRslt = $userStmt->executeQuery([':user' => $user]);
2021-04-08 12:54:49 +02:00
if($user = $userRslt->fetchAssociative()) {
2021-04-09 15:14:35 +02:00
if($autologin) $password = $this->getPassFromAutologinToken($password);
$password = hash($_ENV['HASHING_METHOD'], $password);
if(password_verify($password, $user['password'])) {
return $user['id'];
2021-04-08 12:54:49 +02:00
}
}
return false;
}
2021-04-09 15:14:35 +02:00
2021-04-13 14:44:58 +02:00
public function createAutologinToken($password): string
{
2021-04-09 15:14:35 +02:00
$time = time();
2021-04-15 13:02:21 +02:00
$password = $password . substr($time, -7) ;
2021-04-13 14:44:58 +02:00
$encrypted = Secret::encrypt($password);
return base64_encode(json_encode(['time' => $time, 'password' => base64_encode($encrypted)]));
2021-04-09 15:14:35 +02:00
}
public function getPassFromAutologinToken($token) {
$extracted = json_decode(base64_decode($token), true);
$encrypted = base64_decode($extracted['password']);
2021-04-13 14:44:58 +02:00
$decrypted = Secret::decrypt($encrypted);
2021-04-09 15:14:35 +02:00
return (
(($extracted['time'] + $_ENV['COOKIE_LIFETIME']) > time()) &&
2021-04-13 14:44:58 +02:00
substr($extracted['time'], -7) == substr($decrypted, -7)
2021-04-09 15:14:35 +02:00
)
2021-04-13 14:44:58 +02:00
? substr($decrypted, 0, -7) : null;
2021-04-09 15:14:35 +02:00
}
public function getMailAddresses() {
$emailSql = "SELECT email FROM user WHERE sendmail = 1";
$emailStmt = $this->dbcon->prepare($emailSql);
$emailRslt = $emailStmt->executeQuery();
$return = [];
foreach($emailRslt->fetchAllAssociative() as $email) {
$return[] = $email['email'];
}
return $return;
}
2021-04-08 12:54:49 +02:00
}