Compare commits
21 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| dedef454c8 | |||
| 42a1ca312f | |||
| ed9850c96f | |||
| e2a7c79245 | |||
| 561fbd22e0 | |||
| d31a63829c | |||
| f13ec7f29a | |||
| b44419aebd | |||
| da77b1f8da | |||
| b7c8d2ed80 | |||
| 42177555ac | |||
| e71bfa35dc | |||
| 711110c03b | |||
| a6e6cc9943 | |||
| ade031b0e7 | |||
| bda73e1662 | |||
| 14e0e875f1 | |||
| f24f35d0fc | |||
| 58c789d5f8 | |||
| b9e6060610 | |||
| c6bac33c71 |
@@ -4,6 +4,28 @@ NODE_ENV=production
|
||||
TRUST_PROXY=1
|
||||
SESSION_SECRET=change-me-to-a-long-random-string
|
||||
|
||||
# Единственный администратор (зарегистрированный пользователь с этим email)
|
||||
# При регистрации через сайт все получают роль customer; admin — только этот аккаунт
|
||||
ADMIN_EMAIL=admin@site.com
|
||||
ADMIN_PASSWORD=admin
|
||||
ADMIN_NAME=Администратор
|
||||
|
||||
# URL сайта (ссылки в письмах, WebAuthn origin)
|
||||
SITE_URL=http://localhost:3000
|
||||
|
||||
# Passkey (WebAuthn) — по умолчанию hostname из SITE_URL
|
||||
# WEBAUTHN_RP_ID=shop.example.com
|
||||
# WEBAUTHN_RP_NAME=Shop
|
||||
# WEBAUTHN_ORIGIN=https://shop.example.com,http://localhost:3000
|
||||
|
||||
# SMTP — сброс пароля и уведомления о брони
|
||||
SMTP_HOST=smtp.example.com
|
||||
SMTP_PORT=587
|
||||
SMTP_SECURE=false
|
||||
SMTP_USER=
|
||||
SMTP_PASS=
|
||||
SMTP_FROM=shop@example.com
|
||||
|
||||
# PostgreSQL 17 (одна строка или отдельные переменные)
|
||||
DATABASE_URL=postgresql://shop:shop@127.0.0.1:5432/shop
|
||||
# PGHOST=127.0.0.1
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
## 0.10.0
|
||||
|
||||
Первый стабильный релиз: **PostgreSQL 17**, два способа установки.
|
||||
|
||||
### Установка — Docker
|
||||
|
||||
```bash
|
||||
git checkout v0.10.0
|
||||
cp .env.docker.example .env
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
### Установка — без Docker (Ubuntu)
|
||||
|
||||
```bash
|
||||
git checkout v0.10.0
|
||||
bash scripts/setup-postgres-ubuntu.sh
|
||||
cp .env.example .env
|
||||
npm install --omit=dev
|
||||
systemctl enable --now shop
|
||||
```
|
||||
|
||||
### Что входит
|
||||
|
||||
- Каталог, корзина, регистрация, заказы
|
||||
- Docker Compose (app + postgres, опционально Caddy)
|
||||
- systemd + Caddy на хосте
|
||||
- `/health`, скрипты диагностики
|
||||
|
||||
Полная документация: [docs/RELEASE-0.10.md](docs/RELEASE-0.10.md)
|
||||
@@ -0,0 +1,29 @@
|
||||
## 0.20.0
|
||||
|
||||
Расширенный релиз: роли, админка, профиль, cookies, бронирование, email.
|
||||
|
||||
### Новое
|
||||
|
||||
- **Роли:** клиент (`customer`) и администратор (`admin`), вход `admin@site.com`
|
||||
- **Админ-панель:** заказы, пользователи, товары, бронирования
|
||||
- **Профиль:** просмотр, смена имени, email и пароля
|
||||
- **Cookies:** согласие обязательно для входа и регистрации
|
||||
- **Бронирование товаров** (48 ч) + письмо на email
|
||||
- **Сброс пароля** по ссылке из письма (SMTP)
|
||||
- **Wiki:** инструкции Docker и без Docker
|
||||
|
||||
### Настройка email (.env)
|
||||
|
||||
```env
|
||||
SITE_URL=https://ваш-сайт
|
||||
SMTP_HOST=...
|
||||
SMTP_FROM=...
|
||||
```
|
||||
|
||||
### Установка
|
||||
|
||||
```bash
|
||||
git checkout v0.20.0
|
||||
npm install --omit=dev
|
||||
# или docker compose up -d --build
|
||||
```
|
||||
@@ -1,5 +1,35 @@
|
||||
# Changelog
|
||||
|
||||
## [0.20.0] — 2026-05-17
|
||||
|
||||
### Роли и администрирование
|
||||
|
||||
- Роли `customer` и `admin`, админ-панель `/admin`
|
||||
- Администратор по умолчанию: `admin@site.com` (создаётся при старте)
|
||||
- Управление заказами, пользователями, товарами, бронированиями
|
||||
|
||||
### Личный кабинет
|
||||
|
||||
- Просмотр профиля, смена имени, email (с подтверждением пароля), пароля
|
||||
|
||||
### Cookies
|
||||
|
||||
- Баннер согласия; без принятия недоступны вход, регистрация, кабинет, оформление заказа
|
||||
- Политика: `/cookies/policy`
|
||||
|
||||
### Бронирование и почта
|
||||
|
||||
- Бронирование товара на 48 часов, уведомление на email
|
||||
- Сброс пароля: `/forgot-password`, ссылка в письме (nodemailer + SMTP)
|
||||
- Переменные: `SITE_URL`, `SMTP_*`
|
||||
|
||||
### Документация
|
||||
|
||||
- Wiki: установка Docker и без Docker
|
||||
- Скрипт `scripts/publish-gitea-release.sh`
|
||||
|
||||
[0.20.0]: https://git.evilfox.cc/test/shop10/releases/tag/v0.20.0
|
||||
|
||||
## [0.10.0] — 2026-05-17
|
||||
|
||||
Первый стабильный релиз с PostgreSQL 17. Два способа развёртывания: **Docker Compose** и **без Docker** (Ubuntu + systemd).
|
||||
|
||||
@@ -1,17 +1,22 @@
|
||||
# Shop
|
||||
|
||||
**v0.10.0** — интернет-магазин на **Node.js** и **PostgreSQL 17**.
|
||||
**v0.20.0** — интернет-магазин на **Node.js** и **PostgreSQL 17**.
|
||||
|
||||
Два способа установки: [Docker Compose](#docker-compose-рекомендуется-для-теста) | [без Docker (Ubuntu)](#postgresql-17-без-docker)
|
||||
|
||||
Подробности релиза: [CHANGELOG.md](CHANGELOG.md) · [docs/RELEASE-0.10.md](docs/RELEASE-0.10.md)
|
||||
Подробности релиза: [CHANGELOG.md](CHANGELOG.md) · [docs/RELEASE-0.20.md](docs/RELEASE-0.20.md)
|
||||
|
||||
**Сервер (установка, обновление, ошибки):** [wiki/Server-Operations.md](wiki/Server-Operations.md) · [wiki/Troubleshooting.md](wiki/Troubleshooting.md)
|
||||
|
||||
## Возможности
|
||||
|
||||
- Каталог товаров с категориями и поиском
|
||||
- Корзина и оформление заказа
|
||||
- Регистрация и вход пользователей
|
||||
- История заказов в личном кабинете
|
||||
- Регистрация, вход (пароль или passkey), сброс пароля по email
|
||||
- Личный кабинет: профиль, бронирования
|
||||
- Роли: клиент (`customer`) и **один** администратор (`admin`) — аккаунт из `ADMIN_EMAIL` в `.env`
|
||||
- Согласие на cookies
|
||||
- Подписка «сообщить о поступлении», если товара нет в наличии
|
||||
|
||||
## Требования
|
||||
|
||||
@@ -96,7 +101,7 @@ apt install -y postgresql-17 postgresql-client-17
|
||||
Пользователь и база `shop`:
|
||||
|
||||
```bash
|
||||
cd /opt/shop
|
||||
cd "$SHOP_ROOT"
|
||||
bash scripts/setup-postgres-ubuntu.sh
|
||||
```
|
||||
|
||||
@@ -108,34 +113,31 @@ bash scripts/setup-postgres-ubuntu.sh
|
||||
|
||||
## Быстрый развёртывание на Ubuntu
|
||||
|
||||
Подставьте **URL своего репозитория** и каталог клона `SHOP_ROOT` (часто `/opt/shop`):
|
||||
|
||||
```bash
|
||||
# 1. Система + Node.js 20
|
||||
apt update
|
||||
apt install -y git curl
|
||||
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
|
||||
apt install -y nodejs
|
||||
export SHOP_ROOT=/opt/shop
|
||||
export SHOP_GIT_URL='https://ваш-forge/пользователь/shop.git'
|
||||
|
||||
# 2. PostgreSQL 17
|
||||
apt install -y postgresql-17 postgresql-client-17
|
||||
|
||||
# 3. Код
|
||||
cd /opt
|
||||
git clone <URL_РЕПОЗИТОРИЯ> shop
|
||||
cd shop
|
||||
|
||||
# 4. БД
|
||||
bash scripts/setup-postgres-ubuntu.sh
|
||||
|
||||
# 5. Окружение
|
||||
cp .env.example .env
|
||||
sed -i "s/change-me-to-a-long-random-string/$(openssl rand -hex 32)/" .env
|
||||
# Проверьте DATABASE_URL в .env
|
||||
|
||||
# 6. Приложение
|
||||
npm install --omit=dev
|
||||
npm start
|
||||
apt update && apt install -y git curl
|
||||
git clone "$SHOP_GIT_URL" "$SHOP_ROOT"
|
||||
cd "$SHOP_ROOT"
|
||||
sudo SHOP_INSTALL_DIR="$SHOP_ROOT" SHOP_GIT_URL="$SHOP_GIT_URL" bash scripts/quick-deploy-ubuntu.sh
|
||||
```
|
||||
|
||||
**Обновление** (сайт уже работает) — **лучше так** (из любого каталога):
|
||||
|
||||
```bash
|
||||
export SHOP_ROOT=/opt/shop/shop10
|
||||
bash "$SHOP_ROOT/scripts/server-update.sh"
|
||||
```
|
||||
|
||||
`SHOP_ROOT` — путь к клону с `package.json` (у вас может быть `/opt/shop` вместо `/opt/shop/shop10`).
|
||||
|
||||
Не копируйте в shell шаблоны вроде `<URL_РЕПОЗИТОРИЯ>` — это подсказки в тексте, не команды.
|
||||
|
||||
Подробно: **[wiki/Server-Operations.md](wiki/Server-Operations.md)** (PostgreSQL PGDG, git, systemd, порт 3000).
|
||||
|
||||
Проверка:
|
||||
|
||||
```bash
|
||||
@@ -159,28 +161,31 @@ DATABASE_URL=postgresql://shop:shop@127.0.0.1:5432/shop
|
||||
| `DATABASE_URL` | Строка подключения PostgreSQL |
|
||||
| `PGHOST`, `PGPORT`, `PGUSER`, `PGPASSWORD`, `PGDATABASE` | Альтернатива `DATABASE_URL` |
|
||||
| `HOST` | `127.0.0.1` в production (доступ через Caddy) |
|
||||
| `ADMIN_EMAIL` | Email **единственного** администратора (создаётся/обновляется при старте) |
|
||||
| `ADMIN_PASSWORD` | Пароль администратора (только при первом создании аккаунта) |
|
||||
| `ADMIN_NAME` | Имя администратора |
|
||||
|
||||
### Роли и администратор
|
||||
|
||||
- Через **регистрацию** на сайте все пользователи получают роль **клиент** (`customer`).
|
||||
- **Один** зарегистрированный пользователь — **администратор**: аккаунт с email из `ADMIN_EMAIL` (по умолчанию `admin@site.com`). При старте приложения он создаётся, если ещё нет, или ему назначается роль `admin`.
|
||||
- Админ-панель: `/admin` (кнопка в шапке и в личном кабинете — только у администратора).
|
||||
- Сменить администратора: укажите другой email в `ADMIN_EMAIL` и перезапустите shop (прежние admin-аккаунты станут клиентами).
|
||||
|
||||
---
|
||||
|
||||
## Запуск как служба (systemd)
|
||||
|
||||
```bash
|
||||
cp /opt/shop/deploy/shop.service /etc/systemd/system/shop.service
|
||||
|
||||
cd /opt/shop
|
||||
cp .env.example .env # при первой установке
|
||||
# Заполните SESSION_SECRET и DATABASE_URL
|
||||
|
||||
npm install --omit=dev
|
||||
|
||||
# Не делайте chown -R www-data на весь /opt/shop (ломает git pull)
|
||||
systemctl daemon-reload
|
||||
systemctl enable shop
|
||||
systemctl start shop
|
||||
cd "$SHOP_ROOT"
|
||||
cp .env.example .env # при первой установке — SESSION_SECRET, DATABASE_URL
|
||||
sudo bash scripts/install-shop-service.sh
|
||||
journalctl -u shop -f
|
||||
```
|
||||
|
||||
`EnvironmentFile=/opt/shop/.env` должен содержать `DATABASE_URL`.
|
||||
Не делайте `chown -R www-data` на весь каталог репозитория (ломает `git pull`).
|
||||
|
||||
`EnvironmentFile` в unit должен указывать на `$SHOP_ROOT/.env` с `DATABASE_URL`.
|
||||
|
||||
---
|
||||
|
||||
@@ -199,18 +204,23 @@ journalctl -u shop -n 5 --no-pager
|
||||
|
||||
## Обновление на сервере (git pull)
|
||||
|
||||
См. **[wiki/Server-Operations.md](wiki/Server-Operations.md)**.
|
||||
|
||||
**Рекомендуемый способ** (надёжнее, чем вручную `cd` и `git pull`):
|
||||
|
||||
```bash
|
||||
cd /opt/shop
|
||||
git config --global --add safe.directory /opt/shop
|
||||
bash scripts/server-update.sh
|
||||
export SHOP_ROOT=/opt/shop/shop10
|
||||
bash "$SHOP_ROOT/scripts/server-update.sh"
|
||||
```
|
||||
|
||||
`WorkingDirectory` в `deploy/shop.service` должен совпадать с `$SHOP_ROOT`.
|
||||
|
||||
Скрипт: `git pull` → `npm install` → проверка PostgreSQL → `restart shop` → `curl /health` → `reload caddy`.
|
||||
|
||||
Вручную:
|
||||
|
||||
```bash
|
||||
cd /opt/shop
|
||||
cd "$SHOP_ROOT"
|
||||
git pull
|
||||
npm install --omit=dev
|
||||
systemctl restart shop
|
||||
@@ -220,50 +230,6 @@ systemctl reload caddy
|
||||
|
||||
---
|
||||
|
||||
## Переход с SQLite на PostgreSQL 17
|
||||
|
||||
Если сервер уже работал на старой версии (файлы `data/*.db`):
|
||||
|
||||
```bash
|
||||
# 1. PostgreSQL
|
||||
apt install -y postgresql-17 postgresql-client-17
|
||||
systemctl start postgresql
|
||||
|
||||
# 2. Код
|
||||
cd /opt/shop
|
||||
git config --global --add safe.directory /opt/shop
|
||||
git pull
|
||||
|
||||
# 3. База shop
|
||||
bash scripts/setup-postgres-ubuntu.sh
|
||||
|
||||
# 4. .env — обязательно DATABASE_URL
|
||||
cp -n .env.example .env
|
||||
nano .env
|
||||
# DATABASE_URL=postgresql://shop:shop@127.0.0.1:5432/shop
|
||||
# HOST=127.0.0.1
|
||||
# NODE_ENV=production
|
||||
# TRUST_PROXY=1
|
||||
|
||||
# 5. Зависимости и перезапуск
|
||||
npm install --omit=dev
|
||||
systemctl restart shop
|
||||
|
||||
# 6. Проверка
|
||||
curl -s http://127.0.0.1:3000/health
|
||||
systemctl reload caddy
|
||||
```
|
||||
|
||||
Каталог `data/` больше не используется. Демо-товары появятся при пустой таблице `products`. Аккаунты и заказы из SQLite не переносятся — нужна повторная регистрация или ручной импорт.
|
||||
|
||||
Проверка PostgreSQL:
|
||||
|
||||
```bash
|
||||
psql "postgresql://shop:shop@127.0.0.1:5432/shop" -c '\dt'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Caddy — SSL и reverse proxy
|
||||
|
||||
**Перед Caddy:** `curl http://127.0.0.1:3000/health` → OK.
|
||||
@@ -306,19 +272,17 @@ shop.example.com {
|
||||
**Быстрое исправление (одной командой):**
|
||||
|
||||
```bash
|
||||
cd /opt/shop
|
||||
git pull
|
||||
bash scripts/fix-db-connection.sh
|
||||
bash "$SHOP_ROOT/scripts/fix-db-connection.sh"
|
||||
```
|
||||
|
||||
**Вручную:**
|
||||
|
||||
```bash
|
||||
apt install -y postgresql-17 postgresql-client-17
|
||||
cd "$SHOP_ROOT"
|
||||
sudo bash scripts/install-postgresql-ubuntu.sh
|
||||
systemctl enable --now postgresql
|
||||
pg_isready -h 127.0.0.1 -p 5432
|
||||
|
||||
cd /opt/shop
|
||||
bash scripts/setup-postgres-ubuntu.sh
|
||||
nano .env # DATABASE_URL=postgresql://shop:shop@127.0.0.1:5432/shop
|
||||
|
||||
@@ -331,7 +295,7 @@ curl -s http://127.0.0.1:3000/health
|
||||
### HTTP 502
|
||||
|
||||
```bash
|
||||
bash /opt/shop/scripts/diagnose-502.sh
|
||||
bash "$SHOP_ROOT/scripts/diagnose-502.sh"
|
||||
journalctl -u shop -n 50 --no-pager
|
||||
```
|
||||
|
||||
@@ -374,18 +338,20 @@ caddy/Caddyfile.docker.example
|
||||
deploy/shop.service
|
||||
scripts/
|
||||
setup-postgres-ubuntu.sh
|
||||
install-postgresql-ubuntu.sh
|
||||
quick-deploy-ubuntu.sh
|
||||
fix-db-connection.sh
|
||||
diagnose-502.sh
|
||||
server-update.sh
|
||||
src/
|
||||
```
|
||||
|
||||
## Релиз 0.10.0
|
||||
## Релиз 0.20.0
|
||||
|
||||
```bash
|
||||
git clone <URL_РЕПОЗИТОРИЯ> shop
|
||||
cd shop
|
||||
git checkout v0.10.0
|
||||
git clone <URL-вашего-репозитория> /opt/shop
|
||||
cd /opt/shop
|
||||
git checkout v0.20.0
|
||||
```
|
||||
|
||||
| Способ | Команда |
|
||||
@@ -396,6 +362,6 @@ git checkout v0.10.0
|
||||
## Репозиторий
|
||||
|
||||
```bash
|
||||
git clone <URL_РЕПОЗИТОРИЯ> shop
|
||||
cd shop
|
||||
git clone <URL-вашего-репозитория> /opt/shop
|
||||
cd /opt/shop
|
||||
```
|
||||
|
||||
+7
-4
@@ -1,7 +1,7 @@
|
||||
[Unit]
|
||||
Description=Shop Node.js
|
||||
After=network.target postgresql.service
|
||||
Wants=postgresql.service
|
||||
After=network.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
@@ -9,12 +9,15 @@ User=www-data
|
||||
Group=www-data
|
||||
WorkingDirectory=/opt/shop
|
||||
EnvironmentFile=/opt/shop/.env
|
||||
# Дождаться PostgreSQL (запуск от root, +)
|
||||
ExecStartPre=+/bin/bash -c 'for i in $(seq 1 60); do pg_isready -h 127.0.0.1 -p 5432 -q && exit 0; sleep 1; done; echo "PostgreSQL не отвечает на 127.0.0.1:5432"; exit 1'
|
||||
ExecStartPre=+/opt/shop/scripts/wait-postgres.sh
|
||||
ExecStart=/usr/bin/node src/server.js
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
|
||||
# Логи в journal
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
|
||||
UMask=0022
|
||||
|
||||
[Install]
|
||||
|
||||
+18
-4
@@ -5,7 +5,7 @@
|
||||
## Вариант A — Docker Compose
|
||||
|
||||
```bash
|
||||
git clone <URL_РЕПОЗИТОРИЯ> shop && cd shop
|
||||
git clone https://git.evilfox.cc/test/shop10.git /opt/shop/shop10 && cd /opt/shop/shop10
|
||||
git checkout v0.10.0
|
||||
|
||||
cp .env.docker.example .env
|
||||
@@ -27,7 +27,7 @@ docker compose --profile proxy up -d --build
|
||||
## Вариант B — без Docker (Ubuntu)
|
||||
|
||||
```bash
|
||||
git clone <URL_РЕПОЗИТОРИЯ> shop && cd shop
|
||||
git clone https://git.evilfox.cc/test/shop10.git /opt/shop/shop10 && cd /opt/shop/shop10
|
||||
git checkout v0.10.0
|
||||
|
||||
apt install -y git curl
|
||||
@@ -50,12 +50,26 @@ Caddy на хосте — см. `README.md`, раздел «Caddy».
|
||||
|
||||
## Обновление с более ранних версий
|
||||
|
||||
- С **SQLite**: раздел «Переход с SQLite на PostgreSQL 17» в README
|
||||
- С **0.10-beta**: `git pull`, `npm install`, `systemctl restart shop`
|
||||
|
||||
## Тег
|
||||
## Тег и Release в Gitea
|
||||
|
||||
Тег уже в репозитории:
|
||||
|
||||
```bash
|
||||
git fetch --tags
|
||||
git checkout v0.10.0
|
||||
```
|
||||
|
||||
**Release на сайте Gitea** (раздел Releases, не только Tags):
|
||||
|
||||
1. Откройте: `https://git.evilfox.cc/test/shop10/releases/new`
|
||||
2. Tag: `v0.10.0`, Title: `0.10.0`
|
||||
3. Описание — из файла `.release-notes/v0.10.0.md`
|
||||
|
||||
Или из CLI (нужен токен):
|
||||
|
||||
```bash
|
||||
export GITEA_TOKEN=ваш_токен
|
||||
bash scripts/publish-gitea-release.sh 0.10.0
|
||||
```
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
# Релиз 0.20.0
|
||||
|
||||
## Что нового относительно 0.10.0
|
||||
|
||||
| Функция | Описание |
|
||||
|---------|----------|
|
||||
| Админ-панель | `/admin` — статистика, заказы, пользователи, товары, брони |
|
||||
| Роли | `customer`, `admin` |
|
||||
| Профиль | `/account` — имя, email, пароль |
|
||||
| Cookies | Баннер согласия, блок входа без принятия |
|
||||
| Бронирование | Кнопка на товаре, вкладка в кабинете |
|
||||
| Сброс пароля | `/forgot-password` → письмо → новый пароль |
|
||||
|
||||
## Быстрый старт
|
||||
|
||||
### Docker
|
||||
|
||||
```bash
|
||||
git checkout v0.20.0
|
||||
cp .env.docker.example .env
|
||||
# SESSION_SECRET, при необходимости SMTP и SITE_URL
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
### Ubuntu
|
||||
|
||||
```bash
|
||||
git checkout v0.20.0
|
||||
bash scripts/setup-postgres-ubuntu.sh
|
||||
cp .env.example .env
|
||||
npm install --omit=dev
|
||||
systemctl restart shop
|
||||
```
|
||||
|
||||
## Администратор по умолчанию
|
||||
|
||||
- Email: `admin@site.com`
|
||||
- Пароль: `admin` (смените в production)
|
||||
|
||||
## SMTP (письма)
|
||||
|
||||
Обязательно для production-сброса пароля. Без SMTP ссылка выводится в лог сервера.
|
||||
|
||||
```env
|
||||
SITE_URL=https://shop.example.com
|
||||
SMTP_HOST=smtp.example.com
|
||||
SMTP_PORT=587
|
||||
SMTP_USER=...
|
||||
SMTP_PASS=...
|
||||
SMTP_FROM=shop@example.com
|
||||
```
|
||||
|
||||
## Gitea Release
|
||||
|
||||
```bash
|
||||
export GITEA_TOKEN=...
|
||||
bash scripts/publish-gitea-release.sh 0.20.0
|
||||
```
|
||||
+5
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "shop",
|
||||
"version": "0.10.0",
|
||||
"version": "0.20.0",
|
||||
"description": "Интернет-магазин на Node.js с PostgreSQL 17",
|
||||
"main": "src/server.js",
|
||||
"scripts": {
|
||||
@@ -13,10 +13,13 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"bcryptjs": "^2.4.3",
|
||||
"cookie-parser": "^1.4.7",
|
||||
"connect-pg-simple": "^10.0.0",
|
||||
"ejs": "^3.1.10",
|
||||
"express": "^4.21.2",
|
||||
"express-session": "^1.18.1",
|
||||
"pg": "^8.13.1"
|
||||
"nodemailer": "^6.9.16",
|
||||
"pg": "^8.13.1",
|
||||
"@simplewebauthn/server": "^13.1.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,9 +5,13 @@ CREATE TABLE IF NOT EXISTS users (
|
||||
email TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
role TEXT NOT NULL DEFAULT 'customer'
|
||||
CHECK (role IN ('customer', 'admin')),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_users_role ON users(role);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS categories (
|
||||
id SERIAL PRIMARY KEY,
|
||||
slug TEXT NOT NULL UNIQUE,
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
-- Роли пользователей (миграция для существующих БД)
|
||||
ALTER TABLE users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'customer';
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint WHERE conname = 'users_role_check'
|
||||
) THEN
|
||||
ALTER TABLE users ADD CONSTRAINT users_role_check
|
||||
CHECK (role IN ('customer', 'admin'));
|
||||
END IF;
|
||||
END $$;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_users_role ON users(role);
|
||||
@@ -0,0 +1,28 @@
|
||||
-- Бронирование товаров
|
||||
CREATE TABLE IF NOT EXISTS reservations (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
product_id INTEGER NOT NULL REFERENCES products(id) ON DELETE CASCADE,
|
||||
quantity INTEGER NOT NULL CHECK (quantity > 0),
|
||||
status TEXT NOT NULL DEFAULT 'active'
|
||||
CHECK (status IN ('active', 'fulfilled', 'cancelled', 'expired')),
|
||||
expires_at TIMESTAMPTZ NOT NULL DEFAULT (NOW() + INTERVAL '48 hours'),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_reservations_user ON reservations(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_reservations_product ON reservations(product_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_reservations_status ON reservations(status);
|
||||
|
||||
-- Сброс пароля
|
||||
CREATE TABLE IF NOT EXISTS password_reset_tokens (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
token_hash TEXT NOT NULL,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
used_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_password_reset_user ON password_reset_tokens(user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_password_reset_expires ON password_reset_tokens(expires_at);
|
||||
@@ -0,0 +1,17 @@
|
||||
-- Passkey (WebAuthn) — опциональный вход вместо пароля
|
||||
ALTER TABLE users ADD COLUMN IF NOT EXISTS passkey_enabled BOOLEAN NOT NULL DEFAULT false;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS webauthn_credentials (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
credential_id TEXT NOT NULL UNIQUE,
|
||||
public_key BYTEA NOT NULL,
|
||||
counter BIGINT NOT NULL DEFAULT 0,
|
||||
device_type VARCHAR(32),
|
||||
backed_up BOOLEAN NOT NULL DEFAULT false,
|
||||
transports TEXT,
|
||||
label TEXT NOT NULL DEFAULT 'Passkey',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_webauthn_credentials_user_id ON webauthn_credentials(user_id);
|
||||
@@ -0,0 +1,14 @@
|
||||
-- Подписка «сообщить о поступлении»
|
||||
CREATE TABLE IF NOT EXISTS product_stock_alerts (
|
||||
id SERIAL PRIMARY KEY,
|
||||
product_id INTEGER NOT NULL REFERENCES products(id) ON DELETE CASCADE,
|
||||
email TEXT NOT NULL,
|
||||
user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
notified_at TIMESTAMPTZ,
|
||||
UNIQUE (product_id, email)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_stock_alerts_product_pending
|
||||
ON product_stock_alerts (product_id)
|
||||
WHERE notified_at IS NULL;
|
||||
@@ -2,7 +2,9 @@
|
||||
# Диагностика HTTP 502 (Caddy не достучался до Node / БД)
|
||||
set -e
|
||||
|
||||
echo "=== Shop / Caddy 502 diagnostic ==="
|
||||
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/shop-root.sh" 2>/dev/null || SHOP_ROOT=/opt/shop
|
||||
|
||||
echo "=== Shop / Caddy 502 diagnostic ($SHOP_ROOT) ==="
|
||||
echo
|
||||
|
||||
echo "1. PostgreSQL"
|
||||
@@ -40,11 +42,11 @@ fi
|
||||
echo
|
||||
|
||||
echo "6. .env"
|
||||
if [ -f /opt/shop/.env ]; then
|
||||
grep -E '^(DATABASE_URL|HOST|PORT)=' /opt/shop/.env 2>/dev/null | sed 's/=.*/=***/' || true
|
||||
grep -E '^DATABASE_URL=' /opt/shop/.env || echo " DATABASE_URL не задан"
|
||||
if [ -f "$SHOP_ROOT/.env" ]; then
|
||||
grep -E '^(DATABASE_URL|HOST|PORT)=' "$SHOP_ROOT/.env" 2>/dev/null | sed 's/=.*/=***/' || true
|
||||
grep -E '^DATABASE_URL=' "$SHOP_ROOT/.env" || echo " DATABASE_URL не задан"
|
||||
else
|
||||
echo " /opt/shop/.env не найден"
|
||||
echo " $SHOP_ROOT/.env не найден"
|
||||
fi
|
||||
echo
|
||||
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
#!/bin/bash
|
||||
# Диагностика службы shop
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
source "$SCRIPT_DIR/shop-root.sh"
|
||||
|
||||
echo "=== Диагностика shop.service ==="
|
||||
echo "SHOP_ROOT=$SHOP_ROOT"
|
||||
echo
|
||||
|
||||
echo "1. Unit"
|
||||
systemctl cat shop.service 2>/dev/null | head -25 || echo " shop.service не найден"
|
||||
echo
|
||||
|
||||
echo "2. PostgreSQL"
|
||||
systemctl is-active postgresql 2>/dev/null || systemctl is-active 'postgresql@*' 2>/dev/null || echo " postgresql: не active"
|
||||
pg_isready -q 2>/dev/null && echo " pg_isready (socket): OK" || echo " pg_isready (socket): FAIL"
|
||||
pg_isready -h 127.0.0.1 -p 5432 -q 2>/dev/null && echo " pg_isready 127.0.0.1: OK" || echo " pg_isready 127.0.0.1: FAIL"
|
||||
echo
|
||||
|
||||
echo "3. .env"
|
||||
if [ -f "$SHOP_ROOT/.env" ]; then
|
||||
ls -la "$SHOP_ROOT/.env"
|
||||
grep -E '^(DATABASE_URL|HOST|PORT|NODE_ENV)=' "$SHOP_ROOT/.env" | sed 's/=.*/=***/' || true
|
||||
else
|
||||
echo " .env не найден"
|
||||
fi
|
||||
echo
|
||||
|
||||
echo "4. Порт 3000"
|
||||
ss -tlnp | grep ':3000' || echo " порт 3000 свободен"
|
||||
echo
|
||||
|
||||
echo "5. www-data доступ"
|
||||
sudo -u www-data test -r "$SHOP_ROOT/package.json" && echo " package.json: OK" || echo " package.json: FAIL"
|
||||
sudo -u www-data test -x "$SHOP_ROOT" && echo " каталог: OK" || echo " каталог: FAIL"
|
||||
echo
|
||||
|
||||
echo "6. Тест Node (5 сек)"
|
||||
set +e
|
||||
timeout 8 sudo -u www-data bash -c "cd '$SHOP_ROOT' && set -a && source .env 2>/dev/null && set +a && node src/server.js" 2>&1 | head -20
|
||||
set -e
|
||||
echo
|
||||
|
||||
echo "7. journalctl shop"
|
||||
journalctl -u shop -n 30 --no-pager 2>/dev/null || true
|
||||
@@ -2,29 +2,30 @@
|
||||
# Быстрое исправление ECONNREFUSED 127.0.0.1:5432
|
||||
set -euo pipefail
|
||||
|
||||
cd /opt/shop 2>/dev/null || cd "$(dirname "$0")/.."
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
source "$SCRIPT_DIR/shop-root.sh"
|
||||
|
||||
echo "=== Исправление подключения к PostgreSQL ==="
|
||||
echo "=== Исправление подключения к PostgreSQL ($SHOP_ROOT) ==="
|
||||
|
||||
if ! dpkg -l | grep -q postgresql; then
|
||||
echo "Установка PostgreSQL 17..."
|
||||
apt update
|
||||
apt install -y postgresql-17 postgresql-client-17 || {
|
||||
echo "Если пакет не найден — см. README (репозиторий PGDG)"
|
||||
exit 1
|
||||
}
|
||||
if ! command -v psql >/dev/null; then
|
||||
bash "$SCRIPT_DIR/install-postgresql-ubuntu.sh"
|
||||
fi
|
||||
|
||||
bash scripts/setup-postgres-ubuntu.sh
|
||||
bash "$SCRIPT_DIR/setup-postgres-ubuntu.sh"
|
||||
|
||||
if [ -f .env ] && ! grep -q '^DATABASE_URL=' .env; then
|
||||
echo "DATABASE_URL=postgresql://shop:shop@127.0.0.1:5432/shop" >> .env
|
||||
echo 'DATABASE_URL=postgresql://shop:shop@127.0.0.1:5432/shop' >> .env
|
||||
echo "Добавлен DATABASE_URL в .env"
|
||||
fi
|
||||
|
||||
cp -f deploy/shop.service /etc/systemd/system/shop.service
|
||||
systemctl daemon-reload
|
||||
systemctl restart shop
|
||||
if [ -f deploy/shop.service ]; then
|
||||
cp -f deploy/shop.service /etc/systemd/system/shop.service
|
||||
sed -i "s|WorkingDirectory=.*|WorkingDirectory=${SHOP_ROOT}|" /etc/systemd/system/shop.service
|
||||
sed -i "s|EnvironmentFile=.*|EnvironmentFile=${SHOP_ROOT}/.env|" /etc/systemd/system/shop.service
|
||||
systemctl daemon-reload
|
||||
fi
|
||||
|
||||
systemctl restart shop 2>/dev/null || true
|
||||
sleep 2
|
||||
|
||||
if curl -sf http://127.0.0.1:3000/health; then
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/bin/bash
|
||||
# Освободить порт 3000 (ручной npm start / старый процесс)
|
||||
set -euo pipefail
|
||||
|
||||
PORT="${1:-3000}"
|
||||
|
||||
if ! command -v ss >/dev/null; then
|
||||
echo "ss не найден"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if ! ss -tlnp | grep -q ":${PORT} "; then
|
||||
echo "Порт ${PORT} свободен"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "Порт ${PORT} занят:"
|
||||
ss -tlnp | grep ":${PORT} " || true
|
||||
|
||||
if command -v fuser >/dev/null; then
|
||||
echo "Останавливаем процессы на ${PORT}/tcp..."
|
||||
fuser -k "${PORT}/tcp" 2>/dev/null || true
|
||||
sleep 2
|
||||
fi
|
||||
|
||||
if ss -tlnp | grep -q ":${PORT} "; then
|
||||
echo "Порт ${PORT} всё ещё занят — остановите процесс вручную"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Порт ${PORT} свободен"
|
||||
@@ -0,0 +1,38 @@
|
||||
#!/bin/bash
|
||||
# Синхронизация с origin/main (исправляет detached HEAD)
|
||||
set -euo pipefail
|
||||
|
||||
source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/shop-root.sh"
|
||||
|
||||
if [ ! -d .git ]; then
|
||||
echo "Ошибка: в $SHOP_ROOT нет .git — нужен полный clone:"
|
||||
echo " git clone <URL-репозитория> /opt/shop"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
git config --global --add safe.directory "$SHOP_ROOT" 2>/dev/null || true
|
||||
|
||||
echo "=== git sync: $SHOP_ROOT ==="
|
||||
git fetch origin
|
||||
|
||||
if git symbolic-ref -q HEAD >/dev/null 2>&1; then
|
||||
BRANCH=$(git branch --show-current)
|
||||
echo "Текущая ветка: ${BRANCH:-?}"
|
||||
else
|
||||
echo "Состояние: detached HEAD ($(git rev-parse --short HEAD))"
|
||||
BRANCH=""
|
||||
fi
|
||||
|
||||
if [ "$BRANCH" != "main" ]; then
|
||||
if git show-ref --verify --quiet refs/remotes/origin/main; then
|
||||
git checkout -B main origin/main
|
||||
elif git show-ref --verify --quiet refs/heads/main; then
|
||||
git checkout main
|
||||
else
|
||||
echo "Ветка main не найдена на origin"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
git pull origin main
|
||||
echo "OK: $(git log -1 --oneline)"
|
||||
@@ -0,0 +1,59 @@
|
||||
#!/bin/bash
|
||||
# Установка PostgreSQL 17 (PGDG) или postgresql из Ubuntu
|
||||
# sudo bash scripts/install-postgresql-ubuntu.sh
|
||||
set -euo pipefail
|
||||
|
||||
if command -v psql >/dev/null; then
|
||||
echo "PostgreSQL уже установлен: $(psql --version | head -1)"
|
||||
systemctl enable postgresql 2>/dev/null || true
|
||||
systemctl start postgresql 2>/dev/null || true
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "=== Установка PostgreSQL ==="
|
||||
apt update
|
||||
apt install -y curl ca-certificates gnupg lsb-release
|
||||
|
||||
if [ ! -f /etc/os-release ]; then
|
||||
echo "Ошибка: не найден /etc/os-release"
|
||||
exit 1
|
||||
fi
|
||||
# shellcheck source=/dev/null
|
||||
. /etc/os-release
|
||||
CODENAME="${VERSION_CODENAME:-}"
|
||||
if [ -z "$CODENAME" ]; then
|
||||
echo "Ошибка: не удалось определить VERSION_CODENAME (Ubuntu/Debian?)"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
install -d /usr/share/postgresql-common/pgdg
|
||||
curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc \
|
||||
-o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc
|
||||
|
||||
echo "deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://apt.postgresql.org/pub/repos/apt ${CODENAME}-pgdg main" \
|
||||
> /etc/apt/sources.list.d/pgdg.list
|
||||
|
||||
apt update
|
||||
|
||||
if apt install -y postgresql-17 postgresql-client-17; then
|
||||
echo "Установлен PostgreSQL 17 (PGDG)"
|
||||
else
|
||||
echo "Пакет postgresql-17 недоступен — устанавливаем postgresql из репозитория Ubuntu..."
|
||||
apt install -y postgresql postgresql-contrib
|
||||
fi
|
||||
|
||||
systemctl enable postgresql
|
||||
systemctl start postgresql
|
||||
|
||||
for i in $(seq 1 30); do
|
||||
if pg_isready -h 127.0.0.1 -p 5432 -q 2>/dev/null; then
|
||||
echo "pg_isready: OK"
|
||||
psql --version | head -1
|
||||
exit 0
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
echo "PostgreSQL установлен, но не отвечает на 127.0.0.1:5432"
|
||||
echo " journalctl -u postgresql -n 30 --no-pager"
|
||||
exit 1
|
||||
@@ -0,0 +1,112 @@
|
||||
#!/bin/bash
|
||||
# Установка systemd-службы shop (после git clone и .env)
|
||||
# sudo bash scripts/install-shop-service.sh
|
||||
set -euo pipefail
|
||||
|
||||
if [ "$(id -u)" -ne 0 ]; then
|
||||
echo "Запустите от root: sudo bash scripts/install-shop-service.sh"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
source "$SCRIPT_DIR/shop-root.sh"
|
||||
|
||||
echo "=== Установка службы shop ==="
|
||||
echo "Каталог: $SHOP_ROOT"
|
||||
|
||||
if [ ! -f "$SHOP_ROOT/package.json" ]; then
|
||||
echo "Ошибка: нет package.json в $SHOP_ROOT"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# .env в родительском каталоге (если переносили клон)
|
||||
PARENT_ENV="$(dirname "$SHOP_ROOT")/.env"
|
||||
if [ ! -f "$SHOP_ROOT/.env" ] && [ -f "$PARENT_ENV" ]; then
|
||||
cp "$PARENT_ENV" "$SHOP_ROOT/.env"
|
||||
echo "Скопирован .env из $(dirname "$SHOP_ROOT")"
|
||||
fi
|
||||
|
||||
if [ ! -f "$SHOP_ROOT/.env" ]; then
|
||||
if [ -f "$SHOP_ROOT/.env.example" ]; then
|
||||
cp "$SHOP_ROOT/.env.example" "$SHOP_ROOT/.env"
|
||||
if command -v openssl >/dev/null; then
|
||||
sed -i "s/change-me-to-a-long-random-string/$(openssl rand -hex 32)/" "$SHOP_ROOT/.env"
|
||||
fi
|
||||
echo "Создан .env — проверьте DATABASE_URL"
|
||||
else
|
||||
echo "Ошибка: нет .env"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
if ! grep -q '^DATABASE_URL=' "$SHOP_ROOT/.env"; then
|
||||
echo "Добавляю DATABASE_URL по умолчанию..."
|
||||
echo 'DATABASE_URL=postgresql://shop:shop@127.0.0.1:5432/shop' >> "$SHOP_ROOT/.env"
|
||||
fi
|
||||
|
||||
NODE_BIN=$(command -v node)
|
||||
echo "Node: $NODE_BIN ($($NODE_BIN -v))"
|
||||
|
||||
chmod +x "$SHOP_ROOT/scripts/wait-postgres.sh" 2>/dev/null || true
|
||||
|
||||
if command -v pg_isready >/dev/null; then
|
||||
bash "$SCRIPT_DIR/install-postgresql-ubuntu.sh" 2>/dev/null || true
|
||||
systemctl enable postgresql 2>/dev/null || true
|
||||
systemctl start postgresql 2>/dev/null || true
|
||||
bash "$SCRIPT_DIR/setup-postgres-ubuntu.sh" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
npm install --omit=dev --prefix "$SHOP_ROOT"
|
||||
|
||||
# Доступ www-data: чтение кода и .env (systemd читает .env от root, но на всякий случай)
|
||||
chmod o+x /opt /opt/shop 2>/dev/null || true
|
||||
chmod -R a+rX "$SHOP_ROOT"
|
||||
chmod 640 "$SHOP_ROOT/.env"
|
||||
chown root:www-data "$SHOP_ROOT/.env" 2>/dev/null || chmod 644 "$SHOP_ROOT/.env"
|
||||
|
||||
cp -f "$SHOP_ROOT/deploy/shop.service" /etc/systemd/system/shop.service
|
||||
sed -i "s|WorkingDirectory=.*|WorkingDirectory=${SHOP_ROOT}|" /etc/systemd/system/shop.service
|
||||
sed -i "s|EnvironmentFile=.*|EnvironmentFile=${SHOP_ROOT}/.env|" /etc/systemd/system/shop.service
|
||||
sed -i "s|ExecStartPre=.*|ExecStartPre=+${SHOP_ROOT}/scripts/wait-postgres.sh|" /etc/systemd/system/shop.service
|
||||
sed -i "s|ExecStart=.*|ExecStart=${NODE_BIN} src/server.js|" /etc/systemd/system/shop.service
|
||||
|
||||
if ! sudo -u www-data test -r "$SHOP_ROOT/package.json"; then
|
||||
echo "Ошибка: www-data не читает $SHOP_ROOT"
|
||||
ls -la "$SHOP_ROOT" | head -5
|
||||
exit 1
|
||||
fi
|
||||
|
||||
systemctl daemon-reload
|
||||
systemctl enable shop
|
||||
|
||||
systemctl stop shop 2>/dev/null || true
|
||||
bash "$SCRIPT_DIR/free-port-3000.sh" 3000
|
||||
|
||||
echo "Запуск shop..."
|
||||
if ! systemctl restart shop; then
|
||||
echo ""
|
||||
echo "=== Ошибка запуска — лог ==="
|
||||
journalctl -u shop -n 40 --no-pager
|
||||
echo ""
|
||||
bash "$SCRIPT_DIR/diagnose-shop-service.sh" || true
|
||||
exit 1
|
||||
fi
|
||||
|
||||
sleep 3
|
||||
|
||||
if ! systemctl is-active --quiet shop; then
|
||||
echo "shop.service не в состоянии active"
|
||||
journalctl -u shop -n 40 --no-pager
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if curl -sf http://127.0.0.1:3000/health; then
|
||||
echo ""
|
||||
echo "OK — служба shop запущена (systemd active)"
|
||||
systemctl status shop --no-pager | head -15
|
||||
systemctl reload caddy 2>/dev/null || true
|
||||
else
|
||||
echo "health не отвечает"
|
||||
journalctl -u shop -n 40 --no-pager
|
||||
exit 1
|
||||
fi
|
||||
@@ -0,0 +1,55 @@
|
||||
#!/bin/bash
|
||||
# Публикация Release в Gitea (не только git tag)
|
||||
# Использование:
|
||||
# export GITEA_TOKEN=ваш_токен # Настройки → Приложения → Токен доступа
|
||||
# bash scripts/publish-gitea-release.sh 0.10.0
|
||||
set -euo pipefail
|
||||
|
||||
VERSION="${1:-0.10.0}"
|
||||
TAG="v${VERSION#v}"
|
||||
GITEA_URL="${GITEA_URL:-https://git.evilfox.cc}"
|
||||
OWNER="${GITEA_OWNER:-test}"
|
||||
REPO="${GITEA_REPO:-shop10}"
|
||||
|
||||
if [ -z "${GITEA_TOKEN:-}" ]; then
|
||||
echo "Задайте GITEA_TOKEN (токен с правом write:repository)"
|
||||
echo " export GITEA_TOKEN=..."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
NOTES_FILE="$(dirname "$0")/../.release-notes/${TAG}.md"
|
||||
if [ ! -f "$NOTES_FILE" ]; then
|
||||
NOTES_FILE="$(dirname "$0")/../CHANGELOG.md"
|
||||
fi
|
||||
|
||||
BODY=$(sed -n "/## \[${VERSION#v}\]/,/^## \[/p" "$NOTES_FILE" 2>/dev/null | sed '$d' || cat "$NOTES_FILE")
|
||||
if [ -z "$BODY" ]; then
|
||||
BODY="Release ${TAG} — см. CHANGELOG.md"
|
||||
fi
|
||||
|
||||
# Экранирование JSON
|
||||
BODY_JSON=$(printf '%s' "$BODY" | python3 -c 'import json,sys; print(json.dumps(sys.stdin.read()))')
|
||||
|
||||
HTTP=$(curl -sS -o /tmp/gitea-release.json -w "%{http_code}" -X POST \
|
||||
"${GITEA_URL}/api/v1/repos/${OWNER}/${REPO}/releases" \
|
||||
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"tag_name\":\"${TAG}\",\"name\":\"${VERSION#v}\",\"body\":${BODY_JSON},\"target_commitish\":\"main\",\"prerelease\":false}")
|
||||
|
||||
if [ "$HTTP" = "201" ]; then
|
||||
echo "Release создан: ${GITEA_URL}/${OWNER}/${REPO}/releases/tag/${TAG}"
|
||||
cat /tmp/gitea-release.json | python3 -m json.tool 2>/dev/null || cat /tmp/gitea-release.json
|
||||
elif [ "$HTTP" = "409" ]; then
|
||||
echo "Release ${TAG} уже существует — обновление..."
|
||||
RELEASE_ID=$(curl -sS "${GITEA_URL}/api/v1/repos/${OWNER}/${REPO}/releases/tags/${TAG}" \
|
||||
-H "Authorization: token ${GITEA_TOKEN}" | python3 -c "import json,sys; print(json.load(sys.stdin)['id'])")
|
||||
curl -sS -X PATCH "${GITEA_URL}/api/v1/repos/${OWNER}/${REPO}/releases/${RELEASE_ID}" \
|
||||
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "{\"name\":\"${VERSION#v}\",\"body\":${BODY_JSON}}" | python3 -m json.tool
|
||||
echo "Обновлено: ${GITEA_URL}/${OWNER}/${REPO}/releases/tag/${TAG}"
|
||||
else
|
||||
echo "Ошибка HTTP ${HTTP}"
|
||||
cat /tmp/gitea-release.json
|
||||
exit 1
|
||||
fi
|
||||
@@ -0,0 +1,67 @@
|
||||
#!/bin/bash
|
||||
# Публикация wiki/ в Gitea Wiki
|
||||
#
|
||||
# Способ 1 — токен (рекомендуется):
|
||||
# export GITEA_TOKEN=ваш_токен
|
||||
#
|
||||
# Способ 2 — логин и пароль (не передавайте в чат, только в терминале):
|
||||
# export GITEA_USER=логин
|
||||
# export GITEA_PASSWORD=пароль
|
||||
#
|
||||
# bash scripts/push-wiki.sh
|
||||
set -euo pipefail
|
||||
|
||||
GITEA_WIKI_URL="${GITEA_WIKI_URL:-https://git.evilfox.cc/test/shop10.wiki.git}"
|
||||
REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
WIKI_SRC="${REPO_ROOT}/wiki"
|
||||
TMPDIR="${TMPDIR:-/tmp}/shop-wiki-$$"
|
||||
|
||||
if [ ! -d "$WIKI_SRC" ]; then
|
||||
echo "Нет каталога wiki/"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "${GITEA_TOKEN:-}" ] && { [ -z "${GITEA_USER:-}" ] || [ -z "${GITEA_PASSWORD:-}" ]; }; then
|
||||
echo "Задайте GITEA_TOKEN или пару GITEA_USER + GITEA_PASSWORD"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cleanup() { rm -rf "$TMPDIR"; }
|
||||
trap cleanup EXIT
|
||||
|
||||
HOST_PATH="${GITEA_WIKI_URL#https://}"
|
||||
HOST_PATH="${HOST_PATH#http://}"
|
||||
|
||||
if [ -n "${GITEA_TOKEN:-}" ]; then
|
||||
CLONE_URL="https://${GITEA_TOKEN}@${HOST_PATH}"
|
||||
else
|
||||
# URL-encode не делаем — пароль без спецсимволов; иначе используйте токен
|
||||
CLONE_URL="https://${GITEA_USER}:${GITEA_PASSWORD}@${HOST_PATH}"
|
||||
fi
|
||||
|
||||
mkdir -p "$TMPDIR"
|
||||
cd "$TMPDIR"
|
||||
|
||||
if git clone "$CLONE_URL" . 2>/dev/null; then
|
||||
echo "Wiki репозиторий склонирован."
|
||||
else
|
||||
echo "Инициализация нового wiki репозитория..."
|
||||
git init -b main
|
||||
git remote add origin "$CLONE_URL"
|
||||
fi
|
||||
|
||||
rsync -a --delete "${WIKI_SRC}/" ./
|
||||
|
||||
git add -A
|
||||
if git diff --staged --quiet 2>/dev/null; then
|
||||
echo "Wiki без изменений."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
git config user.email "wiki@shop.local"
|
||||
git config user.name "Shop Wiki"
|
||||
git commit -m "docs: установка Docker и без Docker (v0.10.0)"
|
||||
git push -u origin main
|
||||
|
||||
echo ""
|
||||
echo "Готово: https://git.evilfox.cc/test/shop10/wiki"
|
||||
@@ -0,0 +1,79 @@
|
||||
#!/bin/bash
|
||||
# Быстрое развёртывание / обновление на Ubuntu (без Docker)
|
||||
# sudo bash scripts/quick-deploy-ubuntu.sh
|
||||
#
|
||||
# Каталог: SHOP_INSTALL_DIR (по умолчанию /opt/shop)
|
||||
# URL репозитория: SHOP_GIT_URL (обязателен при первом clone)
|
||||
set -euo pipefail
|
||||
|
||||
INSTALL_DIR="${SHOP_INSTALL_DIR:-/opt/shop}"
|
||||
GIT_URL="${SHOP_GIT_URL:-}"
|
||||
|
||||
if [ "$(id -u)" -ne 0 ]; then
|
||||
echo "Запустите от root: sudo bash scripts/quick-deploy-ubuntu.sh"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "=== Shop: быстрое развёртывание ==="
|
||||
echo "Каталог: $INSTALL_DIR"
|
||||
|
||||
if ! command -v node >/dev/null; then
|
||||
echo "Установка Node.js 20..."
|
||||
apt update
|
||||
apt install -y git curl ca-certificates
|
||||
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
|
||||
apt install -y nodejs
|
||||
fi
|
||||
|
||||
if [ ! -f "$INSTALL_DIR/package.json" ]; then
|
||||
if [ -z "$GIT_URL" ]; then
|
||||
echo "Задайте URL репозитория:"
|
||||
echo " export SHOP_GIT_URL='https://ваш-forge/user/shop.git'"
|
||||
echo " sudo SHOP_GIT_URL=\"\$SHOP_GIT_URL\" bash scripts/quick-deploy-ubuntu.sh"
|
||||
exit 1
|
||||
fi
|
||||
echo "Клонирование: $GIT_URL -> $INSTALL_DIR"
|
||||
mkdir -p "$(dirname "$INSTALL_DIR")"
|
||||
git clone "$GIT_URL" "$INSTALL_DIR"
|
||||
fi
|
||||
|
||||
export SHOP_ROOT="$INSTALL_DIR"
|
||||
cd "$INSTALL_DIR"
|
||||
git config --global --add safe.directory "$INSTALL_DIR" 2>/dev/null || true
|
||||
git pull
|
||||
|
||||
bash scripts/install-postgresql-ubuntu.sh
|
||||
bash scripts/setup-postgres-ubuntu.sh
|
||||
|
||||
if [ ! -f .env ]; then
|
||||
cp .env.example .env
|
||||
if command -v openssl >/dev/null; then
|
||||
SECRET=$(openssl rand -hex 32)
|
||||
sed -i "s/change-me-to-a-long-random-string/${SECRET}/" .env
|
||||
fi
|
||||
if ! grep -q '^DATABASE_URL=' .env; then
|
||||
echo 'DATABASE_URL=postgresql://shop:shop@127.0.0.1:5432/shop' >> .env
|
||||
fi
|
||||
echo "Создан .env — проверьте SITE_URL и SMTP"
|
||||
fi
|
||||
|
||||
npm install --omit=dev
|
||||
|
||||
if [ -f deploy/shop.service ]; then
|
||||
cp -f deploy/shop.service /etc/systemd/system/shop.service
|
||||
# Подставить фактический путь в unit
|
||||
sed -i "s|WorkingDirectory=.*|WorkingDirectory=${INSTALL_DIR}|" /etc/systemd/system/shop.service
|
||||
sed -i "s|EnvironmentFile=.*|EnvironmentFile=${INSTALL_DIR}/.env|" /etc/systemd/system/shop.service
|
||||
systemctl daemon-reload
|
||||
systemctl enable shop 2>/dev/null || true
|
||||
systemctl restart shop
|
||||
sleep 2
|
||||
curl -sf http://127.0.0.1:3000/health && echo && echo "OK — shop запущен (systemd)"
|
||||
systemctl reload caddy 2>/dev/null || true
|
||||
else
|
||||
echo "deploy/shop.service не найден — запустите: npm start"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "Обновления в будущем:"
|
||||
echo " bash ${INSTALL_DIR}/scripts/server-update.sh"
|
||||
+35
-12
@@ -1,11 +1,24 @@
|
||||
#!/bin/bash
|
||||
# Обновление на сервере (запускать от root в /opt/shop)
|
||||
# Обновление на сервере: git pull, npm, restart shop
|
||||
# bash "$SHOP_ROOT/scripts/server-update.sh"
|
||||
set -euo pipefail
|
||||
|
||||
cd /opt/shop
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
# shellcheck source=shop-root.sh
|
||||
source "$SCRIPT_DIR/shop-root.sh"
|
||||
|
||||
git config --global --add safe.directory /opt/shop 2>/dev/null || true
|
||||
git pull
|
||||
echo "=== Shop update: $SHOP_ROOT ==="
|
||||
|
||||
if [ ! -d .git ]; then
|
||||
echo "Ошибка: $SHOP_ROOT не git-репозиторий (нет .git)."
|
||||
echo "Если нет .git — клонируйте заново:"
|
||||
echo " export SHOP_GIT_URL='<URL-репозитория>'"
|
||||
echo " mv \"$SHOP_ROOT\" \"\${SHOP_ROOT}.bak\""
|
||||
echo " git clone \"\$SHOP_GIT_URL\" \"$SHOP_ROOT\""
|
||||
exit 1
|
||||
fi
|
||||
|
||||
bash "$SCRIPT_DIR/git-sync.sh"
|
||||
|
||||
npm install --omit=dev
|
||||
|
||||
@@ -21,15 +34,25 @@ if command -v pg_isready >/dev/null; then
|
||||
}
|
||||
fi
|
||||
|
||||
if systemctl is-active --quiet shop 2>/dev/null; then
|
||||
if [ -f /etc/systemd/system/shop.service ]; then
|
||||
systemctl daemon-reload
|
||||
bash "$SCRIPT_DIR/free-port-3000.sh" 3000 2>/dev/null || true
|
||||
systemctl restart shop
|
||||
sleep 1
|
||||
curl -sf http://127.0.0.1:3000/health && echo || {
|
||||
echo "shop не отвечает — смотрите: journalctl -u shop -n 30"
|
||||
exit 1
|
||||
}
|
||||
systemctl reload caddy 2>/dev/null || true
|
||||
sleep 2
|
||||
if curl -sf http://127.0.0.1:3000/health; then
|
||||
echo ""
|
||||
echo "OK"
|
||||
systemctl reload caddy 2>/dev/null || true
|
||||
else
|
||||
echo "shop не отвечает — journalctl -u shop -n 30"
|
||||
exit 1
|
||||
fi
|
||||
elif [ "$(id -u)" -eq 0 ]; then
|
||||
echo "Служба shop не установлена — устанавливаем..."
|
||||
bash "$SCRIPT_DIR/install-shop-service.sh"
|
||||
else
|
||||
echo "Служба shop не установлена. См. deploy/shop.service в README."
|
||||
echo "Служба shop не установлена. Выполните от root:"
|
||||
echo " sudo bash $SHOP_ROOT/scripts/install-shop-service.sh"
|
||||
echo "WorkingDirectory: $SHOP_ROOT"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
#!/bin/bash
|
||||
# PostgreSQL 17 на Ubuntu — установка службы, пользователь и БД shop
|
||||
# Запуск: sudo bash scripts/setup-postgres-ubuntu.sh
|
||||
# PostgreSQL — пользователь и БД shop (после install-postgresql-ubuntu.sh)
|
||||
# sudo bash scripts/setup-postgres-ubuntu.sh
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
SHOP_ROOT="${SHOP_ROOT:-$(cd "$SCRIPT_DIR/.." && pwd)}"
|
||||
|
||||
DB_USER="${DB_USER:-shop}"
|
||||
DB_PASS="${DB_PASS:-shop}"
|
||||
DB_NAME="${DB_NAME:-shop}"
|
||||
|
||||
if ! command -v psql >/dev/null; then
|
||||
echo "PostgreSQL не установлен."
|
||||
echo " apt install -y postgresql-17 postgresql-client-17"
|
||||
echo " systemctl enable --now postgresql"
|
||||
echo "PostgreSQL не установлен. Запустите:"
|
||||
echo " sudo bash $SCRIPT_DIR/install-postgresql-ubuntu.sh"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -52,7 +54,7 @@ EOF
|
||||
|
||||
echo ""
|
||||
echo "PostgreSQL готов."
|
||||
echo "Добавьте в /opt/shop/.env:"
|
||||
echo "Добавьте в ${SHOP_ROOT}/.env:"
|
||||
echo "DATABASE_URL=postgresql://${DB_USER}:${DB_PASS}@127.0.0.1:5432/${DB_NAME}"
|
||||
echo ""
|
||||
echo "Проверка: psql \"postgresql://${DB_USER}:${DB_PASS}@127.0.0.1:5432/${DB_NAME}\" -c 'SELECT 1'"
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
#!/bin/bash
|
||||
# Каталог репозитория (package.json + по возможности .git)
|
||||
# Переопределение: SHOP_ROOT=/opt/shop/shop10
|
||||
_resolve_shop_root() {
|
||||
local d
|
||||
for d in \
|
||||
"${SHOP_ROOT:-}" \
|
||||
"$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" \
|
||||
"/opt/shop" \
|
||||
"/opt/shop/app"; do
|
||||
[ -z "$d" ] && continue
|
||||
[ -f "${d}/package.json" ] && [ -d "${d}/.git" ] && SHOP_ROOT="$d" && return 0
|
||||
done
|
||||
for d in \
|
||||
"${SHOP_ROOT:-}" \
|
||||
"$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" \
|
||||
"/opt/shop" \
|
||||
"/opt/shop/app"; do
|
||||
[ -z "$d" ] && continue
|
||||
[ -f "${d}/package.json" ] && SHOP_ROOT="$d" && return 0
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
if ! _resolve_shop_root; then
|
||||
echo "Ошибка: не найден каталог Shop (нет package.json)."
|
||||
echo " export SHOP_ROOT=/opt/shop # каталог с package.json"
|
||||
echo " git clone <URL-репозитория> \"\$SHOP_ROOT\""
|
||||
echo " SHOP_ROOT=\$SHOP_ROOT bash scripts/server-update.sh"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
export SHOP_ROOT
|
||||
cd "$SHOP_ROOT"
|
||||
@@ -0,0 +1,13 @@
|
||||
#!/bin/bash
|
||||
# Ожидание PostgreSQL (сокет или TCP 127.0.0.1:5432)
|
||||
for i in $(seq 1 45); do
|
||||
if pg_isready -q 2>/dev/null; then
|
||||
exit 0
|
||||
fi
|
||||
if pg_isready -h 127.0.0.1 -p 5432 -q 2>/dev/null; then
|
||||
exit 0
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
echo "PostgreSQL недоступен (проверьте: systemctl status postgresql)"
|
||||
exit 1
|
||||
@@ -0,0 +1,11 @@
|
||||
const ROLES = {
|
||||
CUSTOMER: 'customer',
|
||||
ADMIN: 'admin',
|
||||
};
|
||||
|
||||
const ROLE_LABELS = {
|
||||
customer: 'Клиент',
|
||||
admin: 'Администратор',
|
||||
};
|
||||
|
||||
module.exports = { ROLES, ROLE_LABELS };
|
||||
@@ -26,9 +26,12 @@ async function query(text, params) {
|
||||
}
|
||||
|
||||
async function initSchema() {
|
||||
const schemaPath = path.join(__dirname, '..', 'postgres', 'init', '01_schema.sql');
|
||||
const sql = fs.readFileSync(schemaPath, 'utf8');
|
||||
const initDir = path.join(__dirname, '..', 'postgres', 'init');
|
||||
const files = fs.readdirSync(initDir).filter((f) => f.endsWith('.sql')).sort();
|
||||
for (const file of files) {
|
||||
const sql = fs.readFileSync(path.join(initDir, file), 'utf8');
|
||||
await pool.query(sql);
|
||||
}
|
||||
}
|
||||
|
||||
async function checkConnection() {
|
||||
|
||||
+19
-2
@@ -1,5 +1,6 @@
|
||||
const { query } = require('../db');
|
||||
const { asyncHandler } = require('../utils/asyncHandler');
|
||||
const { ROLES } = require('../constants/roles');
|
||||
|
||||
function requireAuth(req, res, next) {
|
||||
if (!req.session.userId) {
|
||||
@@ -9,17 +10,33 @@ function requireAuth(req, res, next) {
|
||||
next();
|
||||
}
|
||||
|
||||
function requireAdmin(req, res, next) {
|
||||
if (!req.session.userId) {
|
||||
const nextUrl = encodeURIComponent(req.originalUrl);
|
||||
return res.redirect(`/login?next=${nextUrl}`);
|
||||
}
|
||||
if (res.locals.user?.role !== ROLES.ADMIN) {
|
||||
return res.status(403).render('error', {
|
||||
title: 'Доступ запрещён',
|
||||
message: 'Недостаточно прав. Требуется роль администратора.',
|
||||
code: 403,
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
const loadUser = asyncHandler(async (req, res, next) => {
|
||||
if (req.session.userId) {
|
||||
const { rows } = await query(
|
||||
'SELECT id, email, name FROM users WHERE id = $1',
|
||||
'SELECT id, email, name, role FROM users WHERE id = $1',
|
||||
[req.session.userId]
|
||||
);
|
||||
res.locals.user = rows[0] || null;
|
||||
} else {
|
||||
res.locals.user = null;
|
||||
}
|
||||
res.locals.isAdmin = res.locals.user?.role === ROLES.ADMIN;
|
||||
next();
|
||||
});
|
||||
|
||||
module.exports = { requireAuth, loadUser };
|
||||
module.exports = { requireAuth, requireAdmin, loadUser };
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
const CONSENT_COOKIE = 'cookie_consent';
|
||||
const CONSENT_VALUE = 'accepted';
|
||||
const CONSENT_MAX_AGE_MS = 365 * 24 * 60 * 60 * 1000;
|
||||
|
||||
function hasCookieConsent(req) {
|
||||
return req.cookies?.[CONSENT_COOKIE] === CONSENT_VALUE;
|
||||
}
|
||||
|
||||
function loadCookieConsent(req, res, next) {
|
||||
res.locals.cookieConsent = hasCookieConsent(req);
|
||||
res.locals.returnTo = req.originalUrl;
|
||||
next();
|
||||
}
|
||||
|
||||
function requireCookieConsent(req, res, next) {
|
||||
if (hasCookieConsent(req)) {
|
||||
return next();
|
||||
}
|
||||
|
||||
if (req.method === 'GET') {
|
||||
return res.status(403).render('cookies-required', {
|
||||
title: 'Согласие на cookies',
|
||||
returnTo: req.originalUrl,
|
||||
});
|
||||
}
|
||||
|
||||
return res.redirect(
|
||||
'/?error=' + encodeURIComponent('Примите согласие на использование cookies')
|
||||
);
|
||||
}
|
||||
|
||||
function setConsentCookie(res, isProduction) {
|
||||
res.cookie(CONSENT_COOKIE, CONSENT_VALUE, {
|
||||
maxAge: CONSENT_MAX_AGE_MS,
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
secure: isProduction,
|
||||
path: '/',
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
CONSENT_COOKIE,
|
||||
hasCookieConsent,
|
||||
loadCookieConsent,
|
||||
requireCookieConsent,
|
||||
setConsentCookie,
|
||||
};
|
||||
+328
-1
@@ -281,6 +281,39 @@ a:hover {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.stock-notify {
|
||||
margin-top: 1.25rem;
|
||||
padding: 1.25rem;
|
||||
}
|
||||
|
||||
.stock-notify__title {
|
||||
margin: 0 0 0.35rem;
|
||||
font-size: 1.05rem;
|
||||
}
|
||||
|
||||
.stock-notify__hint {
|
||||
margin: 0 0 1rem;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.stock-notify__form {
|
||||
max-width: 320px;
|
||||
}
|
||||
|
||||
.stock-notify--done {
|
||||
margin-top: 1rem;
|
||||
padding: 0.75rem 1rem;
|
||||
background: rgba(0, 184, 148, 0.12);
|
||||
border-radius: 8px;
|
||||
color: var(--success);
|
||||
}
|
||||
|
||||
.admin-stock-form {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.product-detail__form {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
@@ -392,7 +425,9 @@ a:hover {
|
||||
|
||||
.auth {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 1.25rem;
|
||||
padding: 2rem 0;
|
||||
}
|
||||
|
||||
@@ -402,6 +437,52 @@ a:hover {
|
||||
padding: 1.75rem;
|
||||
}
|
||||
|
||||
.passkey-login {
|
||||
width: 100%;
|
||||
max-width: 400px;
|
||||
padding: 1.25rem 1.75rem;
|
||||
}
|
||||
|
||||
.passkey-login__title {
|
||||
margin: 0 0 0.5rem;
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.passkey-login__hint {
|
||||
margin: 0 0 1rem;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.passkey-list {
|
||||
list-style: none;
|
||||
margin: 0 0 1.25rem;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.passkey-list__item {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.5rem;
|
||||
padding: 0.65rem 0;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.passkey-list__item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.passkey-actions {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.divider {
|
||||
border: none;
|
||||
border-top: 1px solid var(--border);
|
||||
margin: 1.5rem 0;
|
||||
}
|
||||
|
||||
.alert {
|
||||
padding: 0.75rem 1rem;
|
||||
border-radius: 8px;
|
||||
@@ -579,3 +660,249 @@ a:hover {
|
||||
display: inline;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.nav__admin {
|
||||
color: var(--warn);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.btn--admin {
|
||||
background: rgba(253, 203, 110, 0.15);
|
||||
border: 1px solid var(--warn);
|
||||
color: var(--warn);
|
||||
}
|
||||
|
||||
.btn--admin:hover {
|
||||
background: rgba(253, 203, 110, 0.28);
|
||||
color: #fff;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.account-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.75rem;
|
||||
margin-top: 1.25rem;
|
||||
}
|
||||
|
||||
.admin-hint {
|
||||
margin: 0 0 1rem;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.admin-hint code {
|
||||
font-size: 0.85em;
|
||||
}
|
||||
|
||||
.admin-header {
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.admin-header h1 {
|
||||
margin: 0 0 0.75rem;
|
||||
}
|
||||
|
||||
.admin-nav {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.admin-nav__link {
|
||||
padding: 0.4rem 0.85rem;
|
||||
border-radius: 8px;
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
color: var(--muted);
|
||||
text-decoration: none;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.admin-nav__link:hover,
|
||||
.admin-nav__link--active {
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
color: #fff;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.stats-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
|
||||
gap: 1rem;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.stat-card__label {
|
||||
display: block;
|
||||
font-size: 0.85rem;
|
||||
color: var(--muted);
|
||||
margin-bottom: 0.35rem;
|
||||
}
|
||||
|
||||
.stat-card__value {
|
||||
font-size: 1.35rem;
|
||||
}
|
||||
|
||||
.role-badge {
|
||||
display: inline-block;
|
||||
padding: 0.2rem 0.55rem;
|
||||
border-radius: 6px;
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.role-badge--customer {
|
||||
background: rgba(108, 92, 231, 0.2);
|
||||
color: var(--accent-hover);
|
||||
}
|
||||
|
||||
.role-badge--admin {
|
||||
background: rgba(253, 203, 110, 0.25);
|
||||
color: var(--warn);
|
||||
}
|
||||
|
||||
.admin-status-form {
|
||||
display: flex;
|
||||
gap: 0.35rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.input--sm {
|
||||
padding: 0.35rem 0.5rem;
|
||||
font-size: 0.85rem;
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.account-tabs {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.account-tabs__link {
|
||||
padding: 0.45rem 1rem;
|
||||
border-radius: 8px;
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
color: var(--muted);
|
||||
text-decoration: none;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.account-tabs__link:hover,
|
||||
.account-tabs__link--active {
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.account-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
|
||||
gap: 1.25rem;
|
||||
}
|
||||
|
||||
.account-section {
|
||||
padding: 1.25rem;
|
||||
}
|
||||
|
||||
.account-section--narrow {
|
||||
max-width: 420px;
|
||||
}
|
||||
|
||||
.account-section h2 {
|
||||
margin: 0 0 1rem;
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.profile-dl {
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr;
|
||||
gap: 0.5rem 1.25rem;
|
||||
margin: 0 0 1.25rem;
|
||||
}
|
||||
|
||||
.profile-dl dt {
|
||||
color: var(--muted);
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.profile-dl dd {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.cookie-banner {
|
||||
position: fixed;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 1000;
|
||||
background: var(--surface);
|
||||
border-top: 1px solid var(--border);
|
||||
box-shadow: 0 -8px 32px rgba(0, 0, 0, 0.35);
|
||||
padding: 1rem 0;
|
||||
}
|
||||
|
||||
.cookie-banner__inner {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.cookie-banner__text {
|
||||
flex: 1;
|
||||
min-width: 240px;
|
||||
}
|
||||
|
||||
.cookie-banner__text p {
|
||||
margin: 0 0 0.35rem;
|
||||
}
|
||||
|
||||
.cookie-banner__actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.nav__link--disabled {
|
||||
color: var(--muted);
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.cookies-required {
|
||||
max-width: 520px;
|
||||
margin: 2rem auto;
|
||||
}
|
||||
|
||||
.cookies-required h1 {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.legal-page {
|
||||
max-width: 640px;
|
||||
padding: 1.5rem;
|
||||
margin: 0 auto 2rem;
|
||||
}
|
||||
|
||||
.legal-page h2 {
|
||||
font-size: 1rem;
|
||||
margin: 1.25rem 0 0.5rem;
|
||||
}
|
||||
|
||||
body:has(.cookie-banner) .main {
|
||||
padding-bottom: 7rem;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
/**
|
||||
* WebAuthn (passkey) — требуется современный браузер с parseCreationOptionsFromJSON / toJSON.
|
||||
*/
|
||||
(function () {
|
||||
function supportsPasskey() {
|
||||
return (
|
||||
window.PublicKeyCredential &&
|
||||
typeof PublicKeyCredential.parseCreationOptionsFromJSON === 'function' &&
|
||||
typeof PublicKeyCredential.parseRequestOptionsFromJSON === 'function'
|
||||
);
|
||||
}
|
||||
|
||||
function showError(el, message) {
|
||||
if (!el) return;
|
||||
el.textContent = message;
|
||||
el.hidden = false;
|
||||
}
|
||||
|
||||
function hideError(el) {
|
||||
if (el) el.hidden = true;
|
||||
}
|
||||
|
||||
async function postJson(url, body) {
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'same-origin',
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
throw new Error(data.error || 'Ошибка запроса');
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
async function registerPasskey(passwordInput, errorEl, btn) {
|
||||
if (!supportsPasskey()) {
|
||||
showError(errorEl, 'Браузер не поддерживает passkey. Обновите браузер или используйте Chrome, Edge, Safari.');
|
||||
return;
|
||||
}
|
||||
const password = passwordInput?.value;
|
||||
if (!password) {
|
||||
showError(errorEl, 'Введите текущий пароль для подтверждения');
|
||||
return;
|
||||
}
|
||||
|
||||
hideError(errorEl);
|
||||
if (btn) btn.disabled = true;
|
||||
|
||||
try {
|
||||
const options = await postJson('/webauthn/register/options', {
|
||||
current_password: password,
|
||||
});
|
||||
|
||||
const credential = await navigator.credentials.create({
|
||||
publicKey: PublicKeyCredential.parseCreationOptionsFromJSON(options),
|
||||
});
|
||||
|
||||
const result = await postJson('/webauthn/register/verify', credential.toJSON());
|
||||
if (result.redirect) {
|
||||
window.location.href = result.redirect;
|
||||
} else {
|
||||
window.location.reload();
|
||||
}
|
||||
} catch (err) {
|
||||
showError(errorEl, err.message || 'Не удалось привязать passkey');
|
||||
} finally {
|
||||
if (btn) btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function loginWithPasskey(emailInput, nextInput, errorEl, btn) {
|
||||
if (!supportsPasskey()) {
|
||||
showError(errorEl, 'Браузер не поддерживает passkey');
|
||||
return;
|
||||
}
|
||||
const email = (emailInput?.value || '').trim();
|
||||
if (!email) {
|
||||
showError(errorEl, 'Сначала укажите email');
|
||||
emailInput?.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
hideError(errorEl);
|
||||
if (btn) btn.disabled = true;
|
||||
|
||||
try {
|
||||
const options = await postJson('/webauthn/login/options', { email });
|
||||
const credential = await navigator.credentials.get({
|
||||
publicKey: PublicKeyCredential.parseRequestOptionsFromJSON(options),
|
||||
});
|
||||
|
||||
const result = await postJson('/webauthn/login/verify', {
|
||||
...credential.toJSON(),
|
||||
next: nextInput?.value || '/',
|
||||
});
|
||||
|
||||
window.location.href = result.redirect || '/';
|
||||
} catch (err) {
|
||||
showError(errorEl, err.message || 'Не удалось войти по passkey');
|
||||
} finally {
|
||||
if (btn) btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
window.ShopPasskey = {
|
||||
supportsPasskey,
|
||||
registerPasskey,
|
||||
loginWithPasskey,
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1,238 @@
|
||||
const express = require('express');
|
||||
const bcrypt = require('bcryptjs');
|
||||
const { query, formatPrice } = require('../db');
|
||||
const { getCart, cartCount } = require('../cart');
|
||||
const { requireAuth } = require('../middleware/auth');
|
||||
const { requireCookieConsent } = require('../middleware/cookieConsent');
|
||||
const { ROLES, ROLE_LABELS } = require('../constants/roles');
|
||||
const { asyncHandler } = require('../utils/asyncHandler');
|
||||
const { expireOldReservations } = require('../services/reservations');
|
||||
const webauthn = require('../services/webauthn');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.use(requireCookieConsent);
|
||||
|
||||
router.use((req, res, next) => {
|
||||
const cart = getCart(req);
|
||||
res.locals.cartCount = cartCount(cart);
|
||||
res.locals.formatPrice = formatPrice;
|
||||
next();
|
||||
});
|
||||
|
||||
async function loadAccountUser(userId) {
|
||||
const { rows } = await query(
|
||||
'SELECT id, email, name, role, created_at, passkey_enabled FROM users WHERE id = $1',
|
||||
[userId]
|
||||
);
|
||||
return rows[0];
|
||||
}
|
||||
|
||||
async function verifyPassword(userId, password) {
|
||||
const { rows } = await query('SELECT password_hash FROM users WHERE id = $1', [
|
||||
userId,
|
||||
]);
|
||||
if (!rows[0]) return false;
|
||||
return bcrypt.compareSync(password || '', rows[0].password_hash);
|
||||
}
|
||||
|
||||
function accountRender(res, options) {
|
||||
const {
|
||||
user,
|
||||
orderCount,
|
||||
reservations,
|
||||
error,
|
||||
success,
|
||||
activeTab,
|
||||
formatPrice,
|
||||
passkeys,
|
||||
isAdmin,
|
||||
} = options;
|
||||
res.render('account/index', {
|
||||
title: 'Личный кабинет',
|
||||
user,
|
||||
orderCount,
|
||||
reservations: reservations || [],
|
||||
passkeys: passkeys || [],
|
||||
isAdmin: Boolean(isAdmin),
|
||||
roleLabels: ROLE_LABELS,
|
||||
formatPrice: formatPrice || res.locals.formatPrice,
|
||||
error: error || null,
|
||||
success: success || null,
|
||||
activeTab: activeTab || 'profile',
|
||||
});
|
||||
}
|
||||
|
||||
router.get(
|
||||
'/',
|
||||
requireAuth,
|
||||
asyncHandler(async (req, res) => {
|
||||
await expireOldReservations();
|
||||
const user = await loadAccountUser(req.session.userId);
|
||||
const countResult = await query(
|
||||
'SELECT COUNT(*)::int AS n FROM orders WHERE user_id = $1',
|
||||
[user.id]
|
||||
);
|
||||
|
||||
const { rows: reservations } = await query(
|
||||
`SELECT r.*, p.name AS product_name, p.slug AS product_slug, p.price_cents, p.image_url
|
||||
FROM reservations r
|
||||
JOIN products p ON p.id = r.product_id
|
||||
WHERE r.user_id = $1
|
||||
ORDER BY r.created_at DESC`,
|
||||
[user.id]
|
||||
);
|
||||
|
||||
const passkeys = await webauthn.getCredentialsForUser(user.id);
|
||||
|
||||
accountRender(res, {
|
||||
user,
|
||||
orderCount: countResult.rows[0].n,
|
||||
reservations,
|
||||
passkeys,
|
||||
isAdmin: user.role === ROLES.ADMIN,
|
||||
formatPrice,
|
||||
success: req.query.success ? decodeURIComponent(String(req.query.success)) : null,
|
||||
error: req.query.error ? decodeURIComponent(String(req.query.error)) : null,
|
||||
activeTab: req.query.tab || 'profile',
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/profile',
|
||||
requireAuth,
|
||||
asyncHandler(async (req, res) => {
|
||||
const name = (req.body.name || '').trim();
|
||||
if (!name) {
|
||||
return res.redirect('/account?tab=profile&error=' + encodeURIComponent('Укажите имя'));
|
||||
}
|
||||
await query('UPDATE users SET name = $1 WHERE id = $2', [name, req.session.userId]);
|
||||
res.redirect('/account?tab=profile&success=' + encodeURIComponent('Имя обновлено'));
|
||||
})
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/email',
|
||||
requireAuth,
|
||||
asyncHandler(async (req, res) => {
|
||||
const newEmail = (req.body.email || '').trim().toLowerCase();
|
||||
const { current_password } = req.body;
|
||||
|
||||
if (!newEmail) {
|
||||
return res.redirect(
|
||||
'/account?tab=email&error=' + encodeURIComponent('Укажите новый email')
|
||||
);
|
||||
}
|
||||
|
||||
const emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRe.test(newEmail)) {
|
||||
return res.redirect(
|
||||
'/account?tab=email&error=' + encodeURIComponent('Некорректный email')
|
||||
);
|
||||
}
|
||||
|
||||
const user = await loadAccountUser(req.session.userId);
|
||||
if (newEmail === user.email) {
|
||||
return res.redirect(
|
||||
'/account?tab=email&error=' + encodeURIComponent('Это уже ваш текущий email')
|
||||
);
|
||||
}
|
||||
|
||||
if (!(await verifyPassword(req.session.userId, current_password))) {
|
||||
return res.redirect(
|
||||
'/account?tab=email&error=' + encodeURIComponent('Неверный текущий пароль')
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
await query('UPDATE users SET email = $1 WHERE id = $2', [
|
||||
newEmail,
|
||||
req.session.userId,
|
||||
]);
|
||||
res.redirect('/account?tab=email&success=' + encodeURIComponent('Email изменён'));
|
||||
} catch (err) {
|
||||
if (err.code === '23505') {
|
||||
return res.redirect(
|
||||
'/account?tab=email&error=' + encodeURIComponent('Этот email уже занят')
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/password',
|
||||
requireAuth,
|
||||
asyncHandler(async (req, res) => {
|
||||
const { current_password, password, password2 } = req.body;
|
||||
|
||||
if (!(await verifyPassword(req.session.userId, current_password))) {
|
||||
return res.redirect(
|
||||
'/account?tab=password&error=' + encodeURIComponent('Неверный текущий пароль')
|
||||
);
|
||||
}
|
||||
|
||||
if (!password || password.length < 6) {
|
||||
return res.redirect(
|
||||
'/account?tab=password&error=' +
|
||||
encodeURIComponent('Новый пароль не менее 6 символов')
|
||||
);
|
||||
}
|
||||
|
||||
if (password !== password2) {
|
||||
return res.redirect(
|
||||
'/account?tab=password&error=' + encodeURIComponent('Пароли не совпадают')
|
||||
);
|
||||
}
|
||||
|
||||
const hash = bcrypt.hashSync(password, 10);
|
||||
await query('UPDATE users SET password_hash = $1 WHERE id = $2', [
|
||||
hash,
|
||||
req.session.userId,
|
||||
]);
|
||||
res.redirect('/account?tab=password&success=' + encodeURIComponent('Пароль изменён'));
|
||||
})
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/passkey/disable',
|
||||
requireAuth,
|
||||
asyncHandler(async (req, res) => {
|
||||
const { current_password } = req.body;
|
||||
if (!(await verifyPassword(req.session.userId, current_password))) {
|
||||
return res.redirect(
|
||||
'/account?tab=passkey&error=' + encodeURIComponent('Неверный пароль')
|
||||
);
|
||||
}
|
||||
await webauthn.disablePasskeys(req.session.userId);
|
||||
res.redirect(
|
||||
'/account?tab=passkey&success=' + encodeURIComponent('Вход по passkey отключён')
|
||||
);
|
||||
})
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/passkey/credentials/:id/delete',
|
||||
requireAuth,
|
||||
asyncHandler(async (req, res) => {
|
||||
const { current_password } = req.body;
|
||||
if (!(await verifyPassword(req.session.userId, current_password))) {
|
||||
return res.redirect(
|
||||
'/account?tab=passkey&error=' + encodeURIComponent('Неверный пароль')
|
||||
);
|
||||
}
|
||||
const credId = parseInt(req.params.id, 10);
|
||||
if (!Number.isFinite(credId)) {
|
||||
return res.redirect('/account?tab=passkey&error=' + encodeURIComponent('Некорректный ключ'));
|
||||
}
|
||||
const ok = await webauthn.deleteCredential(req.session.userId, credId);
|
||||
if (!ok) {
|
||||
return res.redirect('/account?tab=passkey&error=' + encodeURIComponent('Ключ не найден'));
|
||||
}
|
||||
res.redirect('/account?tab=passkey&success=' + encodeURIComponent('Passkey удалён'));
|
||||
})
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,176 @@
|
||||
const express = require('express');
|
||||
const { query, formatPrice } = require('../db');
|
||||
const { requireAdmin } = require('../middleware/auth');
|
||||
const { asyncHandler } = require('../utils/asyncHandler');
|
||||
const { ROLE_LABELS } = require('../constants/roles');
|
||||
const { notifyIfBackInStock } = require('../services/stock-alerts');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.use(requireAdmin);
|
||||
|
||||
router.get(
|
||||
'/',
|
||||
asyncHandler(async (req, res) => {
|
||||
const [users, products, orders, revenue] = await Promise.all([
|
||||
query('SELECT COUNT(*)::int AS n FROM users'),
|
||||
query('SELECT COUNT(*)::int AS n FROM products'),
|
||||
query('SELECT COUNT(*)::int AS n FROM orders'),
|
||||
query(
|
||||
`SELECT COALESCE(SUM(total_cents), 0)::int AS total FROM orders WHERE status != 'cancelled'`
|
||||
),
|
||||
]);
|
||||
|
||||
const { rows: recentOrders } = await query(
|
||||
`SELECT o.id, o.status, o.total_cents, o.created_at, o.customer_name, u.email AS user_email
|
||||
FROM orders o
|
||||
JOIN users u ON u.id = o.user_id
|
||||
ORDER BY o.created_at DESC
|
||||
LIMIT 10`
|
||||
);
|
||||
|
||||
res.render('admin/dashboard', {
|
||||
title: 'Админ-панель',
|
||||
stats: {
|
||||
users: users.rows[0].n,
|
||||
products: products.rows[0].n,
|
||||
orders: orders.rows[0].n,
|
||||
revenue: revenue.rows[0].total,
|
||||
},
|
||||
recentOrders,
|
||||
formatPrice,
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
router.get(
|
||||
'/users',
|
||||
asyncHandler(async (req, res) => {
|
||||
const { rows: users } = await query(
|
||||
`SELECT id, email, name, role, created_at FROM users ORDER BY created_at DESC`
|
||||
);
|
||||
res.render('admin/users', {
|
||||
title: 'Пользователи',
|
||||
users,
|
||||
roleLabels: ROLE_LABELS,
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
router.get(
|
||||
'/orders',
|
||||
asyncHandler(async (req, res) => {
|
||||
const { rows: orders } = await query(
|
||||
`SELECT o.id, o.status, o.total_cents, o.created_at, o.customer_name, o.customer_email,
|
||||
u.email AS account_email
|
||||
FROM orders o
|
||||
JOIN users u ON u.id = o.user_id
|
||||
ORDER BY o.created_at DESC`
|
||||
);
|
||||
res.render('admin/orders', {
|
||||
title: 'Заказы',
|
||||
orders,
|
||||
formatPrice,
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/orders/:id/status',
|
||||
asyncHandler(async (req, res) => {
|
||||
const { status } = req.body;
|
||||
const allowed = ['pending', 'paid', 'shipped', 'cancelled'];
|
||||
if (!allowed.includes(status)) {
|
||||
return res.redirect('/admin/orders');
|
||||
}
|
||||
await query('UPDATE orders SET status = $1 WHERE id = $2', [status, req.params.id]);
|
||||
res.redirect('/admin/orders');
|
||||
})
|
||||
);
|
||||
|
||||
router.get(
|
||||
'/products',
|
||||
asyncHandler(async (req, res) => {
|
||||
const { rows: products } = await query(
|
||||
`SELECT p.*, c.name AS category_name,
|
||||
(SELECT COUNT(*)::int FROM product_stock_alerts a
|
||||
WHERE a.product_id = p.id AND a.notified_at IS NULL) AS alert_count
|
||||
FROM products p
|
||||
LEFT JOIN categories c ON c.id = p.category_id
|
||||
ORDER BY p.id`
|
||||
);
|
||||
res.render('admin/products', {
|
||||
title: 'Товары',
|
||||
products,
|
||||
formatPrice,
|
||||
stockUpdated: req.query.stock_updated === '1',
|
||||
notified: req.query.notified ? parseInt(req.query.notified, 10) : 0,
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/products/:id/stock',
|
||||
asyncHandler(async (req, res) => {
|
||||
const productId = parseInt(req.params.id, 10);
|
||||
const stock = parseInt(req.body.stock, 10);
|
||||
if (!Number.isFinite(productId) || !Number.isFinite(stock) || stock < 0) {
|
||||
return res.redirect('/admin/products');
|
||||
}
|
||||
|
||||
const { rows } = await query('SELECT stock FROM products WHERE id = $1', [productId]);
|
||||
const oldStock = rows[0]?.stock ?? 0;
|
||||
|
||||
await query('UPDATE products SET stock = $1 WHERE id = $2', [stock, productId]);
|
||||
|
||||
let notified = 0;
|
||||
if (oldStock <= 0 && stock > 0) {
|
||||
const result = await notifyIfBackInStock(productId);
|
||||
notified = result.sent;
|
||||
}
|
||||
|
||||
const qs = new URLSearchParams({ stock_updated: '1' });
|
||||
if (notified > 0) qs.set('notified', String(notified));
|
||||
res.redirect(`/admin/products?${qs}`);
|
||||
})
|
||||
);
|
||||
|
||||
router.get(
|
||||
'/reservations',
|
||||
asyncHandler(async (req, res) => {
|
||||
const { expireOldReservations } = require('../services/reservations');
|
||||
await expireOldReservations();
|
||||
|
||||
const { rows: reservations } = await query(
|
||||
`SELECT r.*, p.name AS product_name, u.email AS user_email, u.name AS user_name
|
||||
FROM reservations r
|
||||
JOIN products p ON p.id = r.product_id
|
||||
JOIN users u ON u.id = r.user_id
|
||||
ORDER BY r.created_at DESC`
|
||||
);
|
||||
|
||||
res.render('admin/reservations', {
|
||||
title: 'Бронирования',
|
||||
reservations,
|
||||
formatPrice,
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/reservations/:id/status',
|
||||
asyncHandler(async (req, res) => {
|
||||
const { status } = req.body;
|
||||
const allowed = ['active', 'fulfilled', 'cancelled', 'expired'];
|
||||
if (!allowed.includes(status)) {
|
||||
return res.redirect('/admin/reservations');
|
||||
}
|
||||
await query('UPDATE reservations SET status = $1 WHERE id = $2', [
|
||||
status,
|
||||
req.params.id,
|
||||
]);
|
||||
res.redirect('/admin/reservations');
|
||||
})
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
+12
-27
@@ -3,6 +3,8 @@ const bcrypt = require('bcryptjs');
|
||||
const { query, formatPrice } = require('../db');
|
||||
const { getCart, cartCount } = require('../cart');
|
||||
const { requireAuth } = require('../middleware/auth');
|
||||
const { requireCookieConsent } = require('../middleware/cookieConsent');
|
||||
const { ROLES } = require('../constants/roles');
|
||||
const { asyncHandler } = require('../utils/asyncHandler');
|
||||
|
||||
const router = express.Router();
|
||||
@@ -14,13 +16,14 @@ router.use((req, res, next) => {
|
||||
next();
|
||||
});
|
||||
|
||||
router.get('/register', (req, res) => {
|
||||
router.get('/register', requireCookieConsent, (req, res) => {
|
||||
if (req.session.userId) return res.redirect('/account');
|
||||
res.render('register', { title: 'Регистрация', error: null, values: {} });
|
||||
});
|
||||
|
||||
router.post(
|
||||
'/register',
|
||||
requireCookieConsent,
|
||||
asyncHandler(async (req, res) => {
|
||||
const { name, email, password, password2 } = req.body;
|
||||
const values = { name, email };
|
||||
@@ -50,8 +53,9 @@ router.post(
|
||||
const hash = bcrypt.hashSync(password, 10);
|
||||
try {
|
||||
const { rows } = await query(
|
||||
'INSERT INTO users (email, password_hash, name) VALUES ($1, $2, $3) RETURNING id',
|
||||
[email.trim().toLowerCase(), hash, name.trim()]
|
||||
`INSERT INTO users (email, password_hash, name, role)
|
||||
VALUES ($1, $2, $3, $4) RETURNING id`,
|
||||
[email.trim().toLowerCase(), hash, name.trim(), ROLES.CUSTOMER]
|
||||
);
|
||||
req.session.userId = rows[0].id;
|
||||
res.redirect('/');
|
||||
@@ -68,7 +72,7 @@ router.post(
|
||||
})
|
||||
);
|
||||
|
||||
router.get('/login', (req, res) => {
|
||||
router.get('/login', requireCookieConsent, (req, res) => {
|
||||
if (req.session.userId) return res.redirect('/account');
|
||||
res.render('login', {
|
||||
title: 'Вход',
|
||||
@@ -80,6 +84,7 @@ router.get('/login', (req, res) => {
|
||||
|
||||
router.post(
|
||||
'/login',
|
||||
requireCookieConsent,
|
||||
asyncHandler(async (req, res) => {
|
||||
const { email, password } = req.body;
|
||||
const next = req.body.next || '/';
|
||||
@@ -100,6 +105,9 @@ router.post(
|
||||
}
|
||||
|
||||
req.session.userId = user.id;
|
||||
if (user.role === ROLES.ADMIN && (next === '/' || next === '/account')) {
|
||||
return res.redirect('/admin');
|
||||
}
|
||||
res.redirect(next.startsWith('/') ? next : '/');
|
||||
})
|
||||
);
|
||||
@@ -110,27 +118,4 @@ router.post('/logout', (req, res) => {
|
||||
});
|
||||
});
|
||||
|
||||
router.get(
|
||||
'/account',
|
||||
requireAuth,
|
||||
asyncHandler(async (req, res) => {
|
||||
const { rows } = await query(
|
||||
'SELECT id, email, name, created_at FROM users WHERE id = $1',
|
||||
[req.session.userId]
|
||||
);
|
||||
const user = rows[0];
|
||||
|
||||
const countResult = await query(
|
||||
'SELECT COUNT(*)::int AS n FROM orders WHERE user_id = $1',
|
||||
[user.id]
|
||||
);
|
||||
|
||||
res.render('account', {
|
||||
title: 'Личный кабинет',
|
||||
user,
|
||||
orderCount: countResult.rows[0].n,
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
const express = require('express');
|
||||
const { setConsentCookie } = require('../middleware/cookieConsent');
|
||||
|
||||
const router = express.Router();
|
||||
const isProduction = process.env.NODE_ENV === 'production';
|
||||
|
||||
router.get('/policy', (req, res) => {
|
||||
res.render('cookies-policy', {
|
||||
title: 'Политика cookies',
|
||||
cookieConsent: res.locals.cookieConsent,
|
||||
});
|
||||
});
|
||||
|
||||
router.post('/accept', (req, res) => {
|
||||
setConsentCookie(res, isProduction);
|
||||
const returnTo = req.body.return_to || req.query.return_to || '/';
|
||||
const safe =
|
||||
typeof returnTo === 'string' && returnTo.startsWith('/') && !returnTo.startsWith('//')
|
||||
? returnTo
|
||||
: '/';
|
||||
res.redirect(safe);
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,164 @@
|
||||
const express = require('express');
|
||||
const bcrypt = require('bcryptjs');
|
||||
const { query, formatPrice } = require('../db');
|
||||
const { getCart, cartCount } = require('../cart');
|
||||
const { requireAuth } = require('../middleware/auth');
|
||||
const { requireCookieConsent } = require('../middleware/cookieConsent');
|
||||
const { ROLES } = require('../constants/roles');
|
||||
const { asyncHandler } = require('../utils/asyncHandler');
|
||||
const webauthn = require('../services/webauthn');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.use((req, res, next) => {
|
||||
const cart = getCart(req);
|
||||
res.locals.cartCount = cartCount(cart);
|
||||
res.locals.formatPrice = formatPrice;
|
||||
next();
|
||||
});
|
||||
|
||||
async function verifyPasswordById(userId, password) {
|
||||
const { rows } = await query('SELECT password_hash FROM users WHERE id = $1', [
|
||||
userId,
|
||||
]);
|
||||
if (!rows[0]) return false;
|
||||
return bcrypt.compareSync(password || '', rows[0].password_hash);
|
||||
}
|
||||
|
||||
async function loadUserById(userId) {
|
||||
const { rows } = await query(
|
||||
'SELECT id, email, name, role, passkey_enabled FROM users WHERE id = $1',
|
||||
[userId]
|
||||
);
|
||||
return rows[0];
|
||||
}
|
||||
|
||||
function saveChallenge(req, challenge, extra = {}) {
|
||||
req.session.webauthnChallenge = challenge;
|
||||
Object.assign(req.session, extra);
|
||||
}
|
||||
|
||||
function clearChallenge(req) {
|
||||
delete req.session.webauthnChallenge;
|
||||
delete req.session.webauthnLoginUserId;
|
||||
}
|
||||
|
||||
function adminRedirect(user, next) {
|
||||
if (user.role === ROLES.ADMIN && (next === '/' || next === '/account')) {
|
||||
return '/admin';
|
||||
}
|
||||
return next.startsWith('/') ? next : '/';
|
||||
}
|
||||
|
||||
// --- Регистрация passkey (в профиле, нужен вход) ---
|
||||
|
||||
router.post(
|
||||
'/register/options',
|
||||
requireCookieConsent,
|
||||
requireAuth,
|
||||
asyncHandler(async (req, res) => {
|
||||
const { current_password } = req.body || {};
|
||||
if (!(await verifyPasswordById(req.session.userId, current_password))) {
|
||||
return res.status(401).json({ error: 'Неверный пароль' });
|
||||
}
|
||||
|
||||
const user = await loadUserById(req.session.userId);
|
||||
if (!user) return res.status(404).json({ error: 'Пользователь не найден' });
|
||||
|
||||
webauthn.assertOrigin(req);
|
||||
const options = await webauthn.generateRegisterOptions(user);
|
||||
saveChallenge(req, options.challenge);
|
||||
res.json(options);
|
||||
})
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/register/verify',
|
||||
requireCookieConsent,
|
||||
requireAuth,
|
||||
asyncHandler(async (req, res) => {
|
||||
const expectedChallenge = req.session.webauthnChallenge;
|
||||
if (!expectedChallenge) {
|
||||
return res.status(400).json({ error: 'Сессия истекла, повторите привязку' });
|
||||
}
|
||||
|
||||
const user = await loadUserById(req.session.userId);
|
||||
if (!user) return res.status(404).json({ error: 'Пользователь не найден' });
|
||||
|
||||
const origin = webauthn.assertOrigin(req);
|
||||
const result = await webauthn.verifyRegister(
|
||||
user,
|
||||
req.body,
|
||||
expectedChallenge,
|
||||
origin
|
||||
);
|
||||
clearChallenge(req);
|
||||
|
||||
if (!result.verified) {
|
||||
return res.status(400).json({ error: 'Не удалось подтвердить passkey' });
|
||||
}
|
||||
|
||||
res.json({ ok: true, redirect: '/account?tab=passkey&success=' + encodeURIComponent('Passkey привязан') });
|
||||
})
|
||||
);
|
||||
|
||||
// --- Вход по passkey ---
|
||||
|
||||
router.post(
|
||||
'/login/options',
|
||||
requireCookieConsent,
|
||||
asyncHandler(async (req, res) => {
|
||||
const email = (req.body?.email || '').trim().toLowerCase();
|
||||
if (!email) {
|
||||
return res.status(400).json({ error: 'Укажите email' });
|
||||
}
|
||||
|
||||
const { user, options } = await webauthn.generateLoginOptions(email);
|
||||
if (!user || !options) {
|
||||
return res.status(404).json({
|
||||
error: 'Passkey не настроен для этого аккаунта',
|
||||
});
|
||||
}
|
||||
|
||||
webauthn.assertOrigin(req);
|
||||
saveChallenge(req, options.challenge, { webauthnLoginUserId: user.id });
|
||||
res.json(options);
|
||||
})
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/login/verify',
|
||||
requireCookieConsent,
|
||||
asyncHandler(async (req, res) => {
|
||||
const expectedChallenge = req.session.webauthnChallenge;
|
||||
const userId = req.session.webauthnLoginUserId;
|
||||
if (!expectedChallenge || !userId) {
|
||||
return res.status(400).json({ error: 'Сессия истекла, начните вход заново' });
|
||||
}
|
||||
|
||||
const user = await loadUserById(userId);
|
||||
if (!user || !user.passkey_enabled) {
|
||||
clearChallenge(req);
|
||||
return res.status(400).json({ error: 'Вход по passkey недоступен' });
|
||||
}
|
||||
|
||||
const origin = webauthn.assertOrigin(req);
|
||||
const result = await webauthn.verifyLogin(
|
||||
user,
|
||||
req.body,
|
||||
expectedChallenge,
|
||||
origin
|
||||
);
|
||||
clearChallenge(req);
|
||||
|
||||
if (!result.verified) {
|
||||
return res.status(401).json({ error: 'Не удалось войти по passkey' });
|
||||
}
|
||||
|
||||
req.session.userId = user.id;
|
||||
const next = req.body?.next || '/';
|
||||
res.json({ ok: true, redirect: adminRedirect(user, next) });
|
||||
})
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,176 @@
|
||||
const express = require('express');
|
||||
const crypto = require('crypto');
|
||||
const bcrypt = require('bcryptjs');
|
||||
const { query } = require('../db');
|
||||
const { getCart, cartCount } = require('../cart');
|
||||
const { formatPrice } = require('../db');
|
||||
const { requireCookieConsent } = require('../middleware/cookieConsent');
|
||||
const { asyncHandler } = require('../utils/asyncHandler');
|
||||
const { sendPasswordResetEmail, siteUrl } = require('../services/mail');
|
||||
|
||||
const router = express.Router();
|
||||
const TOKEN_TTL_MS = 60 * 60 * 1000;
|
||||
|
||||
router.use((req, res, next) => {
|
||||
res.locals.cartCount = cartCount(getCart(req));
|
||||
res.locals.formatPrice = formatPrice;
|
||||
next();
|
||||
});
|
||||
|
||||
function hashToken(token) {
|
||||
return crypto.createHash('sha256').update(token).digest('hex');
|
||||
}
|
||||
|
||||
router.get('/forgot-password', requireCookieConsent, (req, res) => {
|
||||
res.render('auth/forgot-password', {
|
||||
title: 'Сброс пароля',
|
||||
error: null,
|
||||
success: null,
|
||||
values: {},
|
||||
});
|
||||
});
|
||||
|
||||
router.post(
|
||||
'/forgot-password',
|
||||
requireCookieConsent,
|
||||
asyncHandler(async (req, res) => {
|
||||
const email = (req.body.email || '').trim().toLowerCase();
|
||||
const values = { email };
|
||||
const genericSuccess =
|
||||
'Если аккаунт с таким email существует, мы отправили ссылку для сброса пароля.';
|
||||
|
||||
if (!email) {
|
||||
return res.status(400).render('auth/forgot-password', {
|
||||
title: 'Сброс пароля',
|
||||
error: 'Укажите email',
|
||||
success: null,
|
||||
values,
|
||||
});
|
||||
}
|
||||
|
||||
const { rows } = await query('SELECT id, email FROM users WHERE email = $1', [email]);
|
||||
|
||||
if (rows[0]) {
|
||||
const token = crypto.randomBytes(32).toString('hex');
|
||||
const tokenHash = hashToken(token);
|
||||
const expiresAt = new Date(Date.now() + TOKEN_TTL_MS);
|
||||
|
||||
await query(
|
||||
`UPDATE password_reset_tokens SET used_at = NOW()
|
||||
WHERE user_id = $1 AND used_at IS NULL`,
|
||||
[rows[0].id]
|
||||
);
|
||||
|
||||
await query(
|
||||
`INSERT INTO password_reset_tokens (user_id, token_hash, expires_at)
|
||||
VALUES ($1, $2, $3)`,
|
||||
[rows[0].id, tokenHash, expiresAt]
|
||||
);
|
||||
|
||||
const resetLink = `${siteUrl()}/reset-password?token=${token}`;
|
||||
try {
|
||||
await sendPasswordResetEmail(rows[0].email, resetLink);
|
||||
} catch (err) {
|
||||
console.error('Ошибка отправки email:', err.message);
|
||||
return res.status(500).render('auth/forgot-password', {
|
||||
title: 'Сброс пароля',
|
||||
error: 'Не удалось отправить письмо. Проверьте настройки SMTP.',
|
||||
success: null,
|
||||
values,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
res.render('auth/forgot-password', {
|
||||
title: 'Сброс пароля',
|
||||
error: null,
|
||||
success: genericSuccess,
|
||||
values: {},
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
router.get(
|
||||
'/reset-password',
|
||||
requireCookieConsent,
|
||||
asyncHandler(async (req, res) => {
|
||||
const token = req.query.token || '';
|
||||
if (!token) {
|
||||
return res.redirect('/forgot-password');
|
||||
}
|
||||
|
||||
const valid = await findValidToken(token);
|
||||
if (!valid) {
|
||||
return res.render('auth/reset-password', {
|
||||
title: 'Новый пароль',
|
||||
error: 'Ссылка недействительна или устарела. Запросите сброс снова.',
|
||||
token: null,
|
||||
});
|
||||
}
|
||||
|
||||
res.render('auth/reset-password', {
|
||||
title: 'Новый пароль',
|
||||
error: null,
|
||||
token,
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/reset-password',
|
||||
requireCookieConsent,
|
||||
asyncHandler(async (req, res) => {
|
||||
const { token, password, password2 } = req.body;
|
||||
|
||||
if (!token) {
|
||||
return res.redirect('/forgot-password');
|
||||
}
|
||||
|
||||
if (!password || password.length < 6) {
|
||||
return res.render('auth/reset-password', {
|
||||
title: 'Новый пароль',
|
||||
error: 'Пароль не менее 6 символов',
|
||||
token,
|
||||
});
|
||||
}
|
||||
|
||||
if (password !== password2) {
|
||||
return res.render('auth/reset-password', {
|
||||
title: 'Новый пароль',
|
||||
error: 'Пароли не совпадают',
|
||||
token,
|
||||
});
|
||||
}
|
||||
|
||||
const row = await findValidToken(token);
|
||||
if (!row) {
|
||||
return res.render('auth/reset-password', {
|
||||
title: 'Новый пароль',
|
||||
error: 'Ссылка недействительна или устарела',
|
||||
token: null,
|
||||
});
|
||||
}
|
||||
|
||||
const hash = bcrypt.hashSync(password, 10);
|
||||
await query('UPDATE users SET password_hash = $1 WHERE id = $2', [hash, row.user_id]);
|
||||
await query(
|
||||
`UPDATE password_reset_tokens SET used_at = NOW() WHERE id = $1`,
|
||||
[row.id]
|
||||
);
|
||||
|
||||
res.render('auth/reset-password-done', { title: 'Пароль изменён' });
|
||||
})
|
||||
);
|
||||
|
||||
async function findValidToken(token) {
|
||||
const tokenHash = hashToken(token);
|
||||
const { rows } = await query(
|
||||
`SELECT id, user_id FROM password_reset_tokens
|
||||
WHERE token_hash = $1 AND used_at IS NULL AND expires_at > NOW()
|
||||
ORDER BY created_at DESC LIMIT 1`,
|
||||
[tokenHash]
|
||||
);
|
||||
return rows[0] || null;
|
||||
}
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,95 @@
|
||||
const express = require('express');
|
||||
const { query, formatPrice } = require('../db');
|
||||
const { getCart, cartCount } = require('../cart');
|
||||
const { requireAuth } = require('../middleware/auth');
|
||||
const { requireCookieConsent } = require('../middleware/cookieConsent');
|
||||
const { asyncHandler } = require('../utils/asyncHandler');
|
||||
const { sendReservationEmail } = require('../services/mail');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.use(requireCookieConsent);
|
||||
router.use(requireAuth);
|
||||
|
||||
router.use((req, res, next) => {
|
||||
res.locals.cartCount = cartCount(getCart(req));
|
||||
res.locals.formatPrice = formatPrice;
|
||||
next();
|
||||
});
|
||||
|
||||
router.post(
|
||||
'/',
|
||||
asyncHandler(async (req, res) => {
|
||||
const productId = parseInt(req.body.product_id, 10);
|
||||
const quantity = Math.max(1, parseInt(req.body.quantity, 10) || 1);
|
||||
const slug = req.body.slug || '';
|
||||
|
||||
const { rows: products } = await query(
|
||||
'SELECT id, name, stock FROM products WHERE id = $1',
|
||||
[productId]
|
||||
);
|
||||
const product = products[0];
|
||||
|
||||
if (!product) {
|
||||
return res.redirect('/');
|
||||
}
|
||||
|
||||
if (product.stock < quantity) {
|
||||
return res.redirect(
|
||||
`/product/${slug}?error=${encodeURIComponent('Недостаточно товара на складе')}`
|
||||
);
|
||||
}
|
||||
|
||||
const { rows: existing } = await query(
|
||||
`SELECT id FROM reservations
|
||||
WHERE user_id = $1 AND product_id = $2 AND status = 'active'`,
|
||||
[req.session.userId, productId]
|
||||
);
|
||||
|
||||
if (existing[0]) {
|
||||
return res.redirect(
|
||||
`/product/${slug}?error=${encodeURIComponent('У вас уже есть активная бронь этого товара')}`
|
||||
);
|
||||
}
|
||||
|
||||
const { rows: inserted } = await query(
|
||||
`INSERT INTO reservations (user_id, product_id, quantity, status, expires_at)
|
||||
VALUES ($1, $2, $3, 'active', NOW() + INTERVAL '48 hours')
|
||||
RETURNING id, expires_at`,
|
||||
[req.session.userId, productId, quantity]
|
||||
);
|
||||
|
||||
const { rows: userRows } = await query('SELECT email FROM users WHERE id = $1', [
|
||||
req.session.userId,
|
||||
]);
|
||||
|
||||
try {
|
||||
await sendReservationEmail(
|
||||
userRows[0].email,
|
||||
product.name,
|
||||
quantity,
|
||||
inserted[0].expires_at
|
||||
);
|
||||
} catch (err) {
|
||||
console.error('Ошибка email бронирования:', err.message);
|
||||
}
|
||||
|
||||
res.redirect(
|
||||
`/product/${slug}?reserved=1`
|
||||
);
|
||||
})
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/:id/cancel',
|
||||
asyncHandler(async (req, res) => {
|
||||
await query(
|
||||
`UPDATE reservations SET status = 'cancelled'
|
||||
WHERE id = $1 AND user_id = $2 AND status = 'active'`,
|
||||
[req.params.id, req.session.userId]
|
||||
);
|
||||
res.redirect('/account?tab=reservations&success=' + encodeURIComponent('Бронь отменена'));
|
||||
})
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
+48
-1
@@ -2,6 +2,7 @@ const express = require('express');
|
||||
const { query, pool, formatPrice } = require('../db');
|
||||
const { getCart, cartCount, cartItems, cartTotal } = require('../cart');
|
||||
const { requireAuth } = require('../middleware/auth');
|
||||
const { requireCookieConsent } = require('../middleware/cookieConsent');
|
||||
const { asyncHandler } = require('../utils/asyncHandler');
|
||||
|
||||
const router = express.Router();
|
||||
@@ -76,7 +77,49 @@ router.get(
|
||||
});
|
||||
}
|
||||
|
||||
res.render('product', { title: product.name, product });
|
||||
let userReservation = null;
|
||||
if (req.session.userId) {
|
||||
const { rows: resRows } = await query(
|
||||
`SELECT id, quantity, expires_at FROM reservations
|
||||
WHERE user_id = $1 AND product_id = $2 AND status = 'active'`,
|
||||
[req.session.userId, product.id]
|
||||
);
|
||||
userReservation = resRows[0] || null;
|
||||
}
|
||||
|
||||
const errorMsg = req.query.error ? decodeURIComponent(String(req.query.error)) : null;
|
||||
const reserved = req.query.reserved === '1';
|
||||
const notifySuccess = req.query.notify_success
|
||||
? decodeURIComponent(String(req.query.notify_success))
|
||||
: null;
|
||||
const notifyError = req.query.notify_error
|
||||
? decodeURIComponent(String(req.query.notify_error))
|
||||
: null;
|
||||
|
||||
let stockAlertSubscribed = false;
|
||||
let notifyEmail = res.locals.user?.email || '';
|
||||
if (product.stock <= 0) {
|
||||
const stockAlerts = require('../services/stock-alerts');
|
||||
if (notifyEmail) {
|
||||
stockAlertSubscribed = await stockAlerts.isSubscribed(
|
||||
product.id,
|
||||
notifyEmail,
|
||||
req.session.userId
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
res.render('product', {
|
||||
title: product.name,
|
||||
product,
|
||||
userReservation,
|
||||
error: errorMsg,
|
||||
reserved,
|
||||
notifySuccess,
|
||||
notifyError,
|
||||
stockAlertSubscribed,
|
||||
notifyEmail,
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
@@ -155,6 +198,7 @@ router.post('/cart/remove/:id', (req, res) => {
|
||||
|
||||
router.get(
|
||||
'/checkout',
|
||||
requireCookieConsent,
|
||||
requireAuth,
|
||||
asyncHandler(async (req, res) => {
|
||||
const cart = getCart(req);
|
||||
@@ -174,6 +218,7 @@ router.get(
|
||||
|
||||
router.post(
|
||||
'/checkout',
|
||||
requireCookieConsent,
|
||||
requireAuth,
|
||||
asyncHandler(async (req, res) => {
|
||||
const cart = getCart(req);
|
||||
@@ -249,6 +294,7 @@ router.post(
|
||||
|
||||
router.get(
|
||||
'/orders',
|
||||
requireCookieConsent,
|
||||
requireAuth,
|
||||
asyncHandler(async (req, res) => {
|
||||
const { rows: orders } = await query(
|
||||
@@ -264,6 +310,7 @@ router.get(
|
||||
|
||||
router.get(
|
||||
'/orders/:id',
|
||||
requireCookieConsent,
|
||||
requireAuth,
|
||||
asyncHandler(async (req, res) => {
|
||||
const { rows } = await query(
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
const express = require('express');
|
||||
const { query, formatPrice } = require('../db');
|
||||
const { getCart, cartCount } = require('../cart');
|
||||
const { requireCookieConsent } = require('../middleware/cookieConsent');
|
||||
const { asyncHandler } = require('../utils/asyncHandler');
|
||||
const stockAlerts = require('../services/stock-alerts');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.use((req, res, next) => {
|
||||
const cart = getCart(req);
|
||||
res.locals.cartCount = cartCount(cart);
|
||||
res.locals.formatPrice = formatPrice;
|
||||
next();
|
||||
});
|
||||
|
||||
const emailRe = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
|
||||
router.post(
|
||||
'/product/:slug/notify-stock',
|
||||
requireCookieConsent,
|
||||
asyncHandler(async (req, res) => {
|
||||
const slug = req.params.slug;
|
||||
const { rows } = await query('SELECT id, name, stock FROM products WHERE slug = $1', [
|
||||
slug,
|
||||
]);
|
||||
const product = rows[0];
|
||||
|
||||
if (!product) {
|
||||
return res.status(404).render('error', {
|
||||
title: 'Не найдено',
|
||||
message: 'Товар не найден',
|
||||
code: 404,
|
||||
});
|
||||
}
|
||||
|
||||
if (product.stock > 0) {
|
||||
return res.redirect(
|
||||
`/product/${slug}?notify_error=${encodeURIComponent('Товар уже в наличии')}`
|
||||
);
|
||||
}
|
||||
|
||||
let email = (req.body.email || '').trim().toLowerCase();
|
||||
if (req.session.userId) {
|
||||
const { rows: users } = await query('SELECT email FROM users WHERE id = $1', [
|
||||
req.session.userId,
|
||||
]);
|
||||
if (users[0]) email = users[0].email;
|
||||
}
|
||||
|
||||
if (!email || !emailRe.test(email)) {
|
||||
return res.redirect(
|
||||
`/product/${slug}?notify_error=${encodeURIComponent('Укажите корректный email')}`
|
||||
);
|
||||
}
|
||||
|
||||
if (await stockAlerts.isSubscribed(product.id, email, req.session.userId)) {
|
||||
return res.redirect(
|
||||
`/product/${slug}?notify_success=${encodeURIComponent('Вы уже подписаны — сообщим на почту')}`
|
||||
);
|
||||
}
|
||||
|
||||
await stockAlerts.subscribe({
|
||||
productId: product.id,
|
||||
email,
|
||||
userId: req.session.userId || null,
|
||||
});
|
||||
|
||||
res.redirect(
|
||||
`/product/${slug}?notify_success=${encodeURIComponent('Когда товар появится, отправим письмо на ' + email)}`
|
||||
);
|
||||
})
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,38 @@
|
||||
const bcrypt = require('bcryptjs');
|
||||
const { query } = require('./db');
|
||||
const { ROLES } = require('./constants/roles');
|
||||
|
||||
async function seedAdmin() {
|
||||
const email = (process.env.ADMIN_EMAIL || 'admin@site.com').trim().toLowerCase();
|
||||
const password = process.env.ADMIN_PASSWORD || 'admin';
|
||||
const name = process.env.ADMIN_NAME || 'Администратор';
|
||||
|
||||
// Только один администратор — пользователь с ADMIN_EMAIL (остальные customer)
|
||||
const { rowCount: demoted } = await query(
|
||||
`UPDATE users SET role = $1 WHERE role = $2 AND email != $3`,
|
||||
[ROLES.CUSTOMER, ROLES.ADMIN, email]
|
||||
);
|
||||
if (demoted > 0) {
|
||||
console.log('Снята роль admin у', demoted, 'пользоват(елей) — админ только:', email);
|
||||
}
|
||||
|
||||
const { rows } = await query('SELECT id, role FROM users WHERE email = $1', [email]);
|
||||
|
||||
if (!rows[0]) {
|
||||
const hash = bcrypt.hashSync(password, 10);
|
||||
await query(
|
||||
`INSERT INTO users (email, password_hash, name, role)
|
||||
VALUES ($1, $2, $3, $4)`,
|
||||
[email, hash, name, ROLES.ADMIN]
|
||||
);
|
||||
console.log('Создан администратор (единственный):', email);
|
||||
return;
|
||||
}
|
||||
|
||||
if (rows[0].role !== ROLES.ADMIN) {
|
||||
await query('UPDATE users SET role = $1 WHERE id = $2', [ROLES.ADMIN, rows[0].id]);
|
||||
console.log('Назначен единственный администратор:', email);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { seedAdmin };
|
||||
@@ -3,7 +3,6 @@ const { query } = require('./db');
|
||||
async function runSeed() {
|
||||
const { rows } = await query('SELECT COUNT(*)::int AS n FROM products');
|
||||
if (rows[0].n > 0) {
|
||||
console.log('База уже содержит товары, пропуск seed.');
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,24 @@
|
||||
const path = require('path');
|
||||
const express = require('express');
|
||||
const cookieParser = require('cookie-parser');
|
||||
const session = require('express-session');
|
||||
const pgSession = require('connect-pg-simple')(session);
|
||||
|
||||
const { pool, initSchema, checkConnection } = require('./db');
|
||||
const { runSeed } = require('./seed');
|
||||
const { seedAdmin } = require('./seed-admin');
|
||||
const { loadUser } = require('./middleware/auth');
|
||||
const { loadCookieConsent } = require('./middleware/cookieConsent');
|
||||
const healthRoutes = require('./routes/health');
|
||||
const shopRoutes = require('./routes/shop');
|
||||
const authRoutes = require('./routes/auth');
|
||||
const accountRoutes = require('./routes/account');
|
||||
const adminRoutes = require('./routes/admin');
|
||||
const cookiesRoutes = require('./routes/cookies');
|
||||
const passwordResetRoutes = require('./routes/password-reset');
|
||||
const reservationsRoutes = require('./routes/reservations');
|
||||
const passkeyRoutes = require('./routes/passkey');
|
||||
const stockAlertsRoutes = require('./routes/stock-alerts');
|
||||
|
||||
const PORT = process.env.PORT || 3000;
|
||||
const HOST = process.env.HOST || '0.0.0.0';
|
||||
@@ -18,6 +28,7 @@ async function start() {
|
||||
await checkConnection();
|
||||
await initSchema();
|
||||
await runSeed();
|
||||
await seedAdmin();
|
||||
|
||||
const app = express();
|
||||
|
||||
@@ -31,6 +42,8 @@ async function start() {
|
||||
app.use(healthRoutes);
|
||||
app.use(express.static(path.join(__dirname, 'public')));
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
app.use(express.json({ limit: '64kb' }));
|
||||
app.use(cookieParser());
|
||||
|
||||
app.use(
|
||||
session({
|
||||
@@ -51,9 +64,17 @@ async function start() {
|
||||
})
|
||||
);
|
||||
|
||||
app.use(loadCookieConsent);
|
||||
app.use(loadUser);
|
||||
app.use('/cookies', cookiesRoutes);
|
||||
app.use('/', passwordResetRoutes);
|
||||
app.use('/reservations', reservationsRoutes);
|
||||
app.use('/', stockAlertsRoutes);
|
||||
app.use('/', shopRoutes);
|
||||
app.use('/', authRoutes);
|
||||
app.use('/webauthn', passkeyRoutes);
|
||||
app.use('/account', accountRoutes);
|
||||
app.use('/admin', adminRoutes);
|
||||
|
||||
app.use((req, res) => {
|
||||
res.status(404).render('error', {
|
||||
@@ -77,7 +98,13 @@ async function start() {
|
||||
});
|
||||
|
||||
server.on('error', (err) => {
|
||||
if (err.code === 'EADDRINUSE') {
|
||||
console.error(
|
||||
`Порт ${PORT} уже занят (часто старый «npm start»). Выполните: bash scripts/free-port-3000.sh`
|
||||
);
|
||||
} else {
|
||||
console.error('Не удалось запустить сервер:', err.message);
|
||||
}
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@@ -88,8 +115,12 @@ start().catch((err) => {
|
||||
console.error(' systemctl start postgresql');
|
||||
console.error(' bash scripts/setup-postgres-ubuntu.sh');
|
||||
console.error(' Проверьте DATABASE_URL в .env');
|
||||
} else if (err.code === 'MODULE_NOT_FOUND') {
|
||||
console.error('Не найден модуль:', err.message);
|
||||
console.error(' cd', path.join(__dirname, '..'), '&& npm install --omit=dev');
|
||||
} else {
|
||||
console.error('Ошибка запуска:', err.message);
|
||||
if (err.stack) console.error(err.stack);
|
||||
}
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
const nodemailer = require('nodemailer');
|
||||
|
||||
let transporter = null;
|
||||
|
||||
function isConfigured() {
|
||||
return Boolean(process.env.SMTP_HOST && process.env.SMTP_FROM);
|
||||
}
|
||||
|
||||
function getTransporter() {
|
||||
if (!isConfigured()) return null;
|
||||
if (!transporter) {
|
||||
transporter = nodemailer.createTransport({
|
||||
host: process.env.SMTP_HOST,
|
||||
port: parseInt(process.env.SMTP_PORT || '587', 10),
|
||||
secure: process.env.SMTP_SECURE === 'true',
|
||||
auth:
|
||||
process.env.SMTP_USER && process.env.SMTP_PASS
|
||||
? { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS }
|
||||
: undefined,
|
||||
});
|
||||
}
|
||||
return transporter;
|
||||
}
|
||||
|
||||
function siteUrl() {
|
||||
return (process.env.SITE_URL || 'http://localhost:3000').replace(/\/$/, '');
|
||||
}
|
||||
|
||||
async function sendMail({ to, subject, text, html }) {
|
||||
const from = process.env.SMTP_FROM || 'shop@localhost';
|
||||
const payload = { from, to, subject, text, html: html || text };
|
||||
|
||||
const transport = getTransporter();
|
||||
if (!transport) {
|
||||
console.log('--- Email (SMTP не настроен) ---');
|
||||
console.log('To:', to);
|
||||
console.log('Subject:', subject);
|
||||
console.log(text);
|
||||
console.log('--------------------------------');
|
||||
return { logged: true };
|
||||
}
|
||||
|
||||
await transport.sendMail(payload);
|
||||
return { sent: true };
|
||||
}
|
||||
|
||||
async function sendPasswordResetEmail(to, resetLink) {
|
||||
const subject = 'Сброс пароля — Shop';
|
||||
const text = `Вы запросили сброс пароля.\n\nПерейдите по ссылке (действует 1 час):\n${resetLink}\n\nЕсли это были не вы, проигнорируйте письмо.`;
|
||||
const html = `
|
||||
<p>Вы запросили сброс пароля в магазине Shop.</p>
|
||||
<p><a href="${resetLink}">Сбросить пароль</a></p>
|
||||
<p>Ссылка действует <strong>1 час</strong>.</p>
|
||||
<p style="color:#666">Если вы не запрашивали сброс, просто удалите это письмо.</p>
|
||||
`;
|
||||
return sendMail({ to, subject, text, html });
|
||||
}
|
||||
|
||||
async function sendReservationEmail(to, productName, quantity, expiresAt) {
|
||||
const subject = `Бронирование: ${productName}`;
|
||||
const exp = new Date(expiresAt).toLocaleString('ru-RU');
|
||||
const text = `Товар «${productName}» забронирован (${quantity} шт.) до ${exp}.\n\n${siteUrl()}/account?tab=reservations`;
|
||||
const html = `
|
||||
<p>Вы забронировали <strong>${productName}</strong> — ${quantity} шт.</p>
|
||||
<p>Бронь активна до: <strong>${exp}</strong></p>
|
||||
<p><a href="${siteUrl()}/account?tab=reservations">Мои бронирования</a></p>
|
||||
`;
|
||||
return sendMail({ to, subject, text, html });
|
||||
}
|
||||
|
||||
async function sendStockAvailableEmail(to, productName, productUrl) {
|
||||
const subject = `Снова в наличии: ${productName}`;
|
||||
const text = `Товар «${productName}» снова в наличии.\n\nПерейти: ${productUrl}`;
|
||||
const html = `
|
||||
<p>Товар <strong>${productName}</strong> снова в наличии.</p>
|
||||
<p><a href="${productUrl}">Открыть товар в магазине</a></p>
|
||||
<p style="color:#666">Вы получили это письмо, потому что подписались на уведомление о поступлении.</p>
|
||||
`;
|
||||
return sendMail({ to, subject, text, html });
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
isConfigured,
|
||||
sendMail,
|
||||
sendPasswordResetEmail,
|
||||
sendReservationEmail,
|
||||
sendStockAvailableEmail,
|
||||
siteUrl,
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
const { query } = require('../db');
|
||||
|
||||
async function expireOldReservations() {
|
||||
await query(
|
||||
`UPDATE reservations SET status = 'expired'
|
||||
WHERE status = 'active' AND expires_at < NOW()`
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = { expireOldReservations };
|
||||
@@ -0,0 +1,74 @@
|
||||
const { query } = require('../db');
|
||||
const { sendStockAvailableEmail, siteUrl } = require('./mail');
|
||||
|
||||
async function isSubscribed(productId, email, userId) {
|
||||
const normalized = email.trim().toLowerCase();
|
||||
const params = [productId, normalized];
|
||||
let sql = `SELECT 1 FROM product_stock_alerts
|
||||
WHERE product_id = $1 AND notified_at IS NULL
|
||||
AND (email = $2`;
|
||||
if (userId) {
|
||||
sql += ' OR user_id = $3';
|
||||
params.push(userId);
|
||||
}
|
||||
sql += ')';
|
||||
const { rows } = await query(sql, params);
|
||||
return rows.length > 0;
|
||||
}
|
||||
|
||||
async function subscribe({ productId, email, userId }) {
|
||||
const normalized = email.trim().toLowerCase();
|
||||
await query(
|
||||
`INSERT INTO product_stock_alerts (product_id, email, user_id)
|
||||
VALUES ($1, $2, $3)
|
||||
ON CONFLICT (product_id, email) DO UPDATE SET
|
||||
user_id = COALESCE(EXCLUDED.user_id, product_stock_alerts.user_id),
|
||||
notified_at = NULL,
|
||||
created_at = CASE
|
||||
WHEN product_stock_alerts.notified_at IS NOT NULL THEN NOW()
|
||||
ELSE product_stock_alerts.created_at
|
||||
END`,
|
||||
[productId, normalized, userId || null]
|
||||
);
|
||||
}
|
||||
|
||||
async function notifyIfBackInStock(productId) {
|
||||
const { rows: products } = await query(
|
||||
'SELECT id, slug, name, stock FROM products WHERE id = $1',
|
||||
[productId]
|
||||
);
|
||||
const product = products[0];
|
||||
if (!product || product.stock <= 0) return { sent: 0 };
|
||||
|
||||
const { rows: alerts } = await query(
|
||||
`SELECT id, email FROM product_stock_alerts
|
||||
WHERE product_id = $1 AND notified_at IS NULL`,
|
||||
[productId]
|
||||
);
|
||||
|
||||
if (!alerts.length) return { sent: 0 };
|
||||
|
||||
const productUrl = `${siteUrl()}/product/${product.slug}`;
|
||||
let sent = 0;
|
||||
|
||||
for (const alert of alerts) {
|
||||
try {
|
||||
await sendStockAvailableEmail(alert.email, product.name, productUrl);
|
||||
await query(
|
||||
'UPDATE product_stock_alerts SET notified_at = NOW() WHERE id = $1',
|
||||
[alert.id]
|
||||
);
|
||||
sent++;
|
||||
} catch (err) {
|
||||
console.error('stock alert email failed:', alert.email, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
return { sent };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
isSubscribed,
|
||||
subscribe,
|
||||
notifyIfBackInStock,
|
||||
};
|
||||
@@ -0,0 +1,242 @@
|
||||
const crypto = require('crypto');
|
||||
const {
|
||||
generateRegistrationOptions,
|
||||
verifyRegistrationResponse,
|
||||
generateAuthenticationOptions,
|
||||
verifyAuthenticationResponse,
|
||||
} = require('@simplewebauthn/server');
|
||||
const { isoBase64URL } = require('@simplewebauthn/server/helpers');
|
||||
const { query } = require('../db');
|
||||
|
||||
function getRpId() {
|
||||
if (process.env.WEBAUTHN_RP_ID) {
|
||||
return process.env.WEBAUTHN_RP_ID.trim();
|
||||
}
|
||||
const site = process.env.SITE_URL || 'http://localhost:3000';
|
||||
try {
|
||||
return new URL(site).hostname;
|
||||
} catch {
|
||||
return 'localhost';
|
||||
}
|
||||
}
|
||||
|
||||
function getRpName() {
|
||||
return process.env.WEBAUTHN_RP_NAME || 'Shop';
|
||||
}
|
||||
|
||||
function getOrigins() {
|
||||
const list = [];
|
||||
if (process.env.SITE_URL) list.push(process.env.SITE_URL.replace(/\/$/, ''));
|
||||
if (process.env.WEBAUTHN_ORIGIN) {
|
||||
process.env.WEBAUTHN_ORIGIN.split(',').forEach((o) => {
|
||||
const t = o.trim().replace(/\/$/, '');
|
||||
if (t) list.push(t);
|
||||
});
|
||||
}
|
||||
if (!list.length) list.push('http://localhost:3000');
|
||||
const expanded = [...list];
|
||||
for (const o of list) {
|
||||
if (o.includes('localhost')) {
|
||||
expanded.push(o.replace('localhost', '127.0.0.1'));
|
||||
}
|
||||
}
|
||||
return [...new Set(expanded)];
|
||||
}
|
||||
|
||||
function getOriginFromRequest(req) {
|
||||
const proto = req.get('x-forwarded-proto') || req.protocol;
|
||||
const host = req.get('x-forwarded-host') || req.get('host');
|
||||
return `${proto}://${host}`.replace(/\/$/, '');
|
||||
}
|
||||
|
||||
function assertOrigin(req) {
|
||||
const origin = getOriginFromRequest(req);
|
||||
const allowed = getOrigins();
|
||||
if (!allowed.includes(origin)) {
|
||||
const err = new Error('Недопустимый origin для WebAuthn');
|
||||
err.status = 400;
|
||||
throw err;
|
||||
}
|
||||
return origin;
|
||||
}
|
||||
|
||||
function userIdToBuffer(userId) {
|
||||
const buf = Buffer.alloc(8);
|
||||
buf.writeBigUInt64BE(BigInt(userId), 0);
|
||||
return new Uint8Array(buf);
|
||||
}
|
||||
|
||||
async function getCredentialsForUser(userId) {
|
||||
const { rows } = await query(
|
||||
`SELECT id, credential_id, public_key, counter, device_type, backed_up, transports, label, created_at
|
||||
FROM webauthn_credentials WHERE user_id = $1 ORDER BY created_at`,
|
||||
[userId]
|
||||
);
|
||||
return rows;
|
||||
}
|
||||
|
||||
function rowToAuthenticator(row) {
|
||||
return {
|
||||
id: row.credential_id,
|
||||
publicKey: row.public_key,
|
||||
counter: Number(row.counter),
|
||||
transports: row.transports ? row.transports.split(',') : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
async function generateRegisterOptions(user, excludeIds = []) {
|
||||
const credentials = await getCredentialsForUser(user.id);
|
||||
return generateRegistrationOptions({
|
||||
rpName: getRpName(),
|
||||
rpID: getRpId(),
|
||||
userName: user.email,
|
||||
userDisplayName: user.name,
|
||||
userID: userIdToBuffer(user.id),
|
||||
attestationType: 'none',
|
||||
excludeCredentials: credentials.map((c) => ({
|
||||
id: c.credential_id,
|
||||
transports: c.transports ? c.transports.split(',') : undefined,
|
||||
})),
|
||||
authenticatorSelection: {
|
||||
residentKey: 'preferred',
|
||||
userVerification: 'preferred',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function verifyRegister(user, response, expectedChallenge, expectedOrigin) {
|
||||
const verification = await verifyRegistrationResponse({
|
||||
response,
|
||||
expectedChallenge,
|
||||
expectedOrigin,
|
||||
expectedRPID: getRpId(),
|
||||
requireUserVerification: false,
|
||||
});
|
||||
|
||||
if (!verification.verified || !verification.registrationInfo) {
|
||||
return { verified: false };
|
||||
}
|
||||
|
||||
const { credential, credentialDeviceType, credentialBackedUp } =
|
||||
verification.registrationInfo;
|
||||
|
||||
const credentialId =
|
||||
typeof credential.id === 'string'
|
||||
? credential.id
|
||||
: isoBase64URL.fromBuffer(credential.id);
|
||||
const label =
|
||||
credentialDeviceType === 'singleDevice' ? 'Это устройство' : 'Passkey';
|
||||
|
||||
await query(
|
||||
`INSERT INTO webauthn_credentials
|
||||
(user_id, credential_id, public_key, counter, device_type, backed_up, transports, label)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
|
||||
[
|
||||
user.id,
|
||||
credentialId,
|
||||
Buffer.from(credential.publicKey),
|
||||
credential.counter,
|
||||
credentialDeviceType,
|
||||
credentialBackedUp,
|
||||
credential.transports?.join(',') || null,
|
||||
label,
|
||||
]
|
||||
);
|
||||
|
||||
await query('UPDATE users SET passkey_enabled = true WHERE id = $1', [user.id]);
|
||||
|
||||
return { verified: true };
|
||||
}
|
||||
|
||||
async function generateLoginOptions(email) {
|
||||
const { rows } = await query(
|
||||
`SELECT id, email, name, passkey_enabled FROM users WHERE email = $1`,
|
||||
[email.trim().toLowerCase()]
|
||||
);
|
||||
const user = rows[0];
|
||||
if (!user || !user.passkey_enabled) {
|
||||
return { user: null, options: null };
|
||||
}
|
||||
|
||||
const credentials = await getCredentialsForUser(user.id);
|
||||
if (!credentials.length) {
|
||||
return { user: null, options: null };
|
||||
}
|
||||
|
||||
const options = await generateAuthenticationOptions({
|
||||
rpID: getRpId(),
|
||||
allowCredentials: credentials.map((c) => ({
|
||||
id: c.credential_id,
|
||||
transports: c.transports ? c.transports.split(',') : undefined,
|
||||
})),
|
||||
userVerification: 'preferred',
|
||||
});
|
||||
|
||||
return { user, options };
|
||||
}
|
||||
|
||||
async function verifyLogin(user, response, expectedChallenge, expectedOrigin) {
|
||||
const credentialId = response.id;
|
||||
const { rows } = await query(
|
||||
`SELECT * FROM webauthn_credentials WHERE user_id = $1 AND credential_id = $2`,
|
||||
[user.id, credentialId]
|
||||
);
|
||||
const row = rows[0];
|
||||
if (!row) {
|
||||
return { verified: false };
|
||||
}
|
||||
|
||||
const verification = await verifyAuthenticationResponse({
|
||||
response,
|
||||
expectedChallenge,
|
||||
expectedOrigin,
|
||||
expectedRPID: getRpId(),
|
||||
credential: rowToAuthenticator(row),
|
||||
requireUserVerification: false,
|
||||
});
|
||||
|
||||
if (!verification.verified) {
|
||||
return { verified: false };
|
||||
}
|
||||
|
||||
const { newCounter } = verification.authenticationInfo;
|
||||
await query('UPDATE webauthn_credentials SET counter = $1 WHERE id = $2', [
|
||||
newCounter,
|
||||
row.id,
|
||||
]);
|
||||
|
||||
return { verified: true };
|
||||
}
|
||||
|
||||
async function disablePasskeys(userId) {
|
||||
await query('DELETE FROM webauthn_credentials WHERE user_id = $1', [userId]);
|
||||
await query('UPDATE users SET passkey_enabled = false WHERE id = $1', [userId]);
|
||||
}
|
||||
|
||||
async function deleteCredential(userId, credentialDbId) {
|
||||
const { rowCount } = await query(
|
||||
'DELETE FROM webauthn_credentials WHERE id = $1 AND user_id = $2',
|
||||
[credentialDbId, userId]
|
||||
);
|
||||
const remaining = await query(
|
||||
'SELECT COUNT(*)::int AS n FROM webauthn_credentials WHERE user_id = $1',
|
||||
[userId]
|
||||
);
|
||||
if (remaining.rows[0].n === 0) {
|
||||
await query('UPDATE users SET passkey_enabled = false WHERE id = $1', [userId]);
|
||||
}
|
||||
return rowCount > 0;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getRpId,
|
||||
getOrigins,
|
||||
assertOrigin,
|
||||
getCredentialsForUser,
|
||||
generateRegisterOptions,
|
||||
verifyRegister,
|
||||
generateLoginOptions,
|
||||
verifyLogin,
|
||||
disablePasskeys,
|
||||
deleteCredential,
|
||||
};
|
||||
@@ -1,15 +0,0 @@
|
||||
<%- include('partials/layout-start') %>
|
||||
|
||||
<div class="account">
|
||||
<h1>Личный кабинет</h1>
|
||||
<div class="card account-card">
|
||||
<p><strong><%= user.name %></strong></p>
|
||||
<p class="muted"><%= user.email %></p>
|
||||
<p class="muted">С нами с <%= new Date(user.created_at).toLocaleDateString('ru-RU') %></p>
|
||||
<div class="account-actions">
|
||||
<a href="/orders" class="btn btn--primary">Мои заказы (<%= orderCount %>)</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<%- include('partials/layout-end') %>
|
||||
@@ -0,0 +1,195 @@
|
||||
<%- include('../partials/layout-start') %>
|
||||
|
||||
<div class="account">
|
||||
<h1>Личный кабинет</h1>
|
||||
|
||||
<% if (success) { %><p class="alert alert--success"><%= success %></p><% } %>
|
||||
<% if (error) { %><p class="alert alert--error"><%= error %></p><% } %>
|
||||
|
||||
<nav class="account-tabs" aria-label="Разделы профиля">
|
||||
<a href="/account?tab=profile" class="account-tabs__link <%= activeTab === 'profile' ? 'account-tabs__link--active' : '' %>">Профиль</a>
|
||||
<a href="/account?tab=email" class="account-tabs__link <%= activeTab === 'email' ? 'account-tabs__link--active' : '' %>">Смена email</a>
|
||||
<a href="/account?tab=password" class="account-tabs__link <%= activeTab === 'password' ? 'account-tabs__link--active' : '' %>">Смена пароля</a>
|
||||
<a href="/account?tab=passkey" class="account-tabs__link <%= activeTab === 'passkey' ? 'account-tabs__link--active' : '' %>">Passkey</a>
|
||||
<a href="/account?tab=reservations" class="account-tabs__link <%= activeTab === 'reservations' ? 'account-tabs__link--active' : '' %>">Бронирования</a>
|
||||
</nav>
|
||||
|
||||
<% if (activeTab === 'profile') { %>
|
||||
<div class="account-grid">
|
||||
<section class="card account-section">
|
||||
<h2>Мой профиль</h2>
|
||||
<dl class="profile-dl">
|
||||
<dt>ID</dt>
|
||||
<dd><%= user.id %></dd>
|
||||
<dt>Email</dt>
|
||||
<dd><%= user.email %></dd>
|
||||
<dt>Роль</dt>
|
||||
<dd><span class="role-badge role-badge--<%= user.role %>"><%= roleLabels[user.role] || user.role %></span></dd>
|
||||
<dt>Регистрация</dt>
|
||||
<dd><%= new Date(user.created_at).toLocaleString('ru-RU') %></dd>
|
||||
<dt>Заказов</dt>
|
||||
<dd><%= orderCount %></dd>
|
||||
</dl>
|
||||
<div class="account-actions">
|
||||
<a href="/orders" class="btn btn--primary">Мои заказы</a>
|
||||
<% if (isAdmin) { %>
|
||||
<a href="/admin" class="btn btn--admin">Админ-панель</a>
|
||||
<% } %>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card account-section">
|
||||
<h2>Изменить имя</h2>
|
||||
<form action="/account/profile" method="post" class="form">
|
||||
<label class="label">
|
||||
Имя
|
||||
<input type="text" name="name" class="input" required value="<%= user.name %>" autocomplete="name">
|
||||
</label>
|
||||
<button type="submit" class="btn btn--primary">Сохранить</button>
|
||||
</form>
|
||||
</section>
|
||||
</div>
|
||||
<% } %>
|
||||
|
||||
<% if (activeTab === 'email') { %>
|
||||
<section class="card account-section account-section--narrow">
|
||||
<h2>Смена email</h2>
|
||||
<p class="muted">Текущий email: <strong><%= user.email %></strong></p>
|
||||
<form action="/account/email" method="post" class="form">
|
||||
<label class="label">
|
||||
Новый email
|
||||
<input type="email" name="email" class="input" required autocomplete="email">
|
||||
</label>
|
||||
<label class="label">
|
||||
Текущий пароль (подтверждение)
|
||||
<input type="password" name="current_password" class="input" required autocomplete="current-password">
|
||||
</label>
|
||||
<button type="submit" class="btn btn--primary">Изменить email</button>
|
||||
</form>
|
||||
</section>
|
||||
<% } %>
|
||||
|
||||
<% if (activeTab === 'reservations') { %>
|
||||
<section class="card account-section">
|
||||
<h2>Мои бронирования</h2>
|
||||
<% if (!reservations.length) { %>
|
||||
<p class="muted">Активных броней нет.</p>
|
||||
<% } else { %>
|
||||
<table class="cart-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Товар</th>
|
||||
<th>Кол-во</th>
|
||||
<th>Статус</th>
|
||||
<th>До</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<% const resStatus = { active: 'Активна', fulfilled: 'Выполнена', cancelled: 'Отменена', expired: 'Истекла' }; %>
|
||||
<% reservations.forEach(r => { %>
|
||||
<tr>
|
||||
<td><a href="/product/<%= r.product_slug %>"><%= r.product_name %></a></td>
|
||||
<td><%= r.quantity %></td>
|
||||
<td><span class="status status--<%= r.status === 'active' ? 'pending' : r.status %>"><%= resStatus[r.status] || r.status %></span></td>
|
||||
<td><%= r.status === 'active' ? new Date(r.expires_at).toLocaleString('ru-RU') : '—' %></td>
|
||||
<td>
|
||||
<% if (r.status === 'active') { %>
|
||||
<form action="/reservations/<%= r.id %>/cancel" method="post" class="inline-form">
|
||||
<button type="submit" class="btn btn--ghost btn--sm">Отменить</button>
|
||||
</form>
|
||||
<% } %>
|
||||
</td>
|
||||
</tr>
|
||||
<% }) %>
|
||||
</tbody>
|
||||
</table>
|
||||
<% } %>
|
||||
</section>
|
||||
<% } %>
|
||||
|
||||
<% if (activeTab === 'passkey') { %>
|
||||
<section class="card account-section account-section--narrow">
|
||||
<h2>Вход по passkey</h2>
|
||||
<p class="muted">
|
||||
Passkey — вход по отпечатку, Face ID или PIN устройства. Пароль остаётся доступен.
|
||||
Включение необязательно: привяжите ключ, когда будете готовы.
|
||||
</p>
|
||||
|
||||
<% if (user.passkey_enabled) { %>
|
||||
<p class="alert alert--success" style="margin-bottom:1rem">Passkey включён</p>
|
||||
<% } else { %>
|
||||
<p class="muted" style="margin-bottom:1rem">Passkey не настроен</p>
|
||||
<% } %>
|
||||
|
||||
<% if (passkeys.length) { %>
|
||||
<ul class="passkey-list">
|
||||
<% passkeys.forEach(pk => { %>
|
||||
<li class="passkey-list__item">
|
||||
<span><strong><%= pk.label %></strong> · с <%= new Date(pk.created_at).toLocaleDateString('ru-RU') %></span>
|
||||
<form action="/account/passkey/credentials/<%= pk.id %>/delete" method="post" class="inline-form">
|
||||
<input type="password" name="current_password" class="input input--sm" placeholder="Пароль" required autocomplete="current-password" aria-label="Пароль для удаления">
|
||||
<button type="submit" class="btn btn--ghost btn--sm">Удалить</button>
|
||||
</form>
|
||||
</li>
|
||||
<% }) %>
|
||||
</ul>
|
||||
<% } %>
|
||||
|
||||
<div class="passkey-actions">
|
||||
<p id="passkey-register-error" class="alert alert--error" hidden></p>
|
||||
<label class="label">
|
||||
Текущий пароль (для привязки нового ключа)
|
||||
<input type="password" id="passkey-register-password" class="input" autocomplete="current-password">
|
||||
</label>
|
||||
<button type="button" id="passkey-register-btn" class="btn btn--primary">Привязать passkey</button>
|
||||
</div>
|
||||
|
||||
<% if (user.passkey_enabled) { %>
|
||||
<hr class="divider">
|
||||
<h3>Отключить passkey</h3>
|
||||
<p class="muted">Все привязанные ключи будут удалены. Вход только по паролю.</p>
|
||||
<form action="/account/passkey/disable" method="post" class="form">
|
||||
<label class="label">
|
||||
Текущий пароль
|
||||
<input type="password" name="current_password" class="input" required autocomplete="current-password">
|
||||
</label>
|
||||
<button type="submit" class="btn btn--ghost">Отключить passkey</button>
|
||||
</form>
|
||||
<% } %>
|
||||
</section>
|
||||
<script src="/js/passkey.js"></script>
|
||||
<script>
|
||||
document.getElementById('passkey-register-btn')?.addEventListener('click', function () {
|
||||
ShopPasskey.registerPasskey(
|
||||
document.getElementById('passkey-register-password'),
|
||||
document.getElementById('passkey-register-error'),
|
||||
this
|
||||
);
|
||||
});
|
||||
</script>
|
||||
<% } %>
|
||||
|
||||
<% if (activeTab === 'password') { %>
|
||||
<section class="card account-section account-section--narrow">
|
||||
<h2>Смена пароля</h2>
|
||||
<form action="/account/password" method="post" class="form">
|
||||
<label class="label">
|
||||
Текущий пароль
|
||||
<input type="password" name="current_password" class="input" required autocomplete="current-password">
|
||||
</label>
|
||||
<label class="label">
|
||||
Новый пароль
|
||||
<input type="password" name="password" class="input" required minlength="6" autocomplete="new-password">
|
||||
</label>
|
||||
<label class="label">
|
||||
Повторите новый пароль
|
||||
<input type="password" name="password2" class="input" required minlength="6" autocomplete="new-password">
|
||||
</label>
|
||||
<button type="submit" class="btn btn--primary">Изменить пароль</button>
|
||||
</form>
|
||||
</section>
|
||||
<% } %>
|
||||
</div>
|
||||
|
||||
<%- include('../partials/layout-end') %>
|
||||
@@ -0,0 +1,63 @@
|
||||
<%- include('../partials/layout-start') %>
|
||||
|
||||
<div class="admin-header">
|
||||
<h1>Админ-панель</h1>
|
||||
<nav class="admin-nav">
|
||||
<a href="/admin" class="admin-nav__link admin-nav__link--active">Обзор</a>
|
||||
<a href="/admin/orders" class="admin-nav__link">Заказы</a>
|
||||
<a href="/admin/users" class="admin-nav__link">Пользователи</a>
|
||||
<a href="/admin/products" class="admin-nav__link">Товары</a>
|
||||
<a href="/admin/reservations" class="admin-nav__link">Бронирования</a>
|
||||
<a href="/" class="admin-nav__link">В магазин</a>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<div class="stats-grid">
|
||||
<div class="stat-card">
|
||||
<span class="stat-card__label">Пользователи</span>
|
||||
<strong class="stat-card__value"><%= stats.users %></strong>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<span class="stat-card__label">Товары</span>
|
||||
<strong class="stat-card__value"><%= stats.products %></strong>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<span class="stat-card__label">Заказы</span>
|
||||
<strong class="stat-card__value"><%= stats.orders %></strong>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<span class="stat-card__label">Выручка</span>
|
||||
<strong class="stat-card__value"><%= formatPrice(stats.revenue) %></strong>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2>Последние заказы</h2>
|
||||
<% if (!recentOrders.length) { %>
|
||||
<p class="muted">Заказов пока нет.</p>
|
||||
<% } else { %>
|
||||
<table class="cart-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>№</th>
|
||||
<th>Клиент</th>
|
||||
<th>Статус</th>
|
||||
<th>Сумма</th>
|
||||
<th>Дата</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<% const statusLabels = { pending: 'Ожидает', paid: 'Оплачен', shipped: 'Отправлен', cancelled: 'Отменён' }; %>
|
||||
<% recentOrders.forEach(o => { %>
|
||||
<tr>
|
||||
<td>#<%= o.id %></td>
|
||||
<td><%= o.customer_name %><br><span class="muted"><%= o.user_email %></span></td>
|
||||
<td><span class="status status--<%= o.status %>"><%= statusLabels[o.status] || o.status %></span></td>
|
||||
<td><%= formatPrice(o.total_cents) %></td>
|
||||
<td><%= new Date(o.created_at).toLocaleString('ru-RU') %></td>
|
||||
</tr>
|
||||
<% }) %>
|
||||
</tbody>
|
||||
</table>
|
||||
<% } %>
|
||||
|
||||
<%- include('../partials/layout-end') %>
|
||||
@@ -0,0 +1,54 @@
|
||||
<%- include('../partials/layout-start') %>
|
||||
|
||||
<div class="admin-header">
|
||||
<h1>Заказы</h1>
|
||||
<nav class="admin-nav">
|
||||
<a href="/admin" class="admin-nav__link">Обзор</a>
|
||||
<a href="/admin/orders" class="admin-nav__link admin-nav__link--active">Заказы</a>
|
||||
<a href="/admin/users" class="admin-nav__link">Пользователи</a>
|
||||
<a href="/admin/products" class="admin-nav__link">Товары</a>
|
||||
<a href="/admin/reservations" class="admin-nav__link">Бронирования</a>
|
||||
<a href="/" class="admin-nav__link">В магазин</a>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<% const statusLabels = { pending: 'Ожидает', paid: 'Оплачен', shipped: 'Отправлен', cancelled: 'Отменён' }; %>
|
||||
|
||||
<table class="cart-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>№</th>
|
||||
<th>Клиент</th>
|
||||
<th>Статус</th>
|
||||
<th>Сумма</th>
|
||||
<th>Дата</th>
|
||||
<th>Действие</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<% orders.forEach(o => { %>
|
||||
<tr>
|
||||
<td>#<%= o.id %></td>
|
||||
<td>
|
||||
<%= o.customer_name %><br>
|
||||
<span class="muted"><%= o.customer_email %></span>
|
||||
</td>
|
||||
<td><span class="status status--<%= o.status %>"><%= statusLabels[o.status] || o.status %></span></td>
|
||||
<td><%= formatPrice(o.total_cents) %></td>
|
||||
<td><%= new Date(o.created_at).toLocaleString('ru-RU') %></td>
|
||||
<td>
|
||||
<form method="post" action="/admin/orders/<%= o.id %>/status" class="inline-form admin-status-form">
|
||||
<select name="status" class="input input--sm">
|
||||
<% ['pending','paid','shipped','cancelled'].forEach(s => { %>
|
||||
<option value="<%= s %>" <%= o.status === s ? 'selected' : '' %>><%= statusLabels[s] %></option>
|
||||
<% }) %>
|
||||
</select>
|
||||
<button type="submit" class="btn btn--ghost btn--sm">OK</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
<% }) %>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<%- include('../partials/layout-end') %>
|
||||
@@ -0,0 +1,59 @@
|
||||
<%- include('../partials/layout-start') %>
|
||||
|
||||
<div class="admin-header">
|
||||
<h1>Товары</h1>
|
||||
<nav class="admin-nav">
|
||||
<a href="/admin" class="admin-nav__link">Обзор</a>
|
||||
<a href="/admin/orders" class="admin-nav__link">Заказы</a>
|
||||
<a href="/admin/users" class="admin-nav__link">Пользователи</a>
|
||||
<a href="/admin/products" class="admin-nav__link admin-nav__link--active">Товары</a>
|
||||
<a href="/admin/reservations" class="admin-nav__link">Бронирования</a>
|
||||
<a href="/" class="admin-nav__link">В магазин</a>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<% if (stockUpdated) { %>
|
||||
<p class="alert alert--success">
|
||||
Остаток обновлён.<% if (notified > 0) { %> Отправлено уведомлений подписчикам: <%= notified %>.<% } %>
|
||||
</p>
|
||||
<% } %>
|
||||
|
||||
<table class="cart-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Название</th>
|
||||
<th>Категория</th>
|
||||
<th>Цена</th>
|
||||
<th>Остаток</th>
|
||||
<th>Подписки</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<% products.forEach(p => { %>
|
||||
<tr>
|
||||
<td><%= p.id %></td>
|
||||
<td><%= p.name %></td>
|
||||
<td><%= p.category_name || '—' %></td>
|
||||
<td><%= formatPrice(p.price_cents) %></td>
|
||||
<td>
|
||||
<form action="/admin/products/<%= p.id %>/stock" method="post" class="inline-form admin-stock-form">
|
||||
<input type="number" name="stock" class="input input--sm" min="0" value="<%= p.stock %>" aria-label="Остаток">
|
||||
<button type="submit" class="btn btn--ghost btn--sm">OK</button>
|
||||
</form>
|
||||
</td>
|
||||
<td>
|
||||
<% if (p.alert_count > 0) { %>
|
||||
<span class="badge" title="Ждут уведомления"><%= p.alert_count %></span>
|
||||
<% } else { %>
|
||||
—
|
||||
<% } %>
|
||||
</td>
|
||||
<td><a href="/product/<%= p.slug %>">На сайте</a></td>
|
||||
</tr>
|
||||
<% }) %>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<%- include('../partials/layout-end') %>
|
||||
@@ -0,0 +1,53 @@
|
||||
<%- include('../partials/layout-start') %>
|
||||
|
||||
<div class="admin-header">
|
||||
<h1>Бронирования</h1>
|
||||
<nav class="admin-nav">
|
||||
<a href="/admin" class="admin-nav__link">Обзор</a>
|
||||
<a href="/admin/orders" class="admin-nav__link">Заказы</a>
|
||||
<a href="/admin/users" class="admin-nav__link">Пользователи</a>
|
||||
<a href="/admin/products" class="admin-nav__link">Товары</a>
|
||||
<a href="/admin/reservations" class="admin-nav__link admin-nav__link--active">Бронирования</a>
|
||||
<a href="/" class="admin-nav__link">В магазин</a>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<% const resStatus = { active: 'Активна', fulfilled: 'Выполнена', cancelled: 'Отменена', expired: 'Истекла' }; %>
|
||||
|
||||
<table class="cart-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>№</th>
|
||||
<th>Клиент</th>
|
||||
<th>Товар</th>
|
||||
<th>Кол-во</th>
|
||||
<th>Статус</th>
|
||||
<th>До</th>
|
||||
<th>Действие</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<% reservations.forEach(r => { %>
|
||||
<tr>
|
||||
<td>#<%= r.id %></td>
|
||||
<td><%= r.user_name %><br><span class="muted"><%= r.user_email %></span></td>
|
||||
<td><%= r.product_name %></td>
|
||||
<td><%= r.quantity %></td>
|
||||
<td><span class="status status--<%= r.status === 'active' ? 'pending' : r.status %>"><%= resStatus[r.status] || r.status %></span></td>
|
||||
<td><%= r.status === 'active' ? new Date(r.expires_at).toLocaleString('ru-RU') : '—' %></td>
|
||||
<td>
|
||||
<form method="post" action="/admin/reservations/<%= r.id %>/status" class="admin-status-form">
|
||||
<select name="status" class="input input--sm">
|
||||
<% ['active','fulfilled','cancelled','expired'].forEach(s => { %>
|
||||
<option value="<%= s %>" <%= r.status === s ? 'selected' : '' %>><%= resStatus[s] %></option>
|
||||
<% }) %>
|
||||
</select>
|
||||
<button type="submit" class="btn btn--ghost btn--sm">OK</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
<% }) %>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<%- include('../partials/layout-end') %>
|
||||
@@ -0,0 +1,45 @@
|
||||
<%- include('../partials/layout-start') %>
|
||||
|
||||
<div class="admin-header">
|
||||
<h1>Пользователи</h1>
|
||||
<nav class="admin-nav">
|
||||
<a href="/admin" class="admin-nav__link">Обзор</a>
|
||||
<a href="/admin/orders" class="admin-nav__link">Заказы</a>
|
||||
<a href="/admin/users" class="admin-nav__link admin-nav__link--active">Пользователи</a>
|
||||
<a href="/admin/products" class="admin-nav__link">Товары</a>
|
||||
<a href="/admin/reservations" class="admin-nav__link">Бронирования</a>
|
||||
<a href="/" class="admin-nav__link">В магазин</a>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<p class="muted admin-hint">
|
||||
Один администратор — зарегистрированный пользователь с email из <code>ADMIN_EMAIL</code> в <code>.env</code>.
|
||||
Остальные при регистрации получают роль «Клиент».
|
||||
</p>
|
||||
|
||||
<table class="cart-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Имя</th>
|
||||
<th>Email</th>
|
||||
<th>Роль</th>
|
||||
<th>Регистрация</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<% users.forEach(u => { %>
|
||||
<tr>
|
||||
<td><%= u.id %></td>
|
||||
<td><%= u.name %></td>
|
||||
<td><%= u.email %></td>
|
||||
<td>
|
||||
<span class="role-badge role-badge--<%= u.role %>"><%= roleLabels[u.role] || u.role %></span>
|
||||
</td>
|
||||
<td><%= new Date(u.created_at).toLocaleString('ru-RU') %></td>
|
||||
</tr>
|
||||
<% }) %>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<%- include('../partials/layout-end') %>
|
||||
@@ -0,0 +1,18 @@
|
||||
<%- include('../partials/layout-start') %>
|
||||
|
||||
<div class="auth">
|
||||
<form action="/forgot-password" method="post" class="form card">
|
||||
<h1>Сброс пароля</h1>
|
||||
<% if (error) { %><p class="alert alert--error"><%= error %></p><% } %>
|
||||
<% if (success) { %><p class="alert alert--success"><%= success %></p><% } %>
|
||||
<p class="muted">Укажите email аккаунта — отправим ссылку для нового пароля.</p>
|
||||
<label class="label">
|
||||
Email
|
||||
<input type="email" name="email" class="input" required value="<%= values.email || '' %>" autocomplete="email">
|
||||
</label>
|
||||
<button type="submit" class="btn btn--primary btn--block">Отправить ссылку</button>
|
||||
<p class="form-footer"><a href="/login">← Вход</a></p>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<%- include('../partials/layout-end') %>
|
||||
@@ -0,0 +1,11 @@
|
||||
<%- include('../partials/layout-start') %>
|
||||
|
||||
<div class="auth">
|
||||
<div class="card form">
|
||||
<h1>Пароль изменён</h1>
|
||||
<p class="alert alert--success">Теперь можно войти с новым паролем.</p>
|
||||
<a href="/login" class="btn btn--primary btn--block">Войти</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<%- include('../partials/layout-end') %>
|
||||
@@ -0,0 +1,28 @@
|
||||
<%- include('../partials/layout-start') %>
|
||||
|
||||
<div class="auth">
|
||||
<% if (token) { %>
|
||||
<form action="/reset-password" method="post" class="form card">
|
||||
<h1>Новый пароль</h1>
|
||||
<% if (error) { %><p class="alert alert--error"><%= error %></p><% } %>
|
||||
<input type="hidden" name="token" value="<%= token %>">
|
||||
<label class="label">
|
||||
Новый пароль
|
||||
<input type="password" name="password" class="input" required minlength="6" autocomplete="new-password">
|
||||
</label>
|
||||
<label class="label">
|
||||
Повторите пароль
|
||||
<input type="password" name="password2" class="input" required minlength="6" autocomplete="new-password">
|
||||
</label>
|
||||
<button type="submit" class="btn btn--primary btn--block">Сохранить пароль</button>
|
||||
</form>
|
||||
<% } else { %>
|
||||
<div class="card form">
|
||||
<h1>Ссылка недействительна</h1>
|
||||
<% if (error) { %><p class="alert alert--error"><%= error %></p><% } %>
|
||||
<a href="/forgot-password" class="btn btn--primary">Запросить снова</a>
|
||||
</div>
|
||||
<% } %>
|
||||
</div>
|
||||
|
||||
<%- include('../partials/layout-end') %>
|
||||
@@ -0,0 +1,24 @@
|
||||
<%- include('partials/layout-start') %>
|
||||
|
||||
<article class="legal-page card">
|
||||
<h1>Политика использования cookies</h1>
|
||||
|
||||
<h2>Что такое cookies</h2>
|
||||
<p>Cookies — небольшие файлы, которые сайт сохраняет в браузере для корректной работы сервиса.</p>
|
||||
|
||||
<h2>Какие cookies мы используем</h2>
|
||||
<ul>
|
||||
<li><strong>cookie_consent</strong> — запоминает ваш выбор (принятие политики), срок до 1 года.</li>
|
||||
<li><strong>connect.sid</strong> — сессия: корзина, вход в аккаунт, безопасность. Удаляется после выхода или по истечении срока.</li>
|
||||
</ul>
|
||||
|
||||
<h2>Без согласия</h2>
|
||||
<p>Вы можете просматривать каталог. Вход, регистрация и личный кабинет недоступны до нажатия «Принимаю».</p>
|
||||
|
||||
<h2>Управление</h2>
|
||||
<p>Вы можете удалить cookies в настройках браузера. После этого потребуется снова принять политику и войти в аккаунт.</p>
|
||||
|
||||
<p><a href="/">← На главную</a></p>
|
||||
</article>
|
||||
|
||||
<%- include('partials/layout-end') %>
|
||||
@@ -0,0 +1,15 @@
|
||||
<%- include('partials/layout-start', { returnTo: returnTo }) %>
|
||||
|
||||
<div class="cookies-required">
|
||||
<h1>Согласие на cookies</h1>
|
||||
<p>Для этой страницы (вход, регистрация, личный кабинет) необходимо принять использование cookies.</p>
|
||||
<p class="muted">Мы сохраняем только технические cookies для сессии и безопасности.</p>
|
||||
<form action="/cookies/accept" method="post" class="cookie-banner__actions" style="margin-top:1rem">
|
||||
<input type="hidden" name="return_to" value="<%= returnTo %>">
|
||||
<button type="submit" class="btn btn--primary btn--lg">Принимаю cookies</button>
|
||||
<a href="/" class="btn btn--ghost">На главную</a>
|
||||
</form>
|
||||
<p style="margin-top:1rem"><a href="/cookies/policy">Политика cookies</a></p>
|
||||
</div>
|
||||
|
||||
<%- include('partials/layout-end') %>
|
||||
+27
-5
@@ -4,18 +4,40 @@
|
||||
<form action="/login" method="post" class="form card">
|
||||
<h1>Вход</h1>
|
||||
<% if (error) { %><p class="alert alert--error"><%= error %></p><% } %>
|
||||
<input type="hidden" name="next" value="<%= next %>">
|
||||
<input type="hidden" name="next" id="login-next" value="<%= next %>">
|
||||
<label class="label">
|
||||
Email
|
||||
<input type="email" name="email" class="input" required value="<%= values.email || '' %>">
|
||||
<input type="email" name="email" id="login-email" class="input" required value="<%= values.email || '' %>">
|
||||
</label>
|
||||
<label class="label">
|
||||
Пароль
|
||||
<input type="password" name="password" class="input" required>
|
||||
<input type="password" name="password" class="input" required autocomplete="current-password">
|
||||
</label>
|
||||
<button type="submit" class="btn btn--primary btn--block">Войти</button>
|
||||
<p class="form-footer">Нет аккаунта? <a href="/register">Регистрация</a></p>
|
||||
<button type="submit" class="btn btn--primary btn--block">Войти по паролю</button>
|
||||
<p class="form-footer">
|
||||
<a href="/forgot-password">Забыли пароль?</a><br>
|
||||
Нет аккаунта? <a href="/register">Регистрация</a>
|
||||
</p>
|
||||
</form>
|
||||
|
||||
<div class="card passkey-login">
|
||||
<h2 class="passkey-login__title">Или passkey</h2>
|
||||
<p class="muted passkey-login__hint">Если в профиле включён passkey — войдите без пароля (нужен тот же email).</p>
|
||||
<p id="passkey-login-error" class="alert alert--error" hidden></p>
|
||||
<button type="button" id="passkey-login-btn" class="btn btn--ghost btn--block">Войти с passkey</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/js/passkey.js"></script>
|
||||
<script>
|
||||
document.getElementById('passkey-login-btn')?.addEventListener('click', function () {
|
||||
ShopPasskey.loginWithPasskey(
|
||||
document.getElementById('login-email'),
|
||||
document.getElementById('login-next'),
|
||||
document.getElementById('passkey-login-error'),
|
||||
this
|
||||
);
|
||||
});
|
||||
</script>
|
||||
|
||||
<%- include('partials/layout-end') %>
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
<% if (!cookieConsent) { %>
|
||||
<div class="cookie-banner" role="dialog" aria-labelledby="cookie-banner-title" aria-live="polite">
|
||||
<div class="cookie-banner__inner container">
|
||||
<div class="cookie-banner__text">
|
||||
<p id="cookie-banner-title"><strong>Мы используем cookies</strong></p>
|
||||
<p class="muted">
|
||||
Для входа, регистрации и личного кабинета нужны технические cookies (сессия).
|
||||
Продолжая без согласия, каталог доступен; авторизация и регистрация — нет.
|
||||
<a href="/cookies/policy">Подробнее</a>
|
||||
</p>
|
||||
</div>
|
||||
<form action="/cookies/accept" method="post" class="cookie-banner__actions">
|
||||
<input type="hidden" name="return_to" value="<%= typeof returnTo !== 'undefined' ? returnTo : '/' %>">
|
||||
<button type="submit" class="btn btn--primary">Принимаю</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<% } %>
|
||||
@@ -1,8 +1,9 @@
|
||||
</main>
|
||||
<footer class="footer">
|
||||
<div class="container">
|
||||
<p>© <%= new Date().getFullYear() %> Shop — локальный интернет-магазин на Node.js + SQLite</p>
|
||||
<p>© <%= new Date().getFullYear() %> Shop · <a href="/cookies/policy">Cookies</a></p>
|
||||
</div>
|
||||
</footer>
|
||||
<%- include('cookie-banner') %>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -23,13 +23,19 @@
|
||||
<% if (cartCount > 0) { %><span class="badge"><%= cartCount %></span><% } %>
|
||||
</a>
|
||||
<% if (user) { %>
|
||||
<% if (typeof isAdmin !== 'undefined' && isAdmin) { %>
|
||||
<a href="/admin" class="nav__link nav__admin">Админ</a>
|
||||
<% } %>
|
||||
<a href="/account" class="nav__link"><%= user.name %></a>
|
||||
<form action="/logout" method="post" class="inline-form">
|
||||
<button type="submit" class="btn btn--ghost btn--sm">Выйти</button>
|
||||
</form>
|
||||
<% } else { %>
|
||||
<% } else if (cookieConsent) { %>
|
||||
<a href="/login" class="nav__link">Вход</a>
|
||||
<a href="/register" class="btn btn--primary btn--sm">Регистрация</a>
|
||||
<% } else { %>
|
||||
<span class="nav__link nav__link--disabled" title="Примите cookies">Вход</span>
|
||||
<span class="nav__link nav__link--disabled" title="Примите cookies">Регистрация</span>
|
||||
<% } %>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
@@ -17,6 +17,17 @@
|
||||
<p class="product-detail__desc"><%= product.description %></p>
|
||||
<p class="product-detail__stock">В наличии: <strong><%= product.stock %></strong> шт.</p>
|
||||
|
||||
<% if (error) { %><p class="alert alert--error"><%= error %></p><% } %>
|
||||
<% if (notifySuccess) { %><p class="alert alert--success"><%= notifySuccess %></p><% } %>
|
||||
<% if (notifyError) { %><p class="alert alert--error"><%= notifyError %></p><% } %>
|
||||
<% if (reserved) { %><p class="alert alert--success">Товар успешно забронирован. Подробности на почте и в личном кабинете.</p><% } %>
|
||||
<% if (userReservation) { %>
|
||||
<p class="alert alert--success">
|
||||
У вас активная бронь: <%= userReservation.quantity %> шт. до <%= new Date(userReservation.expires_at).toLocaleString('ru-RU') %>.
|
||||
<a href="/account?tab=reservations">Мои бронирования</a>
|
||||
</p>
|
||||
<% } %>
|
||||
|
||||
<% if (product.stock > 0) { %>
|
||||
<form action="/cart/add" method="post" class="product-detail__form">
|
||||
<input type="hidden" name="product_id" value="<%= product.id %>">
|
||||
@@ -27,8 +38,47 @@
|
||||
<input type="hidden" name="redirect" value="/cart">
|
||||
<button type="submit" class="btn btn--primary btn--lg">Добавить в корзину</button>
|
||||
</form>
|
||||
|
||||
<% if (user && !userReservation) { %>
|
||||
<form action="/reservations" method="post" class="product-detail__form">
|
||||
<input type="hidden" name="product_id" value="<%= product.id %>">
|
||||
<input type="hidden" name="slug" value="<%= product.slug %>">
|
||||
<label class="label">
|
||||
Бронь (48 ч)
|
||||
<input type="number" name="quantity" value="1" min="1" max="<%= product.stock %>" class="input input--qty">
|
||||
</label>
|
||||
<button type="submit" class="btn btn--ghost btn--lg">Забронировать</button>
|
||||
</form>
|
||||
<% } else if (!user) { %>
|
||||
<p class="muted">Для бронирования <a href="/login">войдите</a> в аккаунт.</p>
|
||||
<% } %>
|
||||
<% } else { %>
|
||||
<p class="alert alert--warn">Нет в наличии</p>
|
||||
|
||||
<% if (typeof cookieConsent !== 'undefined' && !cookieConsent) { %>
|
||||
<p class="muted">Примите cookies, чтобы подписаться на уведомление о поступлении.</p>
|
||||
<% } else if (stockAlertSubscribed) { %>
|
||||
<p class="stock-notify stock-notify--done">
|
||||
Вы подписаны на уведомление<% if (notifyEmail) { %> — письмо придёт на <strong><%= notifyEmail %></strong><% } %>.
|
||||
</p>
|
||||
<% } else { %>
|
||||
<section class="stock-notify card">
|
||||
<h2 class="stock-notify__title">Сообщить о поступлении</h2>
|
||||
<p class="muted stock-notify__hint">Будьте среди первых, кто узнает, когда товар снова появится в наличии.</p>
|
||||
<form action="/product/<%= product.slug %>/notify-stock" method="post" class="form stock-notify__form">
|
||||
<% if (user && notifyEmail) { %>
|
||||
<p class="muted">Уведомление отправим на <strong><%= notifyEmail %></strong></p>
|
||||
<input type="hidden" name="email" value="<%= notifyEmail %>">
|
||||
<% } else { %>
|
||||
<label class="label">
|
||||
Email
|
||||
<input type="email" name="email" class="input" required autocomplete="email" placeholder="you@example.com" value="<%= notifyEmail || '' %>">
|
||||
</label>
|
||||
<% } %>
|
||||
<button type="submit" class="btn btn--primary">Подписаться</button>
|
||||
</form>
|
||||
</section>
|
||||
<% } %>
|
||||
<% } %>
|
||||
<a href="/" class="link-back">← Назад в каталог</a>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
# Shop — документация
|
||||
|
||||
Интернет-магазин на **Node.js** и **PostgreSQL 17**.
|
||||
|
||||
## Способы установки
|
||||
|
||||
| Способ | Когда использовать |
|
||||
|--------|-------------------|
|
||||
| **[Установка через Docker](Install-Docker)** | Быстрый старт, тест, изолированное окружение |
|
||||
| **[Установка без Docker](Install-Native)** | Production на Ubuntu, systemd, Caddy |
|
||||
| **[Сервер: установка и обновление](Server-Operations)** | Обновления, systemd, типичные ошибки |
|
||||
|
||||
## Требования
|
||||
|
||||
**Docker:** Docker Engine 24+, Docker Compose v2.
|
||||
|
||||
**Без Docker:** Ubuntu 22.04 / 24.04, Node.js 20, PostgreSQL 17.
|
||||
|
||||
## Роли
|
||||
|
||||
| Роль | Кто |
|
||||
|------|-----|
|
||||
| **customer** | Все, кто регистрируется через сайт |
|
||||
| **admin** | **Один** пользователь — email из `ADMIN_EMAIL` в `.env` (по умолчанию `admin@site.com` / пароль `admin`) |
|
||||
|
||||
Админ-панель доступна только этому аккаунту.
|
||||
|
||||
## Быстрый старт
|
||||
|
||||
### Docker
|
||||
|
||||
```bash
|
||||
git clone <URL-вашего-репозитория> shop
|
||||
cd shop
|
||||
cp .env.docker.example .env
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
Сайт: http://localhost:3000
|
||||
|
||||
### Без Docker (сервер)
|
||||
|
||||
```bash
|
||||
export SHOP_ROOT=/opt/shop
|
||||
export GIT_REPO_URL='<URL-вашего-репозитория>'
|
||||
|
||||
git clone "$GIT_REPO_URL" "$SHOP_ROOT"
|
||||
cd "$SHOP_ROOT"
|
||||
sudo bash scripts/quick-deploy-ubuntu.sh
|
||||
```
|
||||
|
||||
Обновление (рекомендуется):
|
||||
|
||||
```bash
|
||||
export SHOP_ROOT=/opt/shop/shop10
|
||||
bash "$SHOP_ROOT/scripts/server-update.sh"
|
||||
```
|
||||
|
||||
Путь `SHOP_ROOT` — ваш каталог клона (см. [Server-Operations](Server-Operations)).
|
||||
|
||||
## Проверка
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:3000/health
|
||||
```
|
||||
|
||||
Ожидается: `{"ok":true,"service":"shop","database":"postgresql"}`
|
||||
|
||||
## Ссылки
|
||||
|
||||
- [Решение проблем](Troubleshooting)
|
||||
- [Сервер: установка и обновление](Server-Operations)
|
||||
@@ -0,0 +1,143 @@
|
||||
# Установка через Docker Compose
|
||||
|
||||
Полный стек в контейнерах: **PostgreSQL 17** + **приложение Shop** (+ опционально **Caddy** для HTTPS).
|
||||
|
||||
## 1. Требования
|
||||
|
||||
- Docker Engine 24 или новее
|
||||
- Docker Compose v2 (`docker compose`)
|
||||
- Git
|
||||
- Порты: **3000** (сайт) или **80/443** (с Caddy)
|
||||
|
||||
Проверка:
|
||||
|
||||
```bash
|
||||
docker --version
|
||||
docker compose version
|
||||
```
|
||||
|
||||
## 2. Получение кода
|
||||
|
||||
```bash
|
||||
git clone https://git.evilfox.cc/test/shop10.git
|
||||
cd shop10
|
||||
git checkout v0.10.0
|
||||
```
|
||||
|
||||
## 3. Настройка переменных
|
||||
|
||||
```bash
|
||||
cp .env.docker.example .env
|
||||
nano .env
|
||||
```
|
||||
|
||||
| Переменная | Описание | Пример |
|
||||
|------------|----------|--------|
|
||||
| `POSTGRES_USER` | Пользователь БД | `shop` |
|
||||
| `POSTGRES_PASSWORD` | Пароль БД | смените в production |
|
||||
| `POSTGRES_DB` | Имя базы | `shop` |
|
||||
| `SESSION_SECRET` | Секрет сессий | `openssl rand -hex 32` |
|
||||
| `APP_PORT` | Порт на хосте | `3000` |
|
||||
| `TRUST_PROXY` | За Caddy: `1`, иначе `0` | `0` |
|
||||
|
||||
## 4. Запуск
|
||||
|
||||
```bash
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
Первый запуск: сборка образа `app`, скачивание `postgres:17-alpine`, создание таблиц и демо-товаров.
|
||||
|
||||
Статус:
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
docker compose logs -f app
|
||||
```
|
||||
|
||||
## 5. Проверка
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:3000/health
|
||||
```
|
||||
|
||||
В браузере: **http://IP_СЕРВЕРА:3000** или **http://localhost:3000**
|
||||
|
||||
## 6. HTTPS с Caddy (опционально)
|
||||
|
||||
1. В `.env` установите `TRUST_PROXY=1`
|
||||
2. Отредактируйте `caddy/Caddyfile.docker.example`:
|
||||
- укажите свой домен вместо `shop.example.com`
|
||||
- или оставьте блок `:80` для доступа по IP
|
||||
3. Запуск:
|
||||
|
||||
```bash
|
||||
docker compose --profile proxy up -d --build
|
||||
```
|
||||
|
||||
Открыты порты **80** и **443**. Контейнер `caddy` проксирует на `app:3000`.
|
||||
|
||||
## 7. Полезные команды
|
||||
|
||||
| Команда | Действие |
|
||||
|---------|----------|
|
||||
| `docker compose logs -f app` | Логи приложения |
|
||||
| `docker compose logs -f postgres` | Логи БД |
|
||||
| `docker compose restart app` | Перезапуск приложения |
|
||||
| `docker compose down` | Остановить контейнеры |
|
||||
| `docker compose down -v` | Остановить и **удалить данные БД** |
|
||||
| `docker compose up -d --build` | Пересборка после `git pull` |
|
||||
|
||||
## 8. Обновление версии
|
||||
|
||||
```bash
|
||||
cd shop10
|
||||
git fetch --tags
|
||||
git checkout v0.10.0 # или новый тег
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
## 9. Только PostgreSQL (разработка)
|
||||
|
||||
Приложение на хосте (`npm run dev`), БД в Docker:
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.dev.yml up -d
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
В `.env`:
|
||||
|
||||
```env
|
||||
DATABASE_URL=postgresql://shop:shop@127.0.0.1:5432/shop
|
||||
HOST=0.0.0.0
|
||||
```
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
## 10. Архитектура
|
||||
|
||||
```
|
||||
┌─────────────┐ ┌──────────────┐ ┌─────────────┐
|
||||
│ Браузер │────▶│ Caddy :443 │────▶│ app :3000 │
|
||||
│ │ │ (опционально)│ │ Node.js │
|
||||
└─────────────┘ └──────────────┘ └──────┬──────┘
|
||||
│
|
||||
┌──────▼──────┐
|
||||
│ postgres:17 │
|
||||
└─────────────┘
|
||||
```
|
||||
|
||||
## 11. Типичные ошибки
|
||||
|
||||
| Симптом | Решение |
|
||||
|---------|---------|
|
||||
| `port is already allocated` | Смените `APP_PORT` в `.env` или освободите порт 3000 |
|
||||
| `app` unhealthy | `docker compose logs app` — часто нет связи с postgres |
|
||||
| Пустой каталог | Подождите seed; `docker compose logs app` |
|
||||
| 502 с Caddy | `TRUST_PROXY=1`, проверьте `docker compose ps` |
|
||||
|
||||
Подробнее: [Решение проблем](Troubleshooting)
|
||||
@@ -0,0 +1,106 @@
|
||||
# Установка без Docker (Ubuntu)
|
||||
|
||||
Production: Node.js 20, PostgreSQL 17, systemd, опционально Caddy.
|
||||
|
||||
**Полное руководство по ошибкам и обновлениям:** [Server-Operations](Server-Operations).
|
||||
|
||||
Задайте каталог клона:
|
||||
|
||||
```bash
|
||||
export SHOP_ROOT=/opt/shop
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 1. Требования
|
||||
|
||||
- Ubuntu 22.04 или 24.04
|
||||
- Порты 22, 80, 443 (для Caddy)
|
||||
- Порт 3000 только localhost
|
||||
|
||||
## 2. Системные пакеты
|
||||
|
||||
### Node.js 20
|
||||
|
||||
```bash
|
||||
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
|
||||
apt install -y nodejs git curl
|
||||
```
|
||||
|
||||
### PostgreSQL 17
|
||||
|
||||
Не используйте `apt install postgresql-17` без PGDG:
|
||||
|
||||
```bash
|
||||
sudo bash "$SHOP_ROOT/scripts/install-postgresql-ubuntu.sh"
|
||||
```
|
||||
|
||||
## 3. Клонирование
|
||||
|
||||
```bash
|
||||
export GIT_REPO_URL='<URL-вашего-репозитория>'
|
||||
git clone "$GIT_REPO_URL" "$SHOP_ROOT"
|
||||
cd "$SHOP_ROOT"
|
||||
```
|
||||
|
||||
Или: `sudo SHOP_GIT_URL="$GIT_REPO_URL" bash scripts/quick-deploy-ubuntu.sh`
|
||||
|
||||
## 4. База данных
|
||||
|
||||
```bash
|
||||
cd "$SHOP_ROOT"
|
||||
bash scripts/setup-postgres-ubuntu.sh
|
||||
```
|
||||
|
||||
## 5. `.env`
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
nano .env
|
||||
```
|
||||
|
||||
`SESSION_SECRET`, `DATABASE_URL`, `SITE_URL` (ваш публичный URL без привязки к конкретному домену в коде).
|
||||
|
||||
## 6. Зависимости
|
||||
|
||||
```bash
|
||||
npm install --omit=dev
|
||||
```
|
||||
|
||||
## 7. systemd
|
||||
|
||||
```bash
|
||||
sudo bash scripts/install-shop-service.sh
|
||||
```
|
||||
|
||||
`WorkingDirectory` в unit = `$SHOP_ROOT`. Не делайте `chown -R www-data` на весь репозиторий.
|
||||
|
||||
## 8. Caddy
|
||||
|
||||
После `curl http://127.0.0.1:3000/health` → OK:
|
||||
|
||||
```bash
|
||||
cp "$SHOP_ROOT/caddy/Caddyfile.example" /etc/caddy/Caddyfile
|
||||
# укажите ваш домен в Caddyfile
|
||||
systemctl reload caddy
|
||||
```
|
||||
|
||||
## 9. Обновление
|
||||
|
||||
```bash
|
||||
bash "$SHOP_ROOT/scripts/server-update.sh"
|
||||
```
|
||||
|
||||
## 10. Архитектура
|
||||
|
||||
```
|
||||
Интернет → Caddy :443 → 127.0.0.1:3000 (Node.js)
|
||||
↓
|
||||
PostgreSQL 127.0.0.1:5432
|
||||
```
|
||||
|
||||
## 11. Резервное копирование
|
||||
|
||||
```bash
|
||||
sudo -u postgres pg_dump shop > shop_backup_$(date +%F).sql
|
||||
```
|
||||
@@ -0,0 +1,197 @@
|
||||
# Сервер: установка и обновление
|
||||
|
||||
Инструкция **без привязки к конкретному домену или хостингу**. Подставьте свои значения:
|
||||
|
||||
| Переменная | Что это | Пример |
|
||||
|------------|---------|--------|
|
||||
| `SHOP_ROOT` | Каталог клона, где лежат `package.json` и `scripts/` | `/opt/shop` |
|
||||
| `GIT_REPO_URL` | URL вашего git-репозитория | `https://forge.example.com/user/shop.git` |
|
||||
| `SITE_URL` | Публичный URL магазина (для писем и passkey) | `https://shop.example.com` |
|
||||
|
||||
Проверка каталога:
|
||||
|
||||
```bash
|
||||
export SHOP_ROOT=/opt/shop
|
||||
test -f "$SHOP_ROOT/package.json" && echo OK || echo "Неверный SHOP_ROOT"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Первая установка (Ubuntu, без Docker)
|
||||
|
||||
```bash
|
||||
export SHOP_ROOT=/opt/shop
|
||||
export GIT_REPO_URL='https://ВАШ-FORGE/путь/к/shop.git'
|
||||
|
||||
apt update && apt install -y git curl
|
||||
git clone "$GIT_REPO_URL" "$SHOP_ROOT"
|
||||
cd "$SHOP_ROOT"
|
||||
|
||||
sudo SHOP_INSTALL_DIR="$SHOP_ROOT" SHOP_GIT_URL="$GIT_REPO_URL" \
|
||||
bash scripts/quick-deploy-ubuntu.sh
|
||||
```
|
||||
|
||||
Скрипт: Node.js (если нет), PostgreSQL (PGDG), `.env`, `npm install`, служба **shop** (systemd).
|
||||
|
||||
---
|
||||
|
||||
## Обновление кода (сайт уже работает)
|
||||
|
||||
**Рекомендуется** — две команды (можно из любого каталога, не нужен `cd`):
|
||||
|
||||
```bash
|
||||
export SHOP_ROOT=/opt/shop/shop10
|
||||
bash "$SHOP_ROOT/scripts/server-update.sh"
|
||||
```
|
||||
|
||||
Подставьте свой путь к клону (где лежит `package.json`). Часто это `/opt/shop` или `/opt/shop/shop10`.
|
||||
|
||||
Почему так надёжнее, чем `cd /opt/shop && git pull`:
|
||||
|
||||
- явно задан каталог репозитория (`SHOP_ROOT`);
|
||||
- внутри выполняются `git-sync` (ветка `main`), `npm install`, перезапуск `shop`, проверка `/health`;
|
||||
- не перепутаете родительскую папку без `package.json` и скриптов.
|
||||
|
||||
Проверка после обновления:
|
||||
|
||||
```bash
|
||||
systemctl status shop
|
||||
curl -s http://127.0.0.1:3000/health
|
||||
```
|
||||
|
||||
Если git в detached HEAD отдельно:
|
||||
|
||||
```bash
|
||||
cd "$SHOP_ROOT"
|
||||
bash scripts/git-sync.sh
|
||||
bash scripts/server-update.sh
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Скрипты в `scripts/`
|
||||
|
||||
| Скрипт | Назначение |
|
||||
|--------|------------|
|
||||
| `quick-deploy-ubuntu.sh` | Первая установка / полный цикл |
|
||||
| `server-update.sh` | `git pull`, `npm install`, перезапуск shop |
|
||||
| `git-sync.sh` | Исправить detached HEAD, синхронизация с `main` |
|
||||
| `install-postgresql-ubuntu.sh` | PostgreSQL 17 через PGDG |
|
||||
| `setup-postgres-ubuntu.sh` | Пользователь и БД `shop` |
|
||||
| `install-shop-service.sh` | Установка systemd unit |
|
||||
| `free-port-3000.sh` | Освободить порт (старый `npm start`) |
|
||||
| `fix-db-connection.sh` | ECONNREFUSED :5432 |
|
||||
| `diagnose-502.sh` | HTTP 502, Caddy |
|
||||
| `diagnose-shop-service.sh` | Падение shop.service |
|
||||
|
||||
Все скрипты сами ищут `SHOP_ROOT` (каталог, откуда вызван `scripts/`, или переменная окружения).
|
||||
|
||||
---
|
||||
|
||||
## Частые ошибки
|
||||
|
||||
### `Unable to locate package postgresql-17`
|
||||
|
||||
В стандартном Ubuntu нет пакета 17. Не копируйте `apt install postgresql-17` из старых заметок.
|
||||
|
||||
```bash
|
||||
sudo bash "$SHOP_ROOT/scripts/install-postgresql-ubuntu.sh"
|
||||
bash "$SHOP_ROOT/scripts/setup-postgres-ubuntu.sh"
|
||||
```
|
||||
|
||||
### `URL_РЕПОЗИТОРИЯ: No such file` или placeholder в команде
|
||||
|
||||
В документации иногда указан **шаблон**, а не команда. Клонируйте так:
|
||||
|
||||
```bash
|
||||
git clone 'https://ВАШ-FORGE/shop.git' "$SHOP_ROOT"
|
||||
```
|
||||
|
||||
### `package.json` ENOENT в `/opt/shop`
|
||||
|
||||
Вы в **родительской** папке, а клон в подкаталоге (или наоборот).
|
||||
|
||||
```bash
|
||||
find /opt -name package.json 2>/dev/null
|
||||
export SHOP_ROOT=/путь/где/найден
|
||||
cd "$SHOP_ROOT"
|
||||
```
|
||||
|
||||
### `You are not currently on a branch`
|
||||
|
||||
После `git checkout v0.x.x` репозиторий в detached HEAD.
|
||||
|
||||
```bash
|
||||
cd "$SHOP_ROOT"
|
||||
bash scripts/git-sync.sh
|
||||
```
|
||||
|
||||
### `scripts/...: No such file or directory`
|
||||
|
||||
Запуск не из клона. Используйте полный путь:
|
||||
|
||||
```bash
|
||||
bash "$SHOP_ROOT/scripts/server-update.sh"
|
||||
```
|
||||
|
||||
### `Служба shop не установлена` / `Unit shop.service could not be found`
|
||||
|
||||
```bash
|
||||
cd "$SHOP_ROOT"
|
||||
sudo bash scripts/install-shop-service.sh
|
||||
```
|
||||
|
||||
В `/etc/systemd/system/shop.service` поля `WorkingDirectory` и `EnvironmentFile` должны указывать на **`$SHOP_ROOT`**.
|
||||
|
||||
### `shop.service: status=1/FAILURE`, `activating (auto-restart)`
|
||||
|
||||
1. **Порт 3000 занят** (старый ручной Node) — health отвечает, systemd падает:
|
||||
|
||||
```bash
|
||||
sudo bash "$SHOP_ROOT/scripts/free-port-3000.sh"
|
||||
sudo systemctl restart shop
|
||||
systemctl status shop
|
||||
```
|
||||
|
||||
2. **PostgreSQL** — смотрите лог:
|
||||
|
||||
```bash
|
||||
journalctl -u shop -n 40 --no-pager
|
||||
bash "$SHOP_ROOT/scripts/diagnose-shop-service.sh"
|
||||
```
|
||||
|
||||
3. **`.env` не в `SHOP_ROOT`** — скопируйте с прежнего места:
|
||||
|
||||
```bash
|
||||
cp /старый/путь/.env "$SHOP_ROOT/.env"
|
||||
sudo bash "$SHOP_ROOT/scripts/install-shop-service.sh"
|
||||
```
|
||||
|
||||
### Изменения в git не видны на сайте
|
||||
|
||||
Обновление делали не в том каталоге или служба смотрит на другой путь:
|
||||
|
||||
```bash
|
||||
cd "$SHOP_ROOT" && git log -1 --oneline
|
||||
grep WorkingDirectory /etc/systemd/system/shop.service
|
||||
bash scripts/server-update.sh
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Проверка
|
||||
|
||||
```bash
|
||||
systemctl status shop
|
||||
curl -s http://127.0.0.1:3000/health
|
||||
```
|
||||
|
||||
Ожидается: `{"ok":true,"service":"shop","database":"postgresql"}` и **`Active: active (running)`**.
|
||||
|
||||
---
|
||||
|
||||
## Caddy / HTTPS
|
||||
|
||||
Пока `curl http://127.0.0.1:3000/health` не OK, reverse proxy будет отдавать **502**. Сначала backend, потом Caddy.
|
||||
|
||||
См. также: [Решение проблем](Troubleshooting), [Установка без Docker](Install-Native).
|
||||
@@ -0,0 +1,89 @@
|
||||
# Решение проблем
|
||||
|
||||
Полное руководство по развёртыванию: **[Сервер: установка и обновление](Server-Operations)**.
|
||||
|
||||
**Обновление на сервере (рекомендуется):**
|
||||
|
||||
```bash
|
||||
export SHOP_ROOT=/opt/shop/shop10
|
||||
bash "$SHOP_ROOT/scripts/server-update.sh"
|
||||
```
|
||||
|
||||
`SHOP_ROOT` — каталог с `package.json` (у вас может быть `/opt/shop`).
|
||||
|
||||
Перед диагностикой:
|
||||
|
||||
```bash
|
||||
export SHOP_ROOT=/opt/shop/shop10
|
||||
cd "$SHOP_ROOT"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Диагностика
|
||||
|
||||
```bash
|
||||
bash "$SHOP_ROOT/scripts/diagnose-502.sh"
|
||||
bash "$SHOP_ROOT/scripts/diagnose-shop-service.sh"
|
||||
journalctl -u shop -n 50 --no-pager
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Краткая таблица ошибок
|
||||
|
||||
| Симптом | Что делать |
|
||||
|---------|------------|
|
||||
| `postgresql-17` not found | `sudo bash scripts/install-postgresql-ubuntu.sh` |
|
||||
| Placeholder / `URL_РЕПОЗИТОРИЯ` | `git clone <ваш-url> "$SHOP_ROOT"` — не копировать шаблоны как команды |
|
||||
| Нет `package.json` | `find /opt -name package.json`; `cd` в найденный каталог |
|
||||
| detached HEAD | `bash scripts/git-sync.sh` |
|
||||
| Нет `scripts/...` | `bash "$SHOP_ROOT/scripts/server-update.sh"` |
|
||||
| Unit shop not found | `sudo bash scripts/install-shop-service.sh` |
|
||||
| shop exit-code / auto-restart | `sudo bash scripts/free-port-3000.sh`; `systemctl restart shop` |
|
||||
| 502 в браузере | `curl http://127.0.0.1:3000/health` — сначала backend |
|
||||
| ECONNREFUSED :5432 | `bash scripts/fix-db-connection.sh` |
|
||||
|
||||
Подробности — в [Server-Operations](Server-Operations).
|
||||
|
||||
---
|
||||
|
||||
## HTTP 502 (Caddy / браузер)
|
||||
|
||||
```bash
|
||||
curl -s http://127.0.0.1:3000/health
|
||||
systemctl status shop
|
||||
```
|
||||
|
||||
Пока `/health` не OK — Caddy будет отдавать 502.
|
||||
|
||||
---
|
||||
|
||||
## Docker
|
||||
|
||||
```bash
|
||||
docker compose logs app
|
||||
docker compose logs postgres
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
`DATABASE_URL` в compose должен указывать на сервис `postgres`, не на `127.0.0.1` внутри контейнера app.
|
||||
|
||||
---
|
||||
|
||||
## git pull / dubious ownership
|
||||
|
||||
Не делайте `chown -R www-data` на весь каталог репозитория.
|
||||
|
||||
```bash
|
||||
git config --global --add safe.directory "$SHOP_ROOT"
|
||||
cd "$SHOP_ROOT" && git pull
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Ссылки
|
||||
|
||||
- [Сервер: установка и обновление](Server-Operations)
|
||||
- [Установка Docker](Install-Docker)
|
||||
- [Установка без Docker](Install-Native)
|
||||
@@ -0,0 +1,6 @@
|
||||
### Навигация
|
||||
|
||||
- [Главная](Home)
|
||||
- [Установка — Docker](Install-Docker)
|
||||
- [Установка — без Docker](Install-Native)
|
||||
- [Решение проблем](Troubleshooting)
|
||||
Reference in New Issue
Block a user