Create an insecure bank application
This commit is contained in:
46
webroot/lib/Model/User.php
Normal file
46
webroot/lib/Model/User.php
Normal file
@ -0,0 +1,46 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Model;
|
||||
|
||||
use Controller\Sql;
|
||||
|
||||
class User
|
||||
{
|
||||
public function __construct(
|
||||
public int $id,
|
||||
public string $name,
|
||||
public ?string $pwHash,
|
||||
public bool $isAdmin,
|
||||
) {
|
||||
}
|
||||
|
||||
public static function create(string $name, string $pwHash): ?self
|
||||
{
|
||||
$sql = Sql::connection();
|
||||
$stmt = $sql->prepare('INSERT INTO user (name, password) VALUES (?, ?)');
|
||||
try {
|
||||
$stmt->execute([$name, $pwHash]);
|
||||
} catch (\PDOException $e) {
|
||||
if ($e->getCode() == 23000) {
|
||||
// duplicate entry, so the username is already in use
|
||||
return null;
|
||||
} else {
|
||||
// unknown error, throw out
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
return new self((int) $sql->lastInsertId(), $name, $pwHash, false);
|
||||
}
|
||||
|
||||
public static function byName(string $name): ?self
|
||||
{
|
||||
$sql = Sql::connection();
|
||||
$stmt = $sql->prepare('SELECT id, name, password, admin FROM user WHERE name = ?');
|
||||
$stmt->execute([$name]);
|
||||
if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
|
||||
return new self($row['id'], $row['name'], $row['password'], (bool) $row['admin']);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user