master
ブランチ master
LittleBeast / src / Site / Controller / User.php
15.8 KB、458行 生 Blame 履歴
1<?php
2/*************************************************************
3# 076 License
4
5Copyright (c) テクニカル諏訪子
6
7Permission is hereby granted to any person obtaining a copy of the software
8Little Beast (the "Software") to use, modify, merge, copy, publish, distribute,
9sublicense, and/or sell copies of the Software, subject to the following conditions:
10
11 1. **Origin Attribution**:
12 - You must not misrepresent the origin of the Software; you must not claim
13 you created the original Software.
14 - If the Software is used in a product, you must either:
15 a. Provide clear attribution in the product's documentation, user interface,
16 or other visible areas, **OR**
17 b. Pay the original developers a fee they specify in writing.
18 2. **Usage Restriction**:
19 - The Software, or any derivative works, dependencies, or libraries
20 incorporating it, must not be used for censorship or to suppress freedom of
21 speech, expression, or creativity. Prohibited uses include, but are not
22 limited to:
23 - Censorship of so-called "hate speech", visuals, non-mainstream opinions,
24 ideas, or objective reality.
25 - Tools or systems designed to restrict access to information or
26 artistic works.
27 3. **Notice Preservation**:
28 - This license and the above copyright notice must remain intact in all copies
29 of the source code.
30
31THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
32INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
33PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
34HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
35CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
36OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 */
38namespace Site\Controller;
39
40use Site\Controller\Mods;
41use Std\Lib\Auth;
42use Std\Lib\Image;
43use Std\Lib\Qr;
44use Std\Lib\Template;
45use Std\Lib\Fedi\Actor;
46use Std\Lib\Fedi\Social;
47use Roles;
48
49class User {
50 use Mods;
51
52 public function login(array $params): void {
53 if (!AUTH_ENABLED) return;
54 try {
55 $auth = new Auth;
56 $user = $auth->getLoggedInUser();
57 if ($user) {
58 header('Location: /');
59 exit();
60 }
61
62 $doLogin = $_SERVER['REQUEST_METHOD'] === 'POST';
63 $error = '';
64 $nyuU = '';
65 // 二段階認証のコードの入力中
66 $ticket = '';
67
68 if ($doLogin) {
69 if (!is_string($_POST['csrf_token'] ?? null) || !\verify_csrf_token($_POST['csrf_token'])) {
70 header('Location: /');
71 exit();
72 }
73 unset($_POST['csrf_token']);
74
75 $a = [];
76 $isBot = false;
77 if (count($_POST) === 4) {
78 $i = 0;
79 foreach ($_POST as $p) {
80 $a[(int)$i] = $p;
81 if ($i >= 2 && $p != '') $isBot = true;
82 $i++;
83 }
84 }
85
86 if ($isBot) {
87 header('Location: /');
88 exit();
89 }
90
91 $loginError = 'エラー:ユーザー名又はパスワードが一致していません。';
92 $username = is_string($a[0] ?? null) ? $a[0] : '';
93 $password = is_string($a[1] ?? null) ? $a[1] : '';
94
95 if (is_string($_POST['ticket'] ?? null)) {
96 // 2段階目:認証アプリのコード
97 $nyuU = is_string($_POST['username'] ?? null) ? $_POST['username'] : '';
98 if ($auth->isLoginThrottled($nyuU)) {
99 $error = 'エラー:ログインの試行回数が多過ぎます。暫くしてから再度お試し下さい。';
100 $ticket = $_POST['ticket'];
101 } else {
102 $auth = new Auth($nyuU);
103 $result = $auth->verifyTwoFactor($nyuU, $_POST['ticket'], is_string($_POST['code'] ?? null) ? $_POST['code'] : '');
104 if ($result->isSuccess) {
105 $auth->clearLoginFailures();
106 header('Location: /');
107 exit();
108 }
109 $auth->recordLoginFailure($nyuU);
110 $error = $result->message;
111 $ticket = $result->data['ticket'] ?? '';
112 }
113 } else if ($username === '' || $password === '') {
114 $error = $loginError;
115 } else if ($auth->isLoginThrottled($username)) {
116 $nyuU = $username;
117 $error = 'エラー:ログインの試行回数が多過ぎます。暫くしてから再度お試し下さい。';
118 } else {
119 $auth = new Auth($username);
120 $res = $auth->isUserExist($username);
121 $result = $res->isSuccess ? $auth->setToken($username, $password) : \Result::Error($loginError);
122 if (!empty($result->data['twoFactor'])) {
123 // パスワードは合っている。コードの画面へ
124 $nyuU = $username;
125 $ticket = $result->data['ticket'];
126 } else if (!$result->isSuccess) {
127 $auth->recordLoginFailure($username);
128 $nyuU = $username;
129 $error = $res->isSuccess ? $result->message : $loginError;
130 } else {
131 $auth->clearLoginFailures();
132 header('Location: /');
133 exit();
134 }
135 }
136 }
137 $tmpl = new Template('/');
138 $pagetit = 'サインイン';
139 $description = 'サイトにサインイン';
140
141 $tmpl->assign('pagetit', $pagetit);
142 $tmpl->assign('curPage', 'auth');
143 $tmpl->assign('custCss', false);
144 $tmpl->assign('menu', $this->getMenu());
145 $tmpl->assign('description', $description);
146 $tmpl->assign('error', $error);
147 $tmpl->assign('nyuU', $nyuU);
148 $tmpl->assign('ticket', $ticket);
149
150 $tmpl->render($ticket !== '' ? 'twofactor' : 'login');
151 } catch (\Exception $e) {
152 throw new \Exception($e->getMessage());
153 }
154 }
155
156 public function logout(array $params): void {
157 if (!AUTH_ENABLED) return;
158 try {
159 $auth = new Auth;
160 $user = $auth->getLoggedInUser();
161 if (!$user) {
162 header('Location: /');
163 exit();
164 }
165
166 $auth->logout();
167 header('Location: /');
168 exit();
169 } catch (\Exception $e) {
170 throw new \Exception($e->getMessage());
171 }
172 }
173
174 public function register(array $params): void {
175 if (!AUTH_REGISTER_ENABLED) return;
176 try {
177 $auth = new Auth;
178 $user = $auth->getLoggedInUser();
179 if ($user) {
180 header('Location: /');
181 exit();
182 }
183
184 $doRegister = $_SERVER['REQUEST_METHOD'] === 'POST';
185 $error = '';
186 $nyuU = '';
187 $nyuE = '';
188
189 if ($doRegister) {
190 if (!is_string($_POST['csrf_token'] ?? null) || !\verify_csrf_token($_POST['csrf_token'])) {
191 header('Location: /');
192 exit();
193 }
194 unset($_POST['csrf_token']);
195
196 $a = [];
197 $isBot = false;
198 if (count($_POST) === 8) {
199 $i = 0;
200 foreach ($_POST as $p) {
201 $a[(int)$i] = $p;
202 if ($i >= 4 && $p != '') $isBot = true;
203 $i++;
204 }
205 }
206
207 if ($isBot) {
208 header('Location: /');
209 exit();
210 }
211
212 $auth = new Auth;
213 $res = $auth->mkUser($a[0] ?? null, $a[1] ?? null, $a[2] ?? null, $a[3] ?? null);
214 if (!$res->isSuccess) {
215 $error = $res->message;
216 $nyuU = $a[0] ?? '';
217 $nyuE = $a[3] ?? '';
218 } else if ($res->data['verify'] ?? false) {
219 // 確認メールのリンクを開くまでログインしない
220 $this->renderVerify('登録', $res->message, '');
221 return;
222 } else {
223 $auth = new Auth($a[0]);
224 $auth->setToken($a[0], $a[1]);
225 header('Location: /');
226 exit();
227 }
228 }
229
230 $tmpl = new Template('/');
231 $pagetit = '登録';
232 $description = 'サイトに登録';
233
234 $tmpl->assign('pagetit', $pagetit);
235 $tmpl->assign('curPage', 'auth');
236 $tmpl->assign('custCss', false);
237 $tmpl->assign('menu', $this->getMenu());
238 $tmpl->assign('description', $description);
239 $tmpl->assign('error', $error);
240 $tmpl->assign('nyuU', $nyuU);
241 $tmpl->assign('nyuE', $nyuE);
242
243 $tmpl->render('register');
244 } catch (\Exception $e) {
245 throw new \Exception($e->getMessage());
246 }
247 }
248
249 /**
250 * 確認メールのリンク(/verify/{token})
251 *
252 * @param array $params パラメータ配列
253 * @return void
254 */
255 public function verify(array $params): void {
256 if (!AUTH_ENABLED) return;
257 try {
258 $auth = new Auth;
259 $res = $auth->verifyEmailToken((string)($params['token'] ?? ''));
260 if ($res->isSuccess) $this->renderVerify('メールアドレスの確認', $res->message, '');
261 else $this->renderVerify('メールアドレスの確認', '', $res->message);
262 } catch (\Exception $e) {
263 throw new \Exception($e->getMessage());
264 }
265 }
266
267 private function renderVerify(string $pagetit, string $message, string $error): void {
268 $tmpl = new Template('/');
269 $tmpl->assign('pagetit', $pagetit);
270 $tmpl->assign('curPage', 'auth');
271 $tmpl->assign('custCss', false);
272 $tmpl->assign('menu', $this->getMenu());
273 $tmpl->assign('description', '');
274 $tmpl->assign('message', $message);
275 $tmpl->assign('error', $error);
276 $tmpl->render('verify');
277 }
278
279 /**
280 * プロフィールの編集(/profile/{name}/edit)。本人と管理者だけ
281 *
282 * @param array $params パラメータ配列
283 * @return void
284 */
285 public function editProfile(array $params): void {
286 if (!AUTH_ENABLED) return;
287 $name = (string)($params['name'] ?? '');
288 $auth = new Auth;
289 $user = $auth->getLoggedInUser();
290 if (!$user) {
291 header('Location: /login');
292 exit();
293 }
294 $edit = $auth->getEditableUser($name);
295 if (!$edit) {
296 header('Location: /404');
297 exit();
298 }
299
300 $error = '';
301 $message = '';
302 if ($_SERVER['REQUEST_METHOD'] === 'POST') {
303 if (!is_string($_POST['csrf_token'] ?? null) || !\verify_csrf_token($_POST['csrf_token'])) {
304 $error = 'セッションの有効期限が切れました。もう一度保存して下さい。';
305 } else {
306 $in = [
307 'displayname' => (string)($_POST['displayname'] ?? ''),
308 'gender' => (string)($_POST['gender'] ?? '-1'),
309 'namecolor' => (string)($_POST['namecolor'] ?? ''),
310 'bio' => (string)($_POST['bio'] ?? ''),
311 'removeAvatar' => isset($_POST['removeAvatar']),
312 ];
313 if ($edit->isSelf) {
314 foreach (['currentPassword', 'newPassword', 'newPasswordVerify', 'email'] as $k) $in[$k] = (string)($_POST[$k] ?? '');
315 }
316 // ロールの欄が送られた時だけ変える(欄が無いフォームから送られても、全部外してBANにしない様に)
317 if ($edit->isAdmin && isset($_POST['rolesForm'])) $in['roles'] = array_map('intval', (array)($_POST['roles'] ?? []));
318 $res = $auth->updateProfile($name, $in, $_FILES['avatar'] ?? null);
319 if ($res->isSuccess) {
320 // Fediverseの設定とプロフィールの配信
321 if (ACTIVITYPUB_MULTIUSER) {
322 $fresh = $res->data['user'];
323 if (can_federate($fresh)) {
324 Actor::saveSettings($name, ['locked' => isset($_POST['locked'])]);
325 Social::sendProfileUpdate($name);
326 }
327 }
328 $message = (string)$res->message;
329 $edit = $auth->getEditableUser($name);
330 } else {
331 $error = (string)$res->message;
332 }
333 }
334 }
335
336 $tmpl = new Template('/');
337 $tmpl->assign('pagetit', 'プロフィールの編集');
338 $tmpl->assign('curPage', 'auth');
339 $tmpl->assign('custCss', false);
340 $tmpl->assign('menu', $this->getMenu());
341 $tmpl->assign('description', '');
342 $tmpl->assign('user', $user);
343 $tmpl->assign('e', $edit);
344 $tmpl->assign('error', $error);
345 $tmpl->assign('message', $message);
346 $tmpl->assign('roles', Roles::LABELS);
347 $tmpl->assign('fediEnabled', ACTIVITYPUB_MULTIUSER);
348 $tmpl->assign('locked', ACTIVITYPUB_MULTIUSER && $edit->fedi ? (bool)Actor::settings($name)['locked'] : false);
349 $tmpl->assign('twoFactor', $auth->twoFactorAvailable());
350 $tmpl->assign('csrf', make_csrf_token());
351 $tmpl->render('editprofile');
352 }
353
354 /**
355 * 二段階認証の設定(QRコードと秘密鍵、有効・無効)
356 */
357 public function twoFactor(array $params): void {
358 if (!AUTH_ENABLED) return;
359 $name = (string)($params['name'] ?? '');
360 $auth = new Auth;
361 $user = $auth->getLoggedInUser();
362 if (!$user) {
363 header('Location: /login');
364 exit();
365 }
366
367 $error = '';
368 $message = '';
369 if ($_SERVER['REQUEST_METHOD'] === 'POST') {
370 if (!is_string($_POST['csrf_token'] ?? null) || !\verify_csrf_token($_POST['csrf_token'])) {
371 $error = 'セッションの有効期限が切れました。もう一度お試し下さい。';
372 } else {
373 $code = (string)($_POST['code'] ?? '');
374 $res = ($_POST['action'] ?? '') === 'disable'
375 ? $auth->disableTwoFactor($name, (string)($_POST['password'] ?? ''), $code)
376 : $auth->enableTwoFactor($name, $code);
377 if ($res->isSuccess) $message = (string)$res->message;
378 else $error = (string)$res->message;
379 }
380 }
381 $status = $auth->twoFactorStatus($name);
382 if (!$status->isSuccess) {
383 header('Location: /404');
384 exit();
385 }
386 $s = (object)$status->data;
387
388 $tmpl = new Template('/');
389 $tmpl->assign('pagetit', '二段階認証');
390 $tmpl->assign('curPage', 'auth');
391 $tmpl->assign('custCss', false);
392 $tmpl->assign('menu', $this->getMenu());
393 $tmpl->assign('description', '');
394 $tmpl->assign('user', $user);
395 $tmpl->assign('s', $s);
396 // 手で入力し易い様に4文字毎に区切る
397 $tmpl->assign('secretGroups', isset($s->secret) ? trim(chunk_split($s->secret, 4, ' ')) : '');
398 $tmpl->assign('error', $error);
399 $tmpl->assign('message', $message);
400 $tmpl->assign('csrf', make_csrf_token());
401 $tmpl->render('twofactorsetup');
402 }
403
404 /**
405 * 設定中の秘密鍵のQRコード(PNG、本人だけ)
406 */
407 public function twoFactorQr(array $params): void {
408 if (!AUTH_ENABLED) return;
409 $auth = new Auth;
410 $status = $auth->getLoggedInUser() ? $auth->twoFactorStatus((string)($params['name'] ?? '')) : null;
411 if (!$status || !isset($status->data['uri'])) {
412 http_response_code(404);
413 exit();
414 }
415 header('Content-Type: image/png');
416 header('Cache-Control: no-store');
417 echo Image::encode((new Qr($status->data['uri']))->bitmap(4), 'image/png');
418 exit();
419 }
420
421 public function profile(array $params): void {
422 if (!AUTH_ENABLED) return;
423 $name = '';
424 if (isset($params['name'])) $name = $params['name'];
425 if ($name === '') {
426 header('Location: /');
427 exit();
428 }
429
430 try {
431 $auth = new Auth;
432 $user = $auth->getLoggedInUser();
433 $u = $auth->getUser($name);
434 if (!$u) {
435 header('Location: /404');
436 exit();
437 }
438
439 $tmpl = new Template('/');
440 $suffix = $u->gender === '男' ? 'くん' : ($u->gender === '女' ? 'ちゃん' : 'さん');
441 $pagetit = $u->altName.$suffix.'のプロフィール';
442 $description = '';
443
444 $tmpl->assign('pagetit', $pagetit);
445 $tmpl->assign('curPage', 'auth');
446 $tmpl->assign('custCss', false);
447 $tmpl->assign('menu', $this->getMenu());
448 $tmpl->assign('description', $description);
449 $tmpl->assign('user', $user);
450 $tmpl->assign('u', $u);
451 $tmpl->assign('name', $name);
452
453 $tmpl->render('profile');
454 } catch (\Exception $e) {
455 throw new \Exception($e->getMessage());
456 }
457 }
458}