initial commit
This commit is contained in:
commit
3f64f4a49a
221 files changed
+26665
No files matched your search
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controllers\Web;
|
||||
|
||||
use Rsgrinko\Proton\Auth\Auth;
|
||||
use Rsgrinko\Proton\Events\Events;
|
||||
use Rsgrinko\Proton\Http\Controller;
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\Support\Audit;
|
||||
use Rsgrinko\Proton\View\View;
|
||||
|
||||
/**
|
||||
* Вход, выход и страница первого запуска.
|
||||
*/
|
||||
final class AuthController extends Controller
|
||||
{
|
||||
/**
|
||||
* Форма входа.
|
||||
*/
|
||||
public function showLogin(): Response
|
||||
{
|
||||
return $this->bare('auth/login', [
|
||||
'remember' => Auth::rememberDays() > 0,
|
||||
], 'Вход');
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверка логина и пароля.
|
||||
*/
|
||||
public function login(Request $request): Response
|
||||
{
|
||||
$result = Auth::attempt(
|
||||
$request->text('login'),
|
||||
(string) $request->input('password', ''),
|
||||
$request->ip()
|
||||
);
|
||||
|
||||
if ($result['user'] === null) {
|
||||
Audit::login($request->text('login'), false);
|
||||
|
||||
$this->flash($result['error'], 'error');
|
||||
|
||||
return $this->redirect('login');
|
||||
}
|
||||
|
||||
Auth::login($result['user'], $request->boolean('remember'));
|
||||
|
||||
Audit::login((string) $result['user']->login);
|
||||
Events::fire('user.login', ['user' => $result['user']]);
|
||||
|
||||
// Человек шёл по ссылке, а его отправили на вход — вернём куда собирался
|
||||
$intended = (string) View::takeStash('intended', '');
|
||||
|
||||
return $intended !== '' && str_starts_with($intended, '/')
|
||||
? Response::redirect($intended)
|
||||
: $this->redirect('home');
|
||||
}
|
||||
|
||||
public function logout(Request $request): Response
|
||||
{
|
||||
$login = Auth::viewer()->login();
|
||||
|
||||
Audit::logout($login);
|
||||
Events::fire('user.logout', ['login' => $login]);
|
||||
|
||||
Auth::logout();
|
||||
|
||||
$this->flash('Вы вышли');
|
||||
|
||||
return $this->redirect('login');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controllers\Web;
|
||||
|
||||
use App\Models\Note;
|
||||
use Rsgrinko\Proton\Access\Scope;
|
||||
use Rsgrinko\Proton\Access\Viewer;
|
||||
use Rsgrinko\Proton\Http\Controller;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
|
||||
/**
|
||||
* Главная страница вошедшего: что у него есть и куда идти дальше.
|
||||
*/
|
||||
final class HomeController extends Controller
|
||||
{
|
||||
public function index(Viewer $viewer, Scope $scope): Response
|
||||
{
|
||||
return $this->view('home', [
|
||||
'active' => 'home',
|
||||
'viewer' => $viewer,
|
||||
'notes' => $scope->apply(Note::query())->count(),
|
||||
'latest' => $scope->apply(Note::query())->orderBy('id', 'desc')->limit(5)->get(),
|
||||
], 'Главная');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controllers\Web;
|
||||
|
||||
use Rsgrinko\Proton\Auth\Auth;
|
||||
use Rsgrinko\Proton\Auth\Password;
|
||||
use Rsgrinko\Proton\Http\Controller;
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\Install\Installer;
|
||||
use Rsgrinko\Proton\Support\Audit;
|
||||
use Rsgrinko\Proton\Support\Config;
|
||||
use Rsgrinko\Proton\View\View;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Веб-установщик: те же шаги, что и у `php bin/proton install`, но мышкой.
|
||||
*
|
||||
* Открыт, только пока приложение не установлено (нет ключа, схемы или ни одного
|
||||
* пользователя) — за этим следит прослойка install. После установки страница
|
||||
* уводит на главную: иначе кто угодно завёл бы себе администратора.
|
||||
*
|
||||
* Делает всё Install\Installer — мастер только спрашивает и показывает.
|
||||
*/
|
||||
final class InstallController extends Controller
|
||||
{
|
||||
public function show(Request $request): Response
|
||||
{
|
||||
return $this->bare('install/index', [
|
||||
'checks' => Installer::requirements(),
|
||||
'ready' => Installer::ready(),
|
||||
'values' => $this->defaults($request),
|
||||
], 'Установка');
|
||||
}
|
||||
|
||||
public function store(Request $request): Response
|
||||
{
|
||||
if (!Installer::ready()) {
|
||||
$this->flash('Окружение не готово: посмотрите проверки выше', 'error');
|
||||
|
||||
return $this->redirect('install');
|
||||
}
|
||||
|
||||
$data = $this->validate($request, [
|
||||
'app_name' => 'required|max:100',
|
||||
'app_url' => 'required|max:191',
|
||||
'timezone' => 'required|max:64',
|
||||
'db_driver' => 'required|in:sqlite,mysql',
|
||||
'db_host' => 'nullable|max:191',
|
||||
'db_port' => 'nullable|integer',
|
||||
'db_database' => 'nullable|max:100',
|
||||
'db_username' => 'nullable|max:100',
|
||||
'db_password' => 'nullable|max:191',
|
||||
'mail_driver' => 'required|in:mail,smtp,mailer,log,null',
|
||||
'mail_from' => 'nullable|email|max:191',
|
||||
'admin_login' => 'required|min:3|max:100|regex:/^[A-Za-z0-9._-]+$/',
|
||||
'admin_email' => 'nullable|email|max:191',
|
||||
'admin_password' => 'required|min:' . Password::minLength() . '|confirmed',
|
||||
], [
|
||||
'app_name' => 'Название',
|
||||
'app_url' => 'Адрес приложения',
|
||||
'timezone' => 'Часовой пояс',
|
||||
'db_driver' => 'База данных',
|
||||
'db_database' => 'Имя базы',
|
||||
'mail_driver' => 'Почта',
|
||||
'mail_from' => 'Адрес отправителя',
|
||||
'admin_login' => 'Логин администратора',
|
||||
'admin_email' => 'Почта администратора',
|
||||
'admin_password' => 'Пароль администратора',
|
||||
]);
|
||||
|
||||
$answers = [
|
||||
'DB_DRIVER' => (string) $data['db_driver'],
|
||||
'DB_HOST' => (string) ($data['db_host'] ?? '127.0.0.1'),
|
||||
'DB_PORT' => (string) ($data['db_port'] ?? 3306),
|
||||
'DB_DATABASE' => (string) ($data['db_database'] ?? ''),
|
||||
'DB_USERNAME' => (string) ($data['db_username'] ?? ''),
|
||||
'DB_PASSWORD' => (string) ($data['db_password'] ?? ''),
|
||||
];
|
||||
|
||||
$settings = Installer::databaseSettings($answers);
|
||||
$error = Installer::checkDatabase($settings);
|
||||
|
||||
if ($error !== null && $answers['DB_DRIVER'] === 'mysql') {
|
||||
// Базы может просто не быть — заведём её сами, это обычный шаг установки
|
||||
if (Installer::createMysqlDatabase($settings) === null) {
|
||||
$error = Installer::checkDatabase($settings);
|
||||
}
|
||||
}
|
||||
|
||||
if ($error !== null) {
|
||||
$this->flash('База недоступна: ' . $error, 'error');
|
||||
|
||||
View::stash('old', $request->all());
|
||||
|
||||
return $this->redirect('install');
|
||||
}
|
||||
|
||||
try {
|
||||
$env = [
|
||||
'APP_NAME' => (string) $data['app_name'],
|
||||
'APP_URL' => rtrim((string) $data['app_url'], '/'),
|
||||
'APP_TIMEZONE' => (string) $data['timezone'],
|
||||
'APP_ENV' => 'production',
|
||||
'APP_DEBUG' => 'false',
|
||||
'MAIL_DRIVER' => (string) $data['mail_driver'],
|
||||
'MAIL_FROM' => (string) ($data['mail_from'] ?? ''),
|
||||
];
|
||||
|
||||
if ($answers['DB_DRIVER'] === 'sqlite') {
|
||||
$env['DB_DRIVER'] = 'sqlite';
|
||||
$env['DB_PATH'] = APP_ROOT . '/var/app.sqlite';
|
||||
} else {
|
||||
$env = array_merge($env, $answers);
|
||||
}
|
||||
|
||||
Installer::writeEnv($env);
|
||||
Installer::ensureKey();
|
||||
Installer::migrate();
|
||||
|
||||
$user = Installer::createAdmin(
|
||||
(string) $data['admin_login'],
|
||||
(string) $data['admin_password'],
|
||||
(string) ($data['admin_email'] ?? '')
|
||||
);
|
||||
|
||||
Auth::login($user, false);
|
||||
|
||||
Audit::created('user', $user->id(), 'установка: заведён администратор ' . (string) $user->login);
|
||||
} catch (Throwable $e) {
|
||||
$this->flash('Установка не завершилась: ' . $e->getMessage(), 'error');
|
||||
|
||||
View::stash('old', $request->all());
|
||||
|
||||
return $this->redirect('install');
|
||||
}
|
||||
|
||||
$this->flash('Готово. Приложение установлено, вы вошли как администратор');
|
||||
|
||||
return $this->redirect('home');
|
||||
}
|
||||
|
||||
/**
|
||||
* Что подставить в форму: то, что уже есть в настройках.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
private function defaults(Request $request): array
|
||||
{
|
||||
return [
|
||||
'app_name' => (string) Config::get('app.name', 'Proton'),
|
||||
'app_url' => rtrim((string) Config::get('app.url', ''), '/') !== ''
|
||||
? (string) Config::get('app.url')
|
||||
: 'http://' . $request->header('host'),
|
||||
'timezone' => (string) Config::get('app.timezone', 'Europe/Moscow'),
|
||||
'db_driver' => (string) Config::get('db.driver', 'sqlite'),
|
||||
'db_host' => (string) Config::get('db.mysql.host', '127.0.0.1'),
|
||||
'db_port' => (string) Config::get('db.mysql.port', 3306),
|
||||
'db_database' => (string) Config::get('db.mysql.database', 'proton'),
|
||||
'db_username' => (string) Config::get('db.mysql.username', ''),
|
||||
'mail_driver' => (string) Config::get('mail.driver', 'mail'),
|
||||
'mail_from' => (string) Config::get('mail.from_email', ''),
|
||||
'admin_login' => 'admin',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controllers\Web;
|
||||
|
||||
use App\Models\Note;
|
||||
use Rsgrinko\Proton\Access\Scope;
|
||||
use Rsgrinko\Proton\Access\Viewer;
|
||||
use Rsgrinko\Proton\Files\Storage;
|
||||
use Rsgrinko\Proton\Http\Controller;
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\Support\Audit;
|
||||
use Rsgrinko\Proton\Support\ProtonException;
|
||||
|
||||
/**
|
||||
* Заметки — демонстрационный раздел: список с поиском и страницами, карточка,
|
||||
* форма, загрузка файла, мягкое удаление.
|
||||
*
|
||||
* Здесь же видно, как работает область видимости: обычный пользователь видит
|
||||
* только свои заметки, а для администратора (право data.all) видны все.
|
||||
* Чужая запись для остальных просто не существует — «не найдено», а не
|
||||
* «нет доступа»: постороннему знать нечего.
|
||||
*/
|
||||
final class NotesController extends Controller
|
||||
{
|
||||
public function index(Request $request, Scope $scope): Response
|
||||
{
|
||||
$search = $request->text('q');
|
||||
|
||||
$query = $scope->apply(Note::query())
|
||||
->when($search, static function ($query, string $needle): void {
|
||||
$query->whereLike('title', $needle);
|
||||
})
|
||||
->orderBy('pinned', 'desc')
|
||||
->orderBy('id', 'desc');
|
||||
|
||||
$page = $query->paginate($this->page($request), $this->perPage());
|
||||
|
||||
return $this->view('notes/index', [
|
||||
'active' => 'notes',
|
||||
'page' => $page,
|
||||
'search' => $search,
|
||||
], 'Заметки');
|
||||
}
|
||||
|
||||
public function create(): Response
|
||||
{
|
||||
return $this->view('notes/form', [
|
||||
'active' => 'notes',
|
||||
'note' => new Note(),
|
||||
], 'Новая заметка');
|
||||
}
|
||||
|
||||
public function store(Request $request, Viewer $viewer): Response
|
||||
{
|
||||
$data = $this->validate($request, [
|
||||
'title' => 'required|max:191',
|
||||
'body' => 'nullable|max:20000',
|
||||
'pinned' => 'nullable|boolean',
|
||||
], ['title' => 'Название', 'body' => 'Текст']);
|
||||
|
||||
$note = new Note($data);
|
||||
|
||||
$note->setAttribute('user_id', $viewer->id());
|
||||
|
||||
$this->attachFile($request, $note);
|
||||
|
||||
$note->save();
|
||||
|
||||
Audit::created('note', $note->id(), 'заметка «' . (string) $note->title . '»');
|
||||
|
||||
$this->flash('Заметка сохранена');
|
||||
|
||||
return $this->redirect('notes.show', ['id' => $note->id()]);
|
||||
}
|
||||
|
||||
public function show(int $id, Scope $scope): Response
|
||||
{
|
||||
$note = $this->find($id, $scope);
|
||||
|
||||
return $this->view('notes/show', [
|
||||
'active' => 'notes',
|
||||
'note' => $note,
|
||||
'author' => $note->author,
|
||||
], (string) $note->title);
|
||||
}
|
||||
|
||||
public function edit(int $id, Scope $scope): Response
|
||||
{
|
||||
return $this->view('notes/form', [
|
||||
'active' => 'notes',
|
||||
'note' => $this->find($id, $scope),
|
||||
], 'Правка заметки');
|
||||
}
|
||||
|
||||
public function update(Request $request, int $id, Scope $scope): Response
|
||||
{
|
||||
$note = $this->find($id, $scope);
|
||||
|
||||
$data = $this->validate($request, [
|
||||
'title' => 'required|max:191',
|
||||
'body' => 'nullable|max:20000',
|
||||
'pinned' => 'nullable|boolean',
|
||||
], ['title' => 'Название', 'body' => 'Текст']);
|
||||
|
||||
$before = ['title' => $note->title, 'body' => $note->body, 'pinned' => $note->raw('pinned')];
|
||||
|
||||
$note->fill($data);
|
||||
|
||||
$this->attachFile($request, $note);
|
||||
|
||||
$note->save();
|
||||
|
||||
Audit::updated('note', $note->id(), 'заметка «' . (string) $note->title . '»', Audit::between($before, [
|
||||
'title' => $note->title,
|
||||
'body' => $note->body,
|
||||
'pinned' => $note->raw('pinned'),
|
||||
]));
|
||||
|
||||
$this->flash('Заметка сохранена');
|
||||
|
||||
return $this->redirect('notes.show', ['id' => $note->id()]);
|
||||
}
|
||||
|
||||
public function delete(int $id, Scope $scope): Response
|
||||
{
|
||||
$note = $this->find($id, $scope);
|
||||
|
||||
// Мягкое удаление: запись остаётся в базе с отметкой времени
|
||||
$note->delete();
|
||||
|
||||
Audit::deleted('note', $note->id(), 'заметка «' . (string) $note->title . '»');
|
||||
|
||||
$this->flash('Заметка удалена');
|
||||
|
||||
return $this->redirect('notes.index');
|
||||
}
|
||||
|
||||
/**
|
||||
* Отдаёт приложенный файл. Хранилище лежит вне public, поэтому файлы
|
||||
* отдаёт код — присланный «аватар.php» не должен стать скриптом на сайте.
|
||||
*/
|
||||
public function file(int $id, Scope $scope): Response
|
||||
{
|
||||
$note = $this->find($id, $scope);
|
||||
|
||||
if (!$note->hasFile() || !Storage::exists((string) $note->raw('file_path'))) {
|
||||
$this->flash('Файла нет', 'error');
|
||||
|
||||
return $this->redirect('notes.show', ['id' => $note->id()]);
|
||||
}
|
||||
|
||||
return Response::download(
|
||||
Storage::read((string) $note->raw('file_path')),
|
||||
(string) $note->raw('file_name')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Заметка с оглядкой на область видимости: чужая для обычного пользователя
|
||||
* просто не существует.
|
||||
*/
|
||||
private function find(int $id, Scope $scope): Note
|
||||
{
|
||||
/** @var Note|null $note */
|
||||
$note = $scope->apply(Note::query())->where('id', $id)->first();
|
||||
|
||||
/** @var Note $found */
|
||||
$found = $this->require($note, 'notes.index', 'Заметка не найдена');
|
||||
|
||||
return $found;
|
||||
}
|
||||
|
||||
/**
|
||||
* Прикладывает файл, если его прислали. Прежний удаляем после того, как
|
||||
* новый лёг на диск, — иначе при ошибке останемся без обоих.
|
||||
*/
|
||||
private function attachFile(Request $request, Note $note): void
|
||||
{
|
||||
$file = $request->file('attachment');
|
||||
|
||||
if ($file === null || !$file->uploaded()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$stored = Storage::put($file, 'notes');
|
||||
} catch (ProtonException $e) {
|
||||
$this->flash($e->getMessage(), 'error');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$previous = (string) $note->raw('file_path');
|
||||
|
||||
$note->forceFill(['file_path' => $stored['path'], 'file_name' => $stored['name']]);
|
||||
|
||||
if ($previous !== '' && $previous !== $stored['path']) {
|
||||
Storage::delete($previous);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controllers\Web;
|
||||
|
||||
use Rsgrinko\Proton\Http\Controller;
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\Mail\Message;
|
||||
use Rsgrinko\Proton\Models\AuthToken;
|
||||
use Rsgrinko\Proton\Models\User;
|
||||
use Rsgrinko\Proton\RateLimit\RateLimiter;
|
||||
use Rsgrinko\Proton\Support\Audit;
|
||||
use Rsgrinko\Proton\Support\Config;
|
||||
use Rsgrinko\Proton\View\View;
|
||||
|
||||
/**
|
||||
* Забытый пароль: письмо со ссылкой и установка нового.
|
||||
*
|
||||
* Ответ на запрос всегда одинаковый — «письмо отправлено», даже если такого
|
||||
* адреса нет. Иначе форма превращается в проверку, зарегистрирован ли человек.
|
||||
*/
|
||||
final class PasswordController extends Controller
|
||||
{
|
||||
public function showForgot(): Response
|
||||
{
|
||||
return $this->bare('auth/forgot', [], 'Восстановление пароля');
|
||||
}
|
||||
|
||||
public function forgot(Request $request): Response
|
||||
{
|
||||
$data = $this->validate($request, ['email' => 'required|email|max:191'], ['email' => 'Почта']);
|
||||
|
||||
// Форму сброса легко превратить в рассылку по чужим адресам —
|
||||
// ограничиваем частоту по адресу отправителя запроса
|
||||
$limiter = new RateLimiter();
|
||||
|
||||
if (!$limiter->attempt('forgot:' . $request->ip(), 5, 900)) {
|
||||
$this->flash('Слишком много запросов. Попробуйте через четверть часа', 'error');
|
||||
|
||||
return $this->redirect('password.forgot');
|
||||
}
|
||||
|
||||
$user = User::findBy('email', (string) $data['email']);
|
||||
|
||||
if ($user !== null && $user->isActive()) {
|
||||
$token = AuthToken::issue($user->id(), AuthToken::RESET, $request->ip());
|
||||
$link = rtrim((string) Config::get('app.url', ''), '/') . View::route('password.reset', ['token' => $token]);
|
||||
|
||||
Message::to((string) $user->email)
|
||||
->subject('Восстановление пароля — ' . (string) Config::get('app.name', 'Proton'))
|
||||
->view('mail/reset', ['user' => $user, 'link' => $link])
|
||||
->queue();
|
||||
|
||||
Audit::action('user', $user->id(), 'запрошено восстановление пароля');
|
||||
}
|
||||
|
||||
$this->flash('Если такой адрес зарегистрирован, письмо со ссылкой уже отправлено');
|
||||
|
||||
return $this->redirect('login');
|
||||
}
|
||||
|
||||
public function showReset(Request $request, string $token): Response
|
||||
{
|
||||
if (AuthToken::match($token, AuthToken::RESET) === null) {
|
||||
$this->flash('Ссылка недействительна или устарела', 'error');
|
||||
|
||||
return $this->redirect('password.forgot');
|
||||
}
|
||||
|
||||
return $this->bare('auth/reset', ['token' => $token], 'Новый пароль');
|
||||
}
|
||||
|
||||
public function reset(Request $request, string $token): Response
|
||||
{
|
||||
$found = AuthToken::match($token, AuthToken::RESET);
|
||||
|
||||
if ($found === null) {
|
||||
$this->flash('Ссылка недействительна или устарела', 'error');
|
||||
|
||||
return $this->redirect('password.forgot');
|
||||
}
|
||||
|
||||
$data = $this->validate($request, [
|
||||
'password' => 'required|min:' . (int) Config::get('auth.password_min', 6) . '|confirmed',
|
||||
], ['password' => 'Пароль']);
|
||||
|
||||
$user = $found->user();
|
||||
|
||||
if ($user === null) {
|
||||
$this->flash('Пользователь не найден', 'error');
|
||||
|
||||
return $this->redirect('login');
|
||||
}
|
||||
|
||||
$found->markUsed();
|
||||
|
||||
// setPassword заодно гасит все сеансы: если пароль восстанавливают,
|
||||
// старым входам доверять нельзя
|
||||
$user->setPassword((string) $data['password']);
|
||||
$user->save();
|
||||
|
||||
Audit::action('user', $user->id(), 'пароль восстановлен по ссылке из письма');
|
||||
|
||||
$this->flash('Пароль изменён, войдите с новым');
|
||||
|
||||
return $this->redirect('login');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controllers\Web;
|
||||
|
||||
use Rsgrinko\Proton\Auth\Auth;
|
||||
use Rsgrinko\Proton\Auth\Devices;
|
||||
use Rsgrinko\Proton\Http\Controller;
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\Models\User;
|
||||
use Rsgrinko\Proton\Support\Audit;
|
||||
use Rsgrinko\Proton\Support\Config;
|
||||
|
||||
/**
|
||||
* Свой профиль: имя, почта, пароль и список устройств.
|
||||
*
|
||||
* Открыт всем вошедшим — иначе человек без права users.manage не сменил бы
|
||||
* себе даже пароль.
|
||||
*/
|
||||
final class ProfileController extends Controller
|
||||
{
|
||||
public function show(User $user): Response
|
||||
{
|
||||
return $this->view('profile', [
|
||||
'active' => '',
|
||||
'user' => $user,
|
||||
'devices' => Devices::of($user->id()),
|
||||
], 'Профиль');
|
||||
}
|
||||
|
||||
/**
|
||||
* Имя и почта.
|
||||
*/
|
||||
public function update(Request $request, User $user): Response
|
||||
{
|
||||
$data = $this->validate($request, [
|
||||
'name' => 'nullable|max:191',
|
||||
'email' => 'nullable|email|max:191|unique:users,email,' . $user->id(),
|
||||
], ['name' => 'Имя', 'email' => 'Почта']);
|
||||
|
||||
$before = ['name' => $user->name, 'email' => $user->email];
|
||||
|
||||
$user->forceFill([
|
||||
'name' => (string) ($data['name'] ?? ''),
|
||||
'email' => (string) ($data['email'] ?? ''),
|
||||
])->save();
|
||||
|
||||
Audit::updated('user', $user->id(), 'изменён свой профиль', Audit::between($before, [
|
||||
'name' => $user->name,
|
||||
'email' => $user->email,
|
||||
]));
|
||||
|
||||
$this->flash('Профиль сохранён');
|
||||
|
||||
return $this->redirect('profile');
|
||||
}
|
||||
|
||||
/**
|
||||
* Смена своего пароля. Старый спрашиваем обязательно: чужой открытый
|
||||
* браузер не должен превращаться в захват аккаунта.
|
||||
*/
|
||||
public function password(Request $request, User $user): Response
|
||||
{
|
||||
$data = $this->validate($request, [
|
||||
'current' => 'required',
|
||||
'password' => 'required|min:' . (int) Config::get('auth.password_min', 6) . '|confirmed',
|
||||
], ['current' => 'Текущий пароль', 'password' => 'Новый пароль']);
|
||||
|
||||
if (!$user->verifyPassword((string) $data['current'])) {
|
||||
$this->flash('Текущий пароль неверен', 'error');
|
||||
|
||||
return $this->redirect('profile');
|
||||
}
|
||||
|
||||
$user->setPassword((string) $data['password']);
|
||||
$user->save();
|
||||
|
||||
// Смена пароля гасит все сеансы, включая свой, — этот оставляем в живых
|
||||
Auth::keepThisSession();
|
||||
|
||||
Audit::action('user', $user->id(), 'сменил себе пароль');
|
||||
|
||||
$this->flash('Пароль изменён, остальные устройства разлогинены');
|
||||
|
||||
return $this->redirect('profile');
|
||||
}
|
||||
|
||||
/**
|
||||
* Завершить одно устройство.
|
||||
*/
|
||||
public function revoke(Request $request, User $user): Response
|
||||
{
|
||||
$id = $request->text('device');
|
||||
|
||||
if (!Devices::revoke($user->id(), $id)) {
|
||||
$this->flash('Устройство не найдено', 'error');
|
||||
|
||||
return $this->redirect('profile');
|
||||
}
|
||||
|
||||
Audit::action('user', $user->id(), 'завершён сеанс устройства');
|
||||
|
||||
$this->flash('Сеанс завершён');
|
||||
|
||||
return $this->redirect('profile');
|
||||
}
|
||||
|
||||
/**
|
||||
* Выйти на остальных устройствах.
|
||||
*/
|
||||
public function revokeOthers(User $user): Response
|
||||
{
|
||||
$user->logoutEverywhere();
|
||||
|
||||
Auth::keepThisSession();
|
||||
|
||||
Audit::action('user', $user->id(), 'завершены сеансы на остальных устройствах');
|
||||
|
||||
$this->flash('На остальных устройствах придётся войти заново');
|
||||
|
||||
return $this->redirect('profile');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controllers\Web;
|
||||
|
||||
use Rsgrinko\Proton\Auth\Auth;
|
||||
use Rsgrinko\Proton\Database\Connection;
|
||||
use Rsgrinko\Proton\Events\Events;
|
||||
use Rsgrinko\Proton\Http\Controller;
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\Mail\Message;
|
||||
use Rsgrinko\Proton\Models\AuthToken;
|
||||
use Rsgrinko\Proton\Models\Role;
|
||||
use Rsgrinko\Proton\Models\User;
|
||||
use Rsgrinko\Proton\Support\Audit;
|
||||
use Rsgrinko\Proton\Support\Config;
|
||||
use Rsgrinko\Proton\View\View;
|
||||
|
||||
/**
|
||||
* Регистрация и подтверждение почты.
|
||||
*
|
||||
* Регистрацию можно закрыть настройкой AUTH_REGISTRATION — тогда пользователей
|
||||
* заводит только администратор. Подтверждение почты включается отдельно
|
||||
* (AUTH_VERIFY_EMAIL): без него человек пользуется сервисом сразу.
|
||||
*/
|
||||
final class RegisterController extends Controller
|
||||
{
|
||||
public function show(): Response
|
||||
{
|
||||
if (!$this->allowed()) {
|
||||
$this->flash('Регистрация закрыта', 'error');
|
||||
|
||||
return $this->redirect('login');
|
||||
}
|
||||
|
||||
return $this->bare('auth/register', [], 'Регистрация');
|
||||
}
|
||||
|
||||
public function store(Request $request): Response
|
||||
{
|
||||
if (!$this->allowed()) {
|
||||
$this->flash('Регистрация закрыта', 'error');
|
||||
|
||||
return $this->redirect('login');
|
||||
}
|
||||
|
||||
$data = $this->validate($request, [
|
||||
'login' => 'required|min:3|max:100|regex:/^[A-Za-z0-9._-]+$/|unique:users,login',
|
||||
'email' => 'required|email|max:191|unique:users,email',
|
||||
'name' => 'nullable|max:191',
|
||||
'password' => 'required|min:' . (int) Config::get('auth.password_min', 6) . '|confirmed',
|
||||
], [
|
||||
'login' => 'Логин',
|
||||
'email' => 'Почта',
|
||||
'name' => 'Имя',
|
||||
'password' => 'Пароль',
|
||||
]);
|
||||
|
||||
// Обычная роль: администратора выдаёт только другой администратор
|
||||
$role = Role::query()->where('is_system', 0)->first();
|
||||
|
||||
$user = User::register((string) $data['login'], (string) $data['password'], [
|
||||
'email' => (string) $data['email'],
|
||||
'name' => (string) ($data['name'] ?? $data['login']),
|
||||
'role_id' => $role?->id() ?? 0,
|
||||
]);
|
||||
|
||||
Audit::created('user', $user->id(), 'регистрация: ' . $user->login);
|
||||
Events::fire('user.registered', ['user' => $user]);
|
||||
|
||||
if ($this->verifyRequired()) {
|
||||
$this->sendVerification($user, $request->ip());
|
||||
|
||||
$this->flash('Мы отправили письмо на ' . (string) $user->email . '. Перейдите по ссылке из него, чтобы подтвердить адрес');
|
||||
|
||||
return $this->redirect('login');
|
||||
}
|
||||
|
||||
Auth::login($user, false);
|
||||
|
||||
$this->flash('Добро пожаловать!');
|
||||
|
||||
return $this->redirect('home');
|
||||
}
|
||||
|
||||
/**
|
||||
* Переход по ссылке из письма.
|
||||
*/
|
||||
public function verify(Request $request, string $token): Response
|
||||
{
|
||||
$found = AuthToken::match($token, AuthToken::VERIFY);
|
||||
|
||||
if ($found === null) {
|
||||
$this->flash('Ссылка недействительна или устарела. Попросите новую', 'error');
|
||||
|
||||
return $this->redirect('login');
|
||||
}
|
||||
|
||||
$user = $found->user();
|
||||
|
||||
if ($user === null) {
|
||||
$this->flash('Пользователь не найден', 'error');
|
||||
|
||||
return $this->redirect('login');
|
||||
}
|
||||
|
||||
$found->markUsed();
|
||||
|
||||
$user->forceFill(['email_verified_at' => Connection::now()])->save();
|
||||
|
||||
Audit::action('user', $user->id(), 'подтверждена почта ' . (string) $user->email);
|
||||
|
||||
Auth::login($user, false);
|
||||
|
||||
$this->flash('Почта подтверждена');
|
||||
|
||||
return $this->redirect('home');
|
||||
}
|
||||
|
||||
/**
|
||||
* Отправляет письмо со ссылкой подтверждения.
|
||||
*/
|
||||
private function sendVerification(User $user, string $ip): void
|
||||
{
|
||||
$token = AuthToken::issue($user->id(), AuthToken::VERIFY, $ip);
|
||||
|
||||
$link = rtrim((string) Config::get('app.url', ''), '/') . View::route('verify', ['token' => $token]);
|
||||
|
||||
// Через очередь: страница регистрации не должна ждать чужой SMTP
|
||||
Message::to((string) $user->email)
|
||||
->subject('Подтверждение адреса — ' . (string) Config::get('app.name', 'Proton'))
|
||||
->view('mail/verify', ['user' => $user, 'link' => $link])
|
||||
->queue();
|
||||
}
|
||||
|
||||
private function allowed(): bool
|
||||
{
|
||||
return (bool) Config::get('auth.registration', true);
|
||||
}
|
||||
|
||||
private function verifyRequired(): bool
|
||||
{
|
||||
return (bool) Config::get('auth.verify_email', false);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user