Repository navigation
Expand file tree
/
Copy pathAuthentication.php
More file actions
310 lines (280 loc) · 10.6 KB
/
Copy pathAuthentication.php
File metadata and controls
310 lines (280 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
<?php
namespace Shaack\Reboot\AddOns;
use Shaack\Htpasswd;
use Shaack\Logger;
use Shaack\Reboot\AddOn;
use Shaack\Reboot\AdminSession;
use Shaack\Reboot\AddOns\Authentication\RememberMeStore;
use Shaack\Reboot\Request;
use Shaack\Reboot\Session;
use Shaack\Reboot\TrustedHosts;
use Shaack\Utils\FileSystemUtils;
use Symfony\Component\Yaml\Yaml;
class Authentication extends AddOn
{
private Htpasswd $htpasswd;
private RememberMeStore $rememberMe;
private string $rolesFile;
private array $roles = [];
/** The "Stay signed in" cookie, see RememberMeStore. */
const REMEMBER_COOKIE = "reboot_remember";
const ROLE_ADMIN = "admin";
const ROLE_EDITOR = "editor";
const ROLE_DISABLED = "disabled";
const EDITOR_PAGES = ["/pages", "/data", "/media"];
/**
* @see AddOn::init()
*/
protected function init() {
Session::start('Strict');
$this->htpasswd = new Htpasswd($this->reboot->getBaseFsPath() . "/local/.htpasswd");
$this->rememberMe = new RememberMeStore($this->reboot->getBaseFsPath());
$this->rolesFile = $this->reboot->getBaseFsPath() . "/local/roles.yml";
if (file_exists($this->rolesFile)) {
$roles = Yaml::parseFile($this->rolesFile);
// users without an entry are admins, so a damaged file must not count as empty
if (!is_array($roles)) {
throw new \RuntimeException("local/roles.yml is damaged, restore it from a backup");
}
$this->roles = $roles;
}
if (empty($_SESSION['user']) && isset($_COOKIE[self::REMEMBER_COOKIE])) {
$this->loginFromRememberCookie();
}
}
/**
* Restores the session from the "Stay signed in" cookie. The token is
* good for one use, a valid one is replaced by a fresh one, anything
* else clears the cookie.
*/
private function loginFromRememberCookie(): void
{
$username = $this->rememberMe->consume($_COOKIE[self::REMEMBER_COOKIE]);
if ($username === null || !in_array($username, $this->htpasswd->getUsers(), true)
|| $this->getUserRole($username) === self::ROLE_DISABLED) {
Logger::info("Stay signed in: cookie rejected");
$this->clearRememberCookie();
return;
}
Logger::info("Stay signed in: session restored for " . $username);
$this->startSession($username);
$this->issueRememberCookie($username);
}
private function startSession(string $username): void
{
session_regenerate_id(true);
$_SESSION['user'] = $username;
$_SESSION['checksum'] = $this->getChecksum();
}
private function issueRememberCookie(string $username): void
{
$token = $this->rememberMe->create($username);
setcookie(self::REMEMBER_COOKIE, $token, $this->rememberCookieOptions(time() + RememberMeStore::LIFETIME));
$_COOKIE[self::REMEMBER_COOKIE] = $token;
}
private function clearRememberCookie(): void
{
if (isset($_COOKIE[self::REMEMBER_COOKIE])) {
setcookie(self::REMEMBER_COOKIE, "", $this->rememberCookieOptions(1));
unset($_COOKIE[self::REMEMBER_COOKIE]);
}
}
private function rememberCookieOptions(int $expires): array
{
$https = Session::isHttps();
return [
'expires' => $expires,
'path' => $this->site->getWebPath() ?: '/',
'secure' => $https,
'httponly' => true,
'samesite' => 'Strict',
];
}
/**
* @see AddOn::preRender()
*/
public function preRender(Request $request): bool
{
if ($this->htpasswd->isDamaged()) {
Logger::error("local/.htpasswd has content but no valid user");
http_response_code(503);
echo "The user file local/.htpasswd is damaged. Restore it from a backup, or delete it to create a new admin account.";
return false;
}
if ($this->htpasswd->isEmpty()) {
if ($request->getPath() !== "/setup") {
$this->reboot->redirect($this->site->getWebPath() . "/setup");
return false;
}
return true;
}
// Handle stop impersonating before access control
if ($this->isImpersonating() && $request->getParam("action") === "stop_impersonate") {
$this->stopImpersonating();
$this->reboot->redirect($this->site->getWebPath() . "/users");
return false;
}
$user = $this->getUser();
if (!$user && $request->getPath() !== "/login") {
Logger::info("No user found, redirect to the login");
$this->reboot->redirect( $this->site->getWebPath() . "/login");
return false;
} else if ($user) {
if (@$_SESSION['checksum'] !== $this->getChecksum()) {
// The session is stale (password file, IP or browser changed). Only the session
// ends, a "Stay signed in" cookie restores it on the next request.
$this->endSession();
return false;
}
// Disabled accounts lose access immediately (skip if impersonating — admin retains access)
if (!$this->isImpersonating() && $this->getUserRole($user) === self::ROLE_DISABLED) {
Logger::info("Access denied, account disabled: " . $user);
$this->rememberMe->deleteForSubject($user);
$this->logout();
return false;
}
// the host a user of the admin reaches the site under, for links in mails
(new TrustedHosts($this->reboot->getBaseFsPath()))->rememberRequestHost();
// Already signed in, for example restored from the "Stay signed in" cookie,
// the login form is not needed
if ($request->getPath() === "/login" && $_SERVER['REQUEST_METHOD'] === 'GET') {
$this->reboot->redirect($this->site->getWebPath() . "/pages");
return false;
}
// Restrict editor access to allowed pages only (skip if impersonating — admin retains access)
if (!$this->isImpersonating() && $this->getUserRole($user) === self::ROLE_EDITOR) {
$path = $request->getPath();
$allowed = false;
foreach (self::EDITOR_PAGES as $editorPage) {
if ($path === $editorPage || str_starts_with($path, $editorPage . "/")) {
$allowed = true;
break;
}
}
if (!$allowed && $path !== "/login" && $path !== "/logout") {
$this->reboot->redirect($this->site->getWebPath() . "/pages");
return false;
}
}
}
return true;
}
/**
* Calculates a checksum for the admin session. Detects, if the .htpasswd was changed, the IP-Address or
* the user agent of the user.
* @return string md5 checksum
*/
private function getChecksum(): string
{
return AdminSession::checksum($this->htpasswd);
}
/**
* @param bool $remember keep the user signed in for two weeks via the "Stay signed in" cookie
*/
public function login($username, $password, bool $remember = false): bool
{
if ($this->htpasswd->validate($username, $password)) {
if ($this->getUserRole($username) === self::ROLE_DISABLED) {
Logger::info("Login denied, account disabled: " . $username);
return false;
}
$this->startSession($username);
if ($remember) {
$this->issueRememberCookie($username);
}
return true;
}
return false;
}
public function impersonate(string $username): void
{
$_SESSION['impersonator'] = $_SESSION['user'];
$_SESSION['user'] = $username;
}
public function stopImpersonating(): void
{
if (isset($_SESSION['impersonator'])) {
$_SESSION['user'] = $_SESSION['impersonator'];
unset($_SESSION['impersonator']);
}
}
public function isImpersonating(): bool
{
return isset($_SESSION['impersonator']);
}
public function getImpersonator(): ?string
{
return $_SESSION['impersonator'] ?? null;
}
/**
* Explicit logout: ends the session and forgets the "Stay signed in" cookie.
*/
public function logout()
{
Logger::info("logout " . $this->getUser());
$this->rememberMe->delete($_COOKIE[self::REMEMBER_COOKIE] ?? null);
$this->clearRememberCookie();
$this->endSession();
}
/**
* Ends the session and sends the browser to the admin, which asks for a
* login unless a "Stay signed in" cookie restores the session.
*/
private function endSession(): void
{
$_SESSION = [];
session_regenerate_id(true);
session_destroy();
$this->reboot->redirect($this->reboot->getBaseWebPath() . "/admin");
}
/**
* @return mixed|null Returns the username, if logged in or null if not
*/
public function getUser()
{
return @$_SESSION['user'];
}
public function getHtpasswd(): Htpasswd
{
return $this->htpasswd;
}
public function refreshChecksum(): void
{
$_SESSION['checksum'] = $this->getChecksum();
}
/**
* Forget the "Stay signed in" tokens of a user, after a password change,
* a deletion or when the account is disabled.
*/
public function forgetRememberedLogins(string $username): void
{
$this->rememberMe->deleteForSubject($username);
}
public function getUserRole(string $username): string
{
return $this->roles[$username] ?? self::ROLE_ADMIN;
}
public function setUserRole(string $username, string $role): void
{
if (!in_array($role, [self::ROLE_ADMIN, self::ROLE_EDITOR, self::ROLE_DISABLED])) {
throw new \InvalidArgumentException("Invalid role: $role");
}
$this->roles[$username] = $role;
$this->saveRoles();
}
public function deleteUserRole(string $username): void
{
unset($this->roles[$username]);
$this->saveRoles();
}
public function isAdmin(?string $username = null): bool
{
$username = $username ?? $this->getUser();
if (!$username) return false;
return $this->getUserRole($username) === self::ROLE_ADMIN;
}
private function saveRoles(): void
{
FileSystemUtils::writeAtomic($this->rolesFile, Yaml::dump($this->roles), 0600);
}
}