feat: passkey в профиле и входе, кнопка админки в кабинете

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
shop
2026-05-17 12:58:00 +03:00
parent 711110c03b
commit e71bfa35dc
12 changed files with 757 additions and 11 deletions
+6 -1
View File
@@ -9,9 +9,14 @@ ADMIN_EMAIL=admin@site.com
ADMIN_PASSWORD=admin ADMIN_PASSWORD=admin
ADMIN_NAME=Администратор ADMIN_NAME=Администратор
# URL сайта (ссылки в письмах) # URL сайта (ссылки в письмах, WebAuthn origin)
SITE_URL=http://localhost:3000 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 — сброс пароля и уведомления о брони
SMTP_HOST=smtp.example.com SMTP_HOST=smtp.example.com
SMTP_PORT=587 SMTP_PORT=587
+1 -1
View File
@@ -12,7 +12,7 @@
- Каталог товаров с категориями и поиском - Каталог товаров с категориями и поиском
- Корзина и оформление заказа - Корзина и оформление заказа
- Регистрация, вход, сброс пароля по email - Регистрация, вход (пароль или passkey), сброс пароля по email
- Личный кабинет: профиль, бронирования - Личный кабинет: профиль, бронирования
- Роли клиент / администратор, админ-панель - Роли клиент / администратор, админ-панель
- Согласие на cookies - Согласие на cookies
+2 -1
View File
@@ -19,6 +19,7 @@
"express": "^4.21.2", "express": "^4.21.2",
"express-session": "^1.18.1", "express-session": "^1.18.1",
"nodemailer": "^6.9.16", "nodemailer": "^6.9.16",
"pg": "^8.13.1" "pg": "^8.13.1",
"@simplewebauthn/server": "^13.1.1"
} }
} }
+17
View File
@@ -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);
+68 -1
View File
@@ -392,7 +392,9 @@ a:hover {
.auth { .auth {
display: flex; display: flex;
justify-content: center; flex-direction: column;
align-items: center;
gap: 1.25rem;
padding: 2rem 0; padding: 2rem 0;
} }
@@ -402,6 +404,52 @@ a:hover {
padding: 1.75rem; 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 { .alert {
padding: 0.75rem 1rem; padding: 0.75rem 1rem;
border-radius: 8px; border-radius: 8px;
@@ -585,6 +633,25 @@ a:hover {
font-weight: 600; 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-header { .admin-header {
margin-bottom: 1.5rem; margin-bottom: 1.5rem;
} }
+112
View File
@@ -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,
};
})();
+50 -2
View File
@@ -4,9 +4,10 @@ const { query, formatPrice } = require('../db');
const { getCart, cartCount } = require('../cart'); const { getCart, cartCount } = require('../cart');
const { requireAuth } = require('../middleware/auth'); const { requireAuth } = require('../middleware/auth');
const { requireCookieConsent } = require('../middleware/cookieConsent'); const { requireCookieConsent } = require('../middleware/cookieConsent');
const { ROLE_LABELS } = require('../constants/roles'); const { ROLES, ROLE_LABELS } = require('../constants/roles');
const { asyncHandler } = require('../utils/asyncHandler'); const { asyncHandler } = require('../utils/asyncHandler');
const { expireOldReservations } = require('../services/reservations'); const { expireOldReservations } = require('../services/reservations');
const webauthn = require('../services/webauthn');
const router = express.Router(); const router = express.Router();
@@ -21,7 +22,7 @@ router.use((req, res, next) => {
async function loadAccountUser(userId) { async function loadAccountUser(userId) {
const { rows } = await query( const { rows } = await query(
'SELECT id, email, name, role, created_at FROM users WHERE id = $1', 'SELECT id, email, name, role, created_at, passkey_enabled FROM users WHERE id = $1',
[userId] [userId]
); );
return rows[0]; return rows[0];
@@ -44,12 +45,16 @@ function accountRender(res, options) {
success, success,
activeTab, activeTab,
formatPrice, formatPrice,
passkeys,
isAdmin,
} = options; } = options;
res.render('account/index', { res.render('account/index', {
title: 'Личный кабинет', title: 'Личный кабинет',
user, user,
orderCount, orderCount,
reservations: reservations || [], reservations: reservations || [],
passkeys: passkeys || [],
isAdmin: Boolean(isAdmin),
roleLabels: ROLE_LABELS, roleLabels: ROLE_LABELS,
formatPrice: formatPrice || res.locals.formatPrice, formatPrice: formatPrice || res.locals.formatPrice,
error: error || null, error: error || null,
@@ -78,10 +83,14 @@ router.get(
[user.id] [user.id]
); );
const passkeys = await webauthn.getCredentialsForUser(user.id);
accountRender(res, { accountRender(res, {
user, user,
orderCount: countResult.rows[0].n, orderCount: countResult.rows[0].n,
reservations, reservations,
passkeys,
isAdmin: user.role === ROLES.ADMIN,
formatPrice, formatPrice,
success: req.query.success ? decodeURIComponent(String(req.query.success)) : null, success: req.query.success ? decodeURIComponent(String(req.query.success)) : null,
error: req.query.error ? decodeURIComponent(String(req.query.error)) : null, error: req.query.error ? decodeURIComponent(String(req.query.error)) : null,
@@ -187,4 +196,43 @@ router.post(
}) })
); );
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; module.exports = router;
+164
View File
@@ -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;
+3
View File
@@ -17,6 +17,7 @@ const adminRoutes = require('./routes/admin');
const cookiesRoutes = require('./routes/cookies'); const cookiesRoutes = require('./routes/cookies');
const passwordResetRoutes = require('./routes/password-reset'); const passwordResetRoutes = require('./routes/password-reset');
const reservationsRoutes = require('./routes/reservations'); const reservationsRoutes = require('./routes/reservations');
const passkeyRoutes = require('./routes/passkey');
const PORT = process.env.PORT || 3000; const PORT = process.env.PORT || 3000;
const HOST = process.env.HOST || '0.0.0.0'; const HOST = process.env.HOST || '0.0.0.0';
@@ -40,6 +41,7 @@ async function start() {
app.use(healthRoutes); app.use(healthRoutes);
app.use(express.static(path.join(__dirname, 'public'))); app.use(express.static(path.join(__dirname, 'public')));
app.use(express.urlencoded({ extended: true })); app.use(express.urlencoded({ extended: true }));
app.use(express.json({ limit: '64kb' }));
app.use(cookieParser()); app.use(cookieParser());
app.use( app.use(
@@ -68,6 +70,7 @@ async function start() {
app.use('/reservations', reservationsRoutes); app.use('/reservations', reservationsRoutes);
app.use('/', shopRoutes); app.use('/', shopRoutes);
app.use('/', authRoutes); app.use('/', authRoutes);
app.use('/webauthn', passkeyRoutes);
app.use('/account', accountRoutes); app.use('/account', accountRoutes);
app.use('/admin', adminRoutes); app.use('/admin', adminRoutes);
+242
View File
@@ -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,
};
+69 -1
View File
@@ -10,6 +10,7 @@
<a href="/account?tab=profile" class="account-tabs__link <%= activeTab === 'profile' ? 'account-tabs__link--active' : '' %>">Профиль</a> <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=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=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> <a href="/account?tab=reservations" class="account-tabs__link <%= activeTab === 'reservations' ? 'account-tabs__link--active' : '' %>">Бронирования</a>
</nav> </nav>
@@ -29,7 +30,12 @@
<dt>Заказов</dt> <dt>Заказов</dt>
<dd><%= orderCount %></dd> <dd><%= orderCount %></dd>
</dl> </dl>
<a href="/orders" class="btn btn--primary">Мои заказы</a> <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>
<section class="card account-section"> <section class="card account-section">
@@ -102,6 +108,68 @@
</section> </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') { %> <% if (activeTab === 'password') { %>
<section class="card account-section account-section--narrow"> <section class="card account-section account-section--narrow">
<h2>Смена пароля</h2> <h2>Смена пароля</h2>
+23 -4
View File
@@ -4,21 +4,40 @@
<form action="/login" method="post" class="form card"> <form action="/login" method="post" class="form card">
<h1>Вход</h1> <h1>Вход</h1>
<% if (error) { %><p class="alert alert--error"><%= error %></p><% } %> <% 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"> <label class="label">
Email 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>
<label class="label"> <label class="label">
Пароль Пароль
<input type="password" name="password" class="input" required> <input type="password" name="password" class="input" required autocomplete="current-password">
</label> </label>
<button type="submit" class="btn btn--primary btn--block">Войти</button> <button type="submit" class="btn btn--primary btn--block">Войти по паролю</button>
<p class="form-footer"> <p class="form-footer">
<a href="/forgot-password">Забыли пароль?</a><br> <a href="/forgot-password">Забыли пароль?</a><br>
Нет аккаунта? <a href="/register">Регистрация</a> Нет аккаунта? <a href="/register">Регистрация</a>
</p> </p>
</form> </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> </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') %> <%- include('partials/layout-end') %>