3 Commits

Author SHA1 Message Date
7b21b86550 Merge branch 'main' into security-models 2024-04-26 20:49:34 -04:00
ce83b2a389 Add Atom support (#17) 2024-04-25 21:19:29 -04:00
cab26db255 First cut of log on page (#9)
- Add session support
- Refactor security handling to use db connection
- Fix db path issue
2024-04-15 23:25:58 -04:00
12 changed files with 385 additions and 184 deletions

View File

@@ -9,7 +9,7 @@ class Data {
* @return SQLite3 A new connection to the database * @return SQLite3 A new connection to the database
*/ */
public static function getConnection(): SQLite3 { public static function getConnection(): SQLite3 {
$db = new SQLite3('../data/' . DATABASE_NAME); $db = new SQLite3(implode(DIRECTORY_SEPARATOR, [__DIR__, '..', 'data', DATABASE_NAME]));
$db->exec('PRAGMA foreign_keys = ON;'); $db->exec('PRAGMA foreign_keys = ON;');
return $db; return $db;
} }
@@ -65,47 +65,6 @@ class Data {
$db->close(); $db->close();
} }
/**
* Find a user by their ID
*
* @param string $email The e-mail address of the user to retrieve
* @return array|null The user information, or null if the user is not found
*/
public static function findUserByEmail(string $email): ?array {
$db = self::getConnection();
try {
$query = $db->prepare('SELECT * FROM frc_user WHERE email = :email');
$query->bindValue(':email', $email);
$result = $query->execute();
if ($result) {
$user = $result->fetchArray(SQLITE3_ASSOC);
if ($user) return $user;
return null;
}
return null;
} finally {
$db->close();
}
}
/**
* Add a user
*
* @param string $email The e-mail address for the user
* @param string $password The user's password
*/
public static function addUser(string $email, string $password): void {
$db = self::getConnection();
try {
$query = $db->prepare('INSERT INTO frc_user (email, password) VALUES (:email, :password)');
$query->bindValue(':email', $email);
$query->bindValue(':password', password_hash($password, PASSWORD_DEFAULT));
$query->execute();
} finally {
$db->close();
}
}
/** /**
* Parse/format a date/time from a string * Parse/format a date/time from a string
* *
@@ -132,7 +91,7 @@ class Data {
try { try {
$query = $db->prepare('SELECT * FROM feed WHERE id = :id AND user_id = :user'); $query = $db->prepare('SELECT * FROM feed WHERE id = :id AND user_id = :user');
$query->bindValue(':id', $feedId); $query->bindValue(':id', $feedId);
$query->bindValue(':user', $_REQUEST[Key::USER_ID]); $query->bindValue(':user', $_SESSION[Key::USER_ID]);
$result = $query->execute(); $result = $query->execute();
return $result ? $result->fetchArray(SQLITE3_ASSOC) : false; return $result ? $result->fetchArray(SQLITE3_ASSOC) : false;
} finally { } finally {

View File

@@ -1,15 +1,55 @@
<?php <?php
/**
* Information for a feed item
*/
class FeedItem {
/** @var string The title of the feed item */
public string $title = '';
/** @var string The unique ID for the feed item */
public string $guid = '';
/** @var string The link to the original content */
public string $link = '';
/** @var string When this item was published */
public string $publishedOn = '';
/** @var ?string When this item was last updated */
public ?string $updatedOn = null;
/** @var string The content for the item */
public string $content = '';
}
/** /**
* Feed retrieval, parsing, and manipulation * Feed retrieval, parsing, and manipulation
*/ */
class Feed { class Feed {
/** @var string The URL for the feed */
public string $url = '';
/** @var string The title of the feed */
public string $title = '';
/** @var ?string When the feed was last updated */
public ?string $updatedOn = null;
/** @var FeedItem[] The items contained in the feed */
public array $items = [];
/** @var string The XML namespace for Atom feeds */ /** @var string The XML namespace for Atom feeds */
public const string ATOM_NS = 'http://www.w3.org/2005/Atom'; public const string ATOM_NS = 'http://www.w3.org/2005/Atom';
/** @var string The XML namespace for the `<content:encoded>` tag that allows HTML content in a feed */ /** @var string The XML namespace for the `<content:encoded>` tag that allows HTML content in a feed */
public const string CONTENT_NS = 'http://purl.org/rss/1.0/modules/content/'; public const string CONTENT_NS = 'http://purl.org/rss/1.0/modules/content/';
/** @var string The XML namespace for XHTML */
public const string XHTML_NS = 'http://www.w3.org/1999/xhtml';
/** /**
* When parsing XML into a DOMDocument, errors are presented as warnings; this creates an exception for them * When parsing XML into a DOMDocument, errors are presented as warnings; this creates an exception for them
* *
@@ -45,24 +85,135 @@ class Feed {
} }
/** /**
* Get the value of a child element by its tag name * Get the value of a child element by its tag name for an RSS feed
* *
* @param DOMElement $element The parent element * @param DOMElement $element The parent element
* @param string $tagName The name of the tag whose value should be obtained * @param string $tagName The name of the tag whose value should be obtained
* @return string The value of the element (or "[element] not found" if that element does not exist) * @return string The value of the element (or "[element] not found" if that element does not exist)
*/ */
private static function eltValue(DOMElement $element, string $tagName): string { private static function rssValue(DOMElement $element, string $tagName): string {
$tags = $element->getElementsByTagName($tagName); $tags = $element->getElementsByTagName($tagName);
return $tags->length == 0 ? "$tagName not found" : $tags->item(0)->textContent; return $tags->length == 0 ? "$tagName not found" : $tags->item(0)->textContent;
} }
/**
* Extract items from an RSS feed
*
* @param DOMDocument $xml The XML received from the feed
* @param string $url The actual URL for the feed
* @return array|Feed[]|string[] ['ok' => feed] if successful, ['error' => message] if not
*/
private static function fromRSS(DOMDocument $xml, string $url): array {
$channel = $xml->getElementsByTagName('channel')->item(0);
if (!($channel instanceof DOMElement)) {
return ['error' => "Channel element not found ($channel->nodeType)"];
}
$feed = new Feed();
$feed->title = self::rssValue($channel, 'title');
$feed->url = $url;
// The Atom namespace provides a lastBuildDate, which contains the last time an item in the feed was updated; if
// that is not present, use the pubDate element instead
$feed->updatedOn = self::rssValue($channel, 'lastBuildDate');
if ($feed->updatedOn == 'lastBuildDate not found') {
$feed->updatedOn = self::rssValue($channel, 'pubDate');
if ($feed->updatedOn == 'pubDate not found') $feed->updatedOn = null;
}
$feed->updatedOn = Data::formatDate($feed->updatedOn);
foreach ($channel->getElementsByTagName('item') as $xmlItem) {
$itemGuid = self::rssValue($xmlItem, 'guid');
$updNodes = $xmlItem->getElementsByTagNameNS(Feed::ATOM_NS, 'updated');
$encNodes = $xmlItem->getElementsByTagNameNS(Feed::CONTENT_NS, 'encoded');
$item = new FeedItem();
$item->guid = $itemGuid == 'guid not found' ? self::rssValue($xmlItem, 'link') : $itemGuid;
$item->title = self::rssValue($xmlItem, 'title');
$item->link = self::rssValue($xmlItem, 'link');
$item->publishedOn = Data::formatDate(self::rssValue($xmlItem, 'pubDate'));
$item->updatedOn = Data::formatDate($updNodes->length > 0 ? $updNodes->item(0)->textContent : null);
$item->content = $encNodes->length > 0
? $encNodes->item(0)->textContent
: self::rssValue($xmlItem, 'description');
$feed->items[] = $item;
}
return ['ok' => $feed];
}
/**
* Get the value of a child element by its tag name for an Atom feed
*
* (Atom feeds can have type attributes on nearly any value. For our purposes, types "text" and "html" will work as
* regular string values; for "xhtml", though, we will need to get the `<div>` and extract its contents instead.)
*
* @param DOMElement $element The parent element
* @param string $tagName The name of the tag whose value should be obtained
* @return string The value of the element (or "[element] not found" if that element does not exist)
*/
private static function atomValue(DOMElement $element, string $tagName): string {
$tags = $element->getElementsByTagName($tagName);
if ($tags->length == 0) return "$tagName not found";
$tag = $tags->item(0);
if (!($tag instanceof DOMElement)) return $tag->textContent;
if ($tag->hasAttributes() && $tag->attributes->getNamedItem('type') == 'xhtml') {
$div = $tag->getElementsByTagNameNS(Feed::XHTML_NS, 'div');
if ($div->length == 0) return "-- invalid XHTML content --";
return $div->item(0)->textContent;
}
return $tag->textContent;
}
/**
* Extract items from an Atom feed
*
* @param DOMDocument $xml The XML received from the feed
* @param string $url The actual URL for the feed
* @return array|Feed[] ['ok' => feed]
*/
private static function fromAtom(DOMDocument $xml, string $url): array {
/** @var DOMElement $root */
$root = $xml->getElementsByTagNameNS(self::ATOM_NS, 'feed')->item(0);
$feed = new Feed();
$feed->title = self::atomValue($root, 'title');
$feed->url = $url;
$feed->updatedOn = self::atomValue($root, 'updated');
if ($feed->updatedOn == 'pubDate not found') $feed->updatedOn = null;
$feed->updatedOn = Data::formatDate($feed->updatedOn);
foreach ($root->getElementsByTagName('entry') as $xmlItem) {
$guid = self::atomValue($xmlItem, 'id');
$link = '';
foreach ($xmlItem->getElementsByTagName('link') as $linkElt) {
if ($linkElt->hasAttributes()) {
$relAttr = $linkElt->attributes->getNamedItem('rel');
if ($relAttr && $relAttr->value == 'alternate') {
$link = $linkElt->attributes->getNamedItem('href')->value;
break;
}
}
}
if ($link == '' && str_starts_with($guid, 'http')) $link = $guid;
$item = new FeedItem();
$item->guid = $guid;
$item->title = self::atomValue($xmlItem, 'title');
$item->link = $link;
$item->publishedOn = Data::formatDate(self::atomValue($xmlItem, 'published'));
$item->updatedOn = Data::formatDate(self::atomValue($xmlItem, 'updated'));
$item->content = self::atomValue($xmlItem, 'content');
$feed->items[] = $item;
}
return ['ok' => $feed];
}
/** /**
* Retrieve the feed * Retrieve the feed
* *
* @param string $url * @param string $url The URL of the feed to retrieve
* @return array|DOMDocument[]|string[]|DOMElement[] * @return array|Feed[]|string[] ['ok' => feed] if successful, ['error' => message] if not
* ['ok' => feedXml, 'url' => actualUrl, 'channel' => channel, 'updated' => updatedDate] if successful,
* ['error' => message] if not
*/ */
public static function retrieveFeed(string $url): array { public static function retrieveFeed(string $url): array {
$feedReq = curl_init($url); $feedReq = curl_init($url);
@@ -83,26 +234,9 @@ class Feed {
if (array_key_exists('error', $parsed)) { if (array_key_exists('error', $parsed)) {
$result['error'] = $parsed['error']; $result['error'] = $parsed['error'];
} else { } else {
$result['ok'] = $parsed['ok']; $extract = $parsed['ok']->getElementsByTagNameNS(self::ATOM_NS, 'feed')->length > 0
$result['url'] = curl_getinfo($feedReq, CURLINFO_EFFECTIVE_URL); ? self::fromAtom(...) : self::fromRSS(...);
$result = $extract($parsed['ok'], curl_getinfo($feedReq, CURLINFO_EFFECTIVE_URL));
$channel = $result['ok']->getElementsByTagName('channel')->item(0);
if ($channel instanceof DOMElement) {
$result['channel'] = $channel;
} else {
return ['error' => "Channel element not found ($channel->nodeType)"];
}
// In Atom feeds, lastBuildDate contains the last time an item in the feed was updated; if that is not
// present, use the pubDate element instead
$updated = self::eltValue($channel, 'lastBuildDate');
if ($updated == 'lastBuildDate not found') {
$updated = self::eltValue($channel, 'pubDate');
if ($updated == 'pubDate not found') $updated = null;
}
$result['updated'] = Data::formatDate($updated);
return $result;
} }
} else { } else {
$result['error'] = "Prospective feed URL $url returned HTTP Code $code: $feedContent"; $result['error'] = "Prospective feed URL $url returned HTTP Code $code: $feedContent";
@@ -112,35 +246,14 @@ class Feed {
return $result; return $result;
} }
/**
* Extract the fields we need to keep from the feed
*
* @param DOMElement $item The item from the feed
* @return array The fields for the item as an associative array
*/
private static function itemFields(DOMElement $item): array {
$itemGuid = self::eltValue($item, 'guid');
$updNodes = $item->getElementsByTagNameNS(self::ATOM_NS, 'updated');
$encNodes = $item->getElementsByTagNameNS(self::CONTENT_NS, 'encoded');
return [
'guid' => $itemGuid == 'guid not found' ? self::eltValue($item, 'link') : $itemGuid,
'title' => self::eltValue($item, 'title'),
'link' => self::eltValue($item, 'link'),
'published' => Data::formatDate(self::eltValue($item, 'pubDate')),
'updated' => Data::formatDate($updNodes->length > 0 ? $updNodes->item(0)->textContent : null),
'content' => $encNodes->length > 0 ? $encNodes->item(0)->textContent
: self::eltValue($item, 'description')
];
}
/** /**
* Update a feed item * Update a feed item
* *
* @param int $itemId The ID of the item to be updated * @param int $itemId The ID of the item to be updated
* @param array $item The fields from the updated item * @param FeedItem $item The item to be updated
* @param SQLite3 $db A database connection to use for the update * @param SQLite3 $db A database connection to use for the update
*/ */
private static function updateItem(int $itemId, array $item, SQLite3 $db): void { private static function updateItem(int $itemId, FeedItem $item, SQLite3 $db): void {
$query = $db->prepare(<<<'SQL' $query = $db->prepare(<<<'SQL'
UPDATE item UPDATE item
SET title = :title, SET title = :title,
@@ -150,10 +263,10 @@ class Feed {
is_read = 0 is_read = 0
WHERE id = :id WHERE id = :id
SQL); SQL);
$query->bindValue(':title', $item['title']); $query->bindValue(':title', $item->title);
$query->bindValue(':published', $item['published']); $query->bindValue(':published', $item->publishedOn);
$query->bindValue(':updated', $item['updated']); $query->bindValue(':updated', $item->updatedOn);
$query->bindValue(':content', $item['content']); $query->bindValue(':content', $item->content);
$query->bindValue(':id', $itemId); $query->bindValue(':id', $itemId);
$query->execute(); $query->execute();
} }
@@ -162,10 +275,10 @@ class Feed {
* Add a feed item * Add a feed item
* *
* @param int $feedId The ID of the feed to which the item should be added * @param int $feedId The ID of the feed to which the item should be added
* @param array $item The fields for the item * @param FeedItem $item The item to be added
* @param SQLite3 $db A database connection to use for the addition * @param SQLite3 $db A database connection to use for the addition
*/ */
private static function addItem(int $feedId, array $item, SQLite3 $db): void { private static function addItem(int $feedId, FeedItem $item, SQLite3 $db): void {
$query = $db->prepare(<<<'SQL' $query = $db->prepare(<<<'SQL'
INSERT INTO item ( INSERT INTO item (
feed_id, item_guid, item_link, title, published_on, updated_on, content feed_id, item_guid, item_link, title, published_on, updated_on, content
@@ -174,12 +287,12 @@ class Feed {
) )
SQL); SQL);
$query->bindValue(':feed', $feedId); $query->bindValue(':feed', $feedId);
$query->bindValue(':guid', $item['guid']); $query->bindValue(':guid', $item->guid);
$query->bindValue(':link', $item['link']); $query->bindValue(':link', $item->link);
$query->bindValue(':title', $item['title']); $query->bindValue(':title', $item->title);
$query->bindValue(':published', $item['published']); $query->bindValue(':published', $item->publishedOn);
$query->bindValue(':updated', $item['updated']); $query->bindValue(':updated', $item->updatedOn);
$query->bindValue(':content', $item['content']); $query->bindValue(':content', $item->content);
$query->execute(); $query->execute();
} }
@@ -187,23 +300,22 @@ class Feed {
* Update a feed's items * Update a feed's items
* *
* @param int $feedId The ID of the feed to which these items belong * @param int $feedId The ID of the feed to which these items belong
* @param DOMElement $channel The RSS feed items * @param Feed $feed The extracted Atom or RSS feed items
* @return array ['ok' => true] if successful, ['error' => message] if not * @return array ['ok' => true] if successful, ['error' => message] if not
*/ */
public static function updateItems(int $feedId, DOMElement $channel, SQLite3 $db): array { public static function updateItems(int $feedId, Feed $feed, SQLite3 $db): array {
try { try {
foreach ($channel->getElementsByTagName('item') as $rawItem) { foreach ($feed->items as $item) {
$item = self::itemFields($rawItem);
$existsQuery = $db->prepare( $existsQuery = $db->prepare(
'SELECT id, published_on, updated_on FROM item WHERE feed_id = :feed AND item_guid = :guid'); 'SELECT id, published_on, updated_on FROM item WHERE feed_id = :feed AND item_guid = :guid');
$existsQuery->bindValue(':feed', $feedId); $existsQuery->bindValue(':feed', $feedId);
$existsQuery->bindValue(':guid', $item['guid']); $existsQuery->bindValue(':guid', $item->guid);
$exists = $existsQuery->execute(); $exists = $existsQuery->execute();
if ($exists) { if ($exists) {
$existing = $exists->fetchArray(SQLITE3_ASSOC); $existing = $exists->fetchArray(SQLITE3_ASSOC);
if ($existing) { if ($existing) {
if ( $existing['published_on'] != $item['published'] if ( $existing['published_on'] != $item->publishedOn
|| $existing['updated_on'] ?? '' != $item['updated'] ?? '') { || ($existing['updated_on'] ?? '') != ($item->updatedOn ?? '')) {
self::updateItem($existing['id'], $item, $db); self::updateItem($existing['id'], $item, $db);
} }
} else { } else {
@@ -229,18 +341,19 @@ class Feed {
private static function refreshFeed(string $url, SQLite3 $db): array { private static function refreshFeed(string $url, SQLite3 $db): array {
$feedQuery = $db->prepare('SELECT id FROM feed WHERE url = :url AND user_id = :user'); $feedQuery = $db->prepare('SELECT id FROM feed WHERE url = :url AND user_id = :user');
$feedQuery->bindValue(':url', $url); $feedQuery->bindValue(':url', $url);
$feedQuery->bindValue(':user', $_REQUEST[Key::USER_ID]); $feedQuery->bindValue(':user', $_SESSION[Key::USER_ID]);
$feedResult = $feedQuery->execute(); $feedResult = $feedQuery->execute();
$feedId = $feedResult ? $feedResult->fetchArray(SQLITE3_NUM)[0] : -1; $feedId = $feedResult ? $feedResult->fetchArray(SQLITE3_NUM)[0] : -1;
if ($feedId < 0) return ['error' => "No feed for URL $url found"]; if ($feedId < 0) return ['error' => "No feed for URL $url found"];
$feed = self::retrieveFeed($url); $feedExtract = self::retrieveFeed($url);
if (array_key_exists('error', $feed)) return $feed; if (array_key_exists('error', $feedExtract)) return $feedExtract;
$itemUpdate = self::updateItems($feedId, $feed['channel'], $db); $feed = $feedExtract['ok'];
$itemUpdate = self::updateItems($feedId, $feed, $db);
if (array_key_exists('error', $itemUpdate)) return $itemUpdate; if (array_key_exists('error', $itemUpdate)) return $itemUpdate;
$urlUpdate = $url == $feed['url'] ? '' : ', url = :url'; $urlUpdate = $url == $feed->url ? '' : ', url = :url';
$feedUpdate = $db->prepare(<<<SQL $feedUpdate = $db->prepare(<<<SQL
UPDATE feed UPDATE feed
SET title = :title, SET title = :title,
@@ -249,11 +362,11 @@ class Feed {
$urlUpdate $urlUpdate
WHERE id = :id WHERE id = :id
SQL); SQL);
$feedUpdate->bindValue(':title', self::eltValue($feed['channel'], 'title')); $feedUpdate->bindValue(':title', $feed->title);
$feedUpdate->bindValue(':updated', $feed['updated']); $feedUpdate->bindValue(':updated', $feed->updatedOn);
$feedUpdate->bindValue(':checked', Data::formatDate('now')); $feedUpdate->bindValue(':checked', Data::formatDate('now'));
$feedUpdate->bindValue(':id', $feedId); $feedUpdate->bindValue(':id', $feedId);
if ($urlUpdate != '') $feedUpdate->bindValue(':url', $feed['url']); if ($urlUpdate != '') $feedUpdate->bindValue(':url', $feed->url);
$feedUpdate->execute(); $feedUpdate->execute();
return ['ok' => true]; return ['ok' => true];
@@ -266,24 +379,25 @@ class Feed {
* @return array ['ok' => feedId] if successful, ['error' => message] if not * @return array ['ok' => feedId] if successful, ['error' => message] if not
*/ */
public static function add(string $url, SQLite3 $db): array { public static function add(string $url, SQLite3 $db): array {
$feed = self::retrieveFeed($url); $feedExtract = self::retrieveFeed($url);
if (array_key_exists('error', $feed)) return $feed; if (array_key_exists('error', $feedExtract)) return $feedExtract;
$feed = $feedExtract['ok'];
$query = $db->prepare(<<<'SQL' $query = $db->prepare(<<<'SQL'
INSERT INTO feed (user_id, url, title, updated_on, checked_on) INSERT INTO feed (user_id, url, title, updated_on, checked_on)
VALUES (:user, :url, :title, :updated, :checked) VALUES (:user, :url, :title, :updated, :checked)
SQL); SQL);
$query->bindValue(':user', $_REQUEST[Key::USER_ID]); $query->bindValue(':user', $_SESSION[Key::USER_ID]);
$query->bindValue(':url', $feed['url']); $query->bindValue(':url', $feed->url);
$query->bindValue(':title', self::eltValue($feed['channel'], 'title')); $query->bindValue(':title', $feed->title);
$query->bindValue(':updated', $feed['updated']); $query->bindValue(':updated', $feed->updatedOn);
$query->bindValue(':checked', Data::formatDate('now')); $query->bindValue(':checked', Data::formatDate('now'));
$result = $query->execute(); $result = $query->execute();
$feedId = $result ? $db->lastInsertRowID() : -1; $feedId = $result ? $db->lastInsertRowID() : -1;
if ($feedId < 0) return ['error' => $db->lastErrorMsg()]; if ($feedId < 0) return ['error' => $db->lastErrorMsg()];
$result = self::updateItems($feedId, $feed['channel'], $db); $result = self::updateItems($feedId, $feed, $db);
if (array_key_exists('error', $result)) return $result; if (array_key_exists('error', $result)) return $result;
return ['ok' => $feedId]; return ['ok' => $feedId];
@@ -294,25 +408,28 @@ class Feed {
* *
* @param array $existing The existing RSS feed * @param array $existing The existing RSS feed
* @param string $url The URL with which the existing feed should be modified * @param string $url The URL with which the existing feed should be modified
* @param SQLite3 $db The database connection on which to execute the update
* @return bool[]|string[] [ 'ok' => true ] if successful, [ 'error' => message ] if not * @return bool[]|string[] [ 'ok' => true ] if successful, [ 'error' => message ] if not
*/ */
public static function update(array $existing, string $url, SQLite3 $db): array { public static function update(array $existing, string $url, SQLite3 $db): array {
$query = $db->prepare('UPDATE feed SET url = :url WHERE id = :id AND user_id = :user'); $query = $db->prepare('UPDATE feed SET url = :url WHERE id = :id AND user_id = :user');
$query->bindValue(':url', $url); $query->bindValue(':url', $url);
$query->bindValue(':id', $existing['id']); $query->bindValue(':id', $existing['id']);
$query->bindValue(':user', $_REQUEST[Key::USER_ID]); $query->bindValue(':user', $_SESSION[Key::USER_ID]);
$query->execute(); $query->execute();
return self::refreshFeed($url, $db); return self::refreshFeed($url, $db);
} }
/** /**
* @param SQLite3 $db * Refresh all feeds
*
* @param SQLite3 $db The database connection to use for refreshing feeds
* @return array|true[] ['ok => true] if successful, ['error' => message] if not (may have multiple error lines) * @return array|true[] ['ok => true] if successful, ['error' => message] if not (may have multiple error lines)
*/ */
public static function refreshAll(SQLite3 $db): array { public static function refreshAll(SQLite3 $db): array {
$query = $db->prepare('SELECT url FROM feed WHERE user_id = :user'); $query = $db->prepare('SELECT url FROM feed WHERE user_id = :user');
$query->bindValue(':user', $_REQUEST[Key::USER_ID]); $query->bindValue(':user', $_SESSION[Key::USER_ID]);
$result = $query->execute(); $result = $query->execute();
$url = $result ? $result->fetchArray(SQLITE3_NUM) : false; $url = $result ? $result->fetchArray(SQLITE3_NUM) : false;
if ($url) { if ($url) {

View File

@@ -2,10 +2,10 @@
class Key { class Key {
/** @var string The $_REQUEST key for teh current user's e-mail address */ /** @var string The $_SESSION key for the current user's e-mail address */
public const string USER_EMAIL = 'FRC_USER_EMAIL'; public const string USER_EMAIL = 'FRC_USER_EMAIL';
/** @var string The $_REQUEST key for the current user's ID */ /** @var string The $_SESSION key for the current user's ID */
public const string USER_ID = 'FRC_USER_ID'; public const string USER_ID = 'FRC_USER_ID';
/** @var string The $_REQUEST key for the array of user messages to display */ /** @var string The $_REQUEST key for the array of user messages to display */

View File

@@ -14,38 +14,108 @@ class Security {
/** @var int Require users to provide e-mail address and password */ /** @var int Require users to provide e-mail address and password */
public const int MULTI_USER = 2; public const int MULTI_USER = 2;
/** @var string The e-mail address for the single user */
public const string SINGLE_USER_EMAIL = 'solouser@example.com';
/** @var string The password for the single user with no password */
private const string SINGLE_USER_PASSWORD = 'no-password-required';
/** /**
* Verify that user is logged on * Find a user by their ID
* @param bool $redirectIfAnonymous Whether to redirect the request if there is no user logged on *
* @param string $email The e-mail address of the user to retrieve
* @param SQLite3 $db The data connection to use to retrieve the user
* @return array|false The user information, or null if the user is not found
*/ */
public static function verifyUser(bool $redirectIfAnonymous = true): void { private static function findUserByEmail(string $email, SQLite3 $db): array|false {
switch (SECURITY_MODEL) { $query = $db->prepare('SELECT * FROM frc_user WHERE email = :email');
case self::SINGLE_USER: $query->bindValue(':email', $email);
$user = self::retrieveSingleUser(); $result = $query->execute();
break; return $result ? $result->fetchArray(SQLITE3_ASSOC) : false;
case self::SINGLE_USER_WITH_PASSWORD:
die('Single User w/ Password has not yet been implemented');
case self::MULTI_USER:
die('Multi-User Mode has not yet been implemented');
default:
die('Unrecognized security model (' . SECURITY_MODEL . ')');
}
if (!$user && $redirectIfAnonymous) {
header('/logon?returnTo=' . $_SERVER['REQUEST_URI'], true, HTTP_REDIRECT_TEMP);
die();
}
$_REQUEST[Key::USER_ID] = $user['id'];
$_REQUEST[Key::USER_EMAIL] = $user['email'];
} }
/** /**
* Retrieve the single user * Add a user
* @return array The user information for the single user *
* @param string $email The e-mail address for the user
* @param string $password The user's password
* @param SQLite3 $db The data connection to use to add the user
*/ */
private static function retrieveSingleUser(): array { public static function addUser(string $email, string $password, SQLite3 $db): void {
$user = Data::findUserByEmail('solouser@example.com'); $query = $db->prepare('INSERT INTO frc_user (email, password) VALUES (:email, :password)');
if ($user) return $user; $query->bindValue(':email', $email);
Data::addUser('solouser@example.com', 'no-password-required'); $query->bindValue(':password', password_hash($password, PASSWORD_DEFAULT));
return Data::findUserByEmail('solouser@example.com'); $query->execute();
}
/**
* Verify a user's password
*
* @param array $user The user information retrieved from the database
* @param string $password The password provided by the user
* @param string|null $returnTo The URL to which the user should be redirected
* @param SQLite3 $db The database connection to use to verify the user's credentials
*/
private static function verifyPassword(array $user, string $password, ?string $returnTo, SQLite3 $db): void {
if (password_verify($password, $user['password'])) {
if (password_needs_rehash($user['password'], PASSWORD_DEFAULT)) {
$rehash = $db->prepare('UPDATE frc_user SET password = :hash WHERE id = :id');
$rehash->bindValue(':hash', password_hash($password, PASSWORD_DEFAULT));
$rehash->bindValue(':id', $user['id']);
$rehash->execute();
}
$_SESSION[Key::USER_ID] = $user['id'];
$_SESSION[Key::USER_EMAIL] = $user['email'];
frc_redirect($returnTo ?? '/');
}
}
/**
* Log on a user with e-mail address and password
*
* @param string $email The e-mail address for the user
* @param string $password The password provided by the user
* @param string|null $returnTo The URL to which the user should be redirected
* @param SQLite3 $db The database connection to use to verify the user's credentials
*/
public static function logOnUser(string $email, string $password, ?string $returnTo, SQLite3 $db): void {
$user = self::findUserByEmail($email, $db);
if ($user) self::verifyPassword($user, $password, $returnTo, $db);
add_error('Invalid credentials; log on unsuccessful');
}
/**
* Log on the single user
*
* @param SQLite3 $db The data connection to use to retrieve the user
*/
private static function logOnSingleUser(SQLite3 $db): void {
$user = self::findUserByEmail(self::SINGLE_USER_EMAIL, $db);
if (!$user) {
self::addUser(self::SINGLE_USER_EMAIL, self::SINGLE_USER_PASSWORD, $db);
$user = self::findUserByEmail(self::SINGLE_USER_EMAIL, $db);
}
self::verifyPassword($user, self::SINGLE_USER_PASSWORD, $_GET['returnTo'], $db);
}
/**
* Verify that user is logged on
*
* @param SQLite3 $db The data connection to use if required
* @param bool $redirectIfAnonymous Whether to redirect the request if there is no user logged on
*/
public static function verifyUser(SQLite3 $db, bool $redirectIfAnonymous = true): void {
if (array_key_exists(Key::USER_ID, $_SESSION)) return;
if (SECURITY_MODEL == self::SINGLE_USER) self::logOnSingleUser($db);
if (SECURITY_MODEL != self::SINGLE_USER_WITH_PASSWORD && SECURITY_MODEL != self::MULTI_USER) {
die('Unrecognized security model (' . SECURITY_MODEL . ')');
}
if ($redirectIfAnonymous) {
header("Location: /user/log-on?returnTo={$_SERVER['REQUEST_URI']}", true, 307);
die();
}
} }
} }

View File

@@ -57,7 +57,10 @@ article {
padding: .5rem; padding: .5rem;
} }
} }
input[type=url], input[type=text] { input[type=url],
input[type=text],
input[type=email],
input[type=password] {
width: 50%; width: 50%;
font-size: 1rem; font-size: 1rem;
padding: .25rem; padding: .25rem;

View File

@@ -7,10 +7,10 @@
include '../start.php'; include '../start.php';
Security::verifyUser();
$feedId = array_key_exists('id', $_GET) ? $_GET['id'] : '';
$db = Data::getConnection(); $db = Data::getConnection();
Security::verifyUser($db);
$feedId = $_GET['id'] ?? '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') { if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$isNew = $_POST['id'] == 'new'; $isNew = $_POST['id'] == 'new';
@@ -31,7 +31,7 @@ if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($feedId == 'new') { if ($feedId == 'new') {
$title = 'Add RSS Feed'; $title = 'Add RSS Feed';
$feed = [ 'id' => $_GET['id'], 'url' => '' ]; $feed = [ 'id' => $_GET['id'], 'url' => ''];
} else { } else {
$title = 'Edit RSS Feed'; $title = 'Edit RSS Feed';
if ($feedId == 'error') { if ($feedId == 'error') {

View File

@@ -7,9 +7,8 @@
include '../start.php'; include '../start.php';
Security::verifyUser();
$db = Data::getConnection(); $db = Data::getConnection();
Security::verifyUser($db);
if (array_key_exists('refresh', $_GET)) { if (array_key_exists('refresh', $_GET)) {
$refreshResult = Feed::refreshAll($db); $refreshResult = Feed::refreshAll($db);
@@ -36,7 +35,7 @@ page_head('Welcome'); ?>
if ($item) { if ($item) {
while ($item) { ?> while ($item) { ?>
<p><a href=/item?id=<?=$item['id']?>><?=$item['item_title']?></a><br> <p><a href=/item?id=<?=$item['id']?>><?=$item['item_title']?></a><br>
<?=$item['feed_title']?><br><small><em><?=date_time($item['as_of'])?></em></small><?php <?=htmlentities($item['feed_title'])?><br><small><em><?=date_time($item['as_of'])?></em></small><?php
$item = $result->fetchArray(SQLITE3_ASSOC); $item = $result->fetchArray(SQLITE3_ASSOC);
} }
} else { ?> } else { ?>

View File

@@ -8,9 +8,8 @@
include '../start.php'; include '../start.php';
Security::verifyUser();
$db = Data::getConnection(); $db = Data::getConnection();
Security::verifyUser($db);
if ($_SERVER['REQUEST_METHOD'] == 'POST') { if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// "Keep as New" button sends a POST request to reset the is_read flag before going back to the list of unread items // "Keep as New" button sends a POST request to reset the is_read flag before going back to the list of unread items
@@ -20,7 +19,7 @@ if ($_SERVER['REQUEST_METHOD'] == 'POST') {
WHERE item.id = :id AND feed.user_id = :user WHERE item.id = :id AND feed.user_id = :user
SQL); SQL);
$isValidQuery->bindValue(':id', $_POST['id']); $isValidQuery->bindValue(':id', $_POST['id']);
$isValidQuery->bindValue(':user', $_REQUEST[Key::USER_ID]); $isValidQuery->bindValue(':user', $_SESSION[Key::USER_ID]);
$isValidResult = $isValidQuery->execute(); $isValidResult = $isValidQuery->execute();
if ($isValidResult && $isValidResult->fetchArray(SQLITE3_NUM)[0] == 1) { if ($isValidResult && $isValidResult->fetchArray(SQLITE3_NUM)[0] == 1) {
$keepUnread = $db->prepare('UPDATE item SET is_read = 0 WHERE id = :id'); $keepUnread = $db->prepare('UPDATE item SET is_read = 0 WHERE id = :id');
@@ -39,7 +38,7 @@ $query = $db->prepare(<<<'SQL'
AND feed.user_id = :user AND feed.user_id = :user
SQL); SQL);
$query->bindValue(':id', $_GET['id']); $query->bindValue(':id', $_GET['id']);
$query->bindValue(':user', $_REQUEST[Key::USER_ID]); $query->bindValue(':user', $_SESSION[Key::USER_ID]);
$result = $query->execute(); $result = $query->execute();
$item = $result ? $result->fetchArray(SQLITE3_ASSOC) : false; $item = $result ? $result->fetchArray(SQLITE3_ASSOC) : false;

View File

@@ -0,0 +1,10 @@
<?php
/**
* User Log Off Page
*/
include '../../start.php';
if (array_key_exists(Key::USER_ID, $_SESSION)) session_destroy();
frc_redirect('/');

View File

@@ -0,0 +1,39 @@
<?php
include '../../start.php';
$db = Data::getConnection();
Security::verifyUser($db, redirectIfAnonymous: false);
// Users already logged on have no need of this page
if (array_key_exists(Key::USER_ID, $_SESSION)) frc_redirect('/');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
Security::logOnUser($_POST['email'] ?? '', $_POST['password'], $_POST['returnTo'], $db);
// If we're still here, something didn't work; preserve the returnTo parameter
$_GET['returnTo'] = $_POST['returnTo'];
}
$isSingle = SECURITY_MODEL == Security::SINGLE_USER_WITH_PASSWORD;
page_head('Log On'); ?>
<h1>Log On</h1>
<article>
<form method=POST action=/user/log-on hx-post=/user/log-on><?php
if (($_GET['returnTo'] ?? '') != '') { ?>
<input type=hidden name=returnTo value="<?=$_GET['returnTo']?>"><?php
}
if (!$isSingle) { ?>
<label>
E-mail Address
<input type=email name=email required autofocus>
</label><br><?php
} ?>
<label>
Password
<input type=password name=password required<?=$isSingle ? ' autofocus' : ''?>>
</label><br>
<button type=submit>Log On</button>
</form>
</article><?php
page_foot();
$db->close();

View File

@@ -14,6 +14,12 @@ require 'user-config.php';
Data::ensureDb(); Data::ensureDb();
session_start([
'name' => 'FRCSESSION',
'use_strict_mode' => true,
'cookie_httponly' => true,
'cookie_samesite' => 'Strict']);
/** /**
* Add a message to be displayed at the top of the page * Add a message to be displayed at the top of the page
* *
@@ -59,21 +65,21 @@ function page_head(string $title): void {
<header> <header>
<a class=title href="/">Feed Reader Central</a> <a class=title href="/">Feed Reader Central</a>
<div><?php <div><?php
if (array_key_exists(Key::USER_ID, $_REQUEST)) { if (array_key_exists(Key::USER_ID, $_SESSION)) {
echo '<a href=/feed?id=new>Add Feed</a>'; echo '<a href=/feed?id=new>Add Feed</a> | <a href=/user/log-off>Log Off</a>';
if ($_REQUEST[Key::USER_EMAIL] != 'solouser@example.com') echo " | {$_REQUEST[Key::USER_EMAIL]}"; if ($_SESSION[Key::USER_EMAIL] != Security::SINGLE_USER_EMAIL) echo " | {$_SESSION[Key::USER_EMAIL]}";
} else {
echo '<a href=/user/log-on>Log On</a>';
} ?> } ?>
</div> </div>
</header> </header>
<main hx-target=this><?php <main hx-target=this><?php
if (array_key_exists(Key::USER_MSG, $_REQUEST)) { foreach ($_REQUEST[Key::USER_MSG] ?? [] as $msg) { ?>
foreach ($_REQUEST[Key::USER_MSG] as $msg) { ?>
<div> <div>
<?=$msg['level'] == 'INFO' ? '' : "<strong>{$msg['level']}</strong><br>"?> <?=$msg['level'] == 'INFO' ? '' : "<strong>{$msg['level']}</strong><br>"?>
<?=$msg['message']?> <?=$msg['message']?>
</div><?php </div><?php
} }
}
} }
/** /**
@@ -81,6 +87,7 @@ function page_head(string $title): void {
*/ */
function page_foot(): void { function page_foot(): void {
?></main></body></html><?php ?></main></body></html><?php
session_commit();
} }
/** /**
@@ -94,8 +101,8 @@ function frc_redirect(string $value): void {
http_response_code(400); http_response_code(400);
die(); die();
} }
header("Location: $value"); session_commit();
http_response_code(303); header("Location: $value", true, 303);
die(); die();
} }

View File

@@ -11,8 +11,6 @@
* - Security::SINGLE_USER (no e-mail required, does not require a password) * - Security::SINGLE_USER (no e-mail required, does not require a password)
* - Security::SINGLE_USER_WITH_PASSWORD (no e-mail required, does require a password) * - Security::SINGLE_USER_WITH_PASSWORD (no e-mail required, does require a password)
* - Security::MULTI_USER (e-mail and password required for all users) * - Security::MULTI_USER (e-mail and password required for all users)
*
* (NOTE THAT ONLY SINGLE_USER IS CURRENTLY IMPLEMENTED)
*/ */
const SECURITY_MODEL = Security::SINGLE_USER; const SECURITY_MODEL = Security::SINGLE_USER;