Merge pull request #25 from quoije/cursor/user-creation-control-page-ccb0
User creation control page
This commit was merged in pull request #25.
This commit is contained in:
@@ -181,8 +181,11 @@
|
||||
<span id="admin-users-count">—</span> utilisateur(s)
|
||||
</div>
|
||||
</div>
|
||||
<div class="d-flex gap-2">
|
||||
<button type="button" id="open-add-user-modal" class="btn btn-warning btn-sm">Ajouter un utilisateur</button>
|
||||
<button type="button" id="refresh-users" class="btn btn-outline-primary btn-sm">Rafraîchir</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="table-responsive">
|
||||
<table class="table table-sm align-middle mb-0">
|
||||
@@ -391,6 +394,54 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Add user modal -->
|
||||
<div class="modal fade" id="addUserModal" tabindex="-1" aria-hidden="true">
|
||||
<div class="modal-dialog modal-dialog-scrollable">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title">Ajouter un utilisateur</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="text-muted mb-2">
|
||||
Crée un compte avec un <strong>mot de passe temporaire</strong> (affiché une seule fois). L’utilisateur devra le changer à sa prochaine connexion.
|
||||
</div>
|
||||
|
||||
<div id="add-user-response" class="alert d-none" role="alert"></div>
|
||||
|
||||
<form id="add-user-form">
|
||||
<div class="mb-3">
|
||||
<label for="add_user_name" class="form-label">Nom</label>
|
||||
<input type="text" class="form-control" id="add_user_name" placeholder="Prénom / pseudo" required>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="add_user_email" class="form-label">Email</label>
|
||||
<input type="email" class="form-control" id="add_user_email" placeholder="[email protected]" required>
|
||||
</div>
|
||||
<div class="form-check mb-3">
|
||||
<input class="form-check-input" type="checkbox" id="add_user_admin">
|
||||
<label class="form-check-label" for="add_user_admin">Admin</label>
|
||||
</div>
|
||||
|
||||
<div id="add-user-result" class="border rounded p-2 bg-light d-none">
|
||||
<div class="small text-muted mb-1">Mot de passe temporaire (affiché une seule fois)</div>
|
||||
<div class="d-flex gap-2 align-items-center">
|
||||
<code class="flex-grow-1" id="add-user-temp-password">—</code>
|
||||
<button type="button" class="btn btn-outline-secondary btn-sm" id="copy-add-user-temp-password">Copier</button>
|
||||
</div>
|
||||
<div class="small text-muted mt-2" id="add-user-expires-at"></div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Fermer</button>
|
||||
<button type="button" id="add-user-reset" class="btn btn-outline-secondary">Reset</button>
|
||||
<button type="submit" form="add-user-form" class="btn btn-warning" id="add-user-submit">Créer</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Edit movie modal -->
|
||||
<div class="modal fade" id="editMovieModal" tabindex="-1" aria-hidden="true">
|
||||
<div class="modal-dialog modal-lg modal-dialog-scrollable">
|
||||
|
||||
@@ -218,6 +218,22 @@ window.onload = async function () {
|
||||
const adminUsersCountEl = document.getElementById('admin-users-count');
|
||||
const adminUsersTabBtn = document.getElementById('admin-users-tab');
|
||||
|
||||
// Admin: add user form elements
|
||||
const openAddUserModalBtn = document.getElementById('open-add-user-modal');
|
||||
const addUserModalEl = document.getElementById('addUserModal');
|
||||
const addUserModal = addUserModalEl ? new bootstrap.Modal(addUserModalEl) : null;
|
||||
const addUserForm = document.getElementById('add-user-form');
|
||||
const addUserNameEl = document.getElementById('add_user_name');
|
||||
const addUserEmailEl = document.getElementById('add_user_email');
|
||||
const addUserAdminEl = document.getElementById('add_user_admin');
|
||||
const addUserResponseEl = document.getElementById('add-user-response');
|
||||
const addUserResultEl = document.getElementById('add-user-result');
|
||||
const addUserTempPasswordEl = document.getElementById('add-user-temp-password');
|
||||
const addUserExpiresAtEl = document.getElementById('add-user-expires-at');
|
||||
const addUserSubmitBtn = document.getElementById('add-user-submit');
|
||||
const addUserResetBtn = document.getElementById('add-user-reset');
|
||||
const copyAddUserTempPasswordBtn = document.getElementById('copy-add-user-temp-password');
|
||||
|
||||
// Admin user modals
|
||||
const resetUserPasswordModalEl = document.getElementById('resetUserPasswordModal');
|
||||
const resetUserPasswordModal = resetUserPasswordModalEl ? new bootstrap.Modal(resetUserPasswordModalEl) : null;
|
||||
@@ -255,6 +271,27 @@ window.onload = async function () {
|
||||
el.textContent = '';
|
||||
}
|
||||
|
||||
function resetAddUserUi(options = {}) {
|
||||
hideAlert(addUserResponseEl);
|
||||
if (addUserResultEl) addUserResultEl.classList.add('d-none');
|
||||
if (addUserTempPasswordEl) addUserTempPasswordEl.textContent = '—';
|
||||
if (addUserExpiresAtEl) addUserExpiresAtEl.textContent = '';
|
||||
if (options.resetForm && addUserForm) {
|
||||
try { addUserForm.reset(); } catch (_) {}
|
||||
}
|
||||
if (addUserSubmitBtn) addUserSubmitBtn.disabled = false;
|
||||
}
|
||||
|
||||
function openAddUserModal() {
|
||||
if (!addUserModal) return;
|
||||
resetAddUserUi({ resetForm: true });
|
||||
try { addUserModal.show(); } catch (_) {}
|
||||
// Focus name field (best effort)
|
||||
setTimeout(() => {
|
||||
try { addUserNameEl?.focus(); } catch (_) {}
|
||||
}, 50);
|
||||
}
|
||||
|
||||
function resetResetUserModalUi() {
|
||||
hideAlert(resetUserModalResponseEl);
|
||||
if (resetUserModalResultEl) resetUserModalResultEl.classList.add('d-none');
|
||||
@@ -531,6 +568,91 @@ window.onload = async function () {
|
||||
});
|
||||
}
|
||||
|
||||
if (copyAddUserTempPasswordBtn) {
|
||||
copyAddUserTempPasswordBtn.addEventListener('click', async () => {
|
||||
const text = String(addUserTempPasswordEl?.textContent || '').trim();
|
||||
if (!text || text === '—') return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
setAlert(addUserResponseEl, 'success', 'Copié.');
|
||||
setTimeout(() => hideAlert(addUserResponseEl), 1200);
|
||||
} catch (_) {
|
||||
setAlert(addUserResponseEl, 'warning', 'Impossible de copier automatiquement. Copie manuellement.');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (openAddUserModalBtn) {
|
||||
openAddUserModalBtn.addEventListener('click', () => openAddUserModal());
|
||||
}
|
||||
|
||||
if (addUserModalEl) {
|
||||
// Whenever the modal is opened, clear previous result/state.
|
||||
addUserModalEl.addEventListener('shown.bs.modal', () => {
|
||||
resetAddUserUi({ resetForm: true });
|
||||
});
|
||||
}
|
||||
|
||||
if (addUserResetBtn) {
|
||||
addUserResetBtn.addEventListener('click', () => {
|
||||
resetAddUserUi({ resetForm: true });
|
||||
});
|
||||
}
|
||||
|
||||
if (addUserForm) {
|
||||
addUserForm.addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
resetAddUserUi({ resetForm: false });
|
||||
|
||||
const name = String(addUserNameEl?.value || '').trim();
|
||||
const email = String(addUserEmailEl?.value || '').trim();
|
||||
const admin = !!addUserAdminEl?.checked;
|
||||
|
||||
if (!name) {
|
||||
setAlert(addUserResponseEl, 'warning', 'Nom requis.');
|
||||
return;
|
||||
}
|
||||
if (!email) {
|
||||
setAlert(addUserResponseEl, 'warning', 'Email requis.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (addUserSubmitBtn) addUserSubmitBtn.disabled = true;
|
||||
setAlert(addUserResponseEl, 'warning', 'Création...');
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/users/admin/create', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify({ name, email, admin }),
|
||||
});
|
||||
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
setAlert(addUserResponseEl, 'danger', data.message || data.error || `Erreur (${res.status})`);
|
||||
if (addUserSubmitBtn) addUserSubmitBtn.disabled = false;
|
||||
return;
|
||||
}
|
||||
|
||||
// Show temp password once
|
||||
if (addUserTempPasswordEl) addUserTempPasswordEl.textContent = data?.tempPassword || '—';
|
||||
if (addUserExpiresAtEl) addUserExpiresAtEl.textContent = data?.expiresAt ? `Expire: ${data.expiresAt}` : '';
|
||||
if (addUserResultEl) addUserResultEl.classList.remove('d-none');
|
||||
setAlert(addUserResponseEl, 'success', data.message || 'Utilisateur créé.');
|
||||
if (addUserSubmitBtn) addUserSubmitBtn.disabled = false;
|
||||
|
||||
// Refresh list if already loaded or when user tab is active
|
||||
await loadAdminUsers({ force: true });
|
||||
} catch (err) {
|
||||
setAlert(addUserResponseEl, 'danger', err.message || 'Erreur réseau');
|
||||
if (addUserSubmitBtn) addUserSubmitBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (confirmResetUserPasswordBtn) {
|
||||
confirmResetUserPasswordBtn.addEventListener('click', async () => {
|
||||
const target = currentResetTarget;
|
||||
|
||||
@@ -298,6 +298,61 @@ router.get("/admin/list", verifyToken, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Admin: create a user with a random temp password (forces change on first login).
|
||||
router.post("/admin/create", verifyToken, async (req, res) => {
|
||||
if (!isAdminFromDecoded(req.user)) {
|
||||
return res.status(403).json({ message: "You do not have admin privileges" });
|
||||
}
|
||||
|
||||
const { name, email, admin } = req.body || {};
|
||||
const nameNorm = typeof name === "string" ? name.trim() : "";
|
||||
const emailNorm = typeof email === "string" ? email.trim() : "";
|
||||
const makeAdmin = !!admin;
|
||||
|
||||
if (!nameNorm) {
|
||||
return res.status(400).json({ message: "Nom requis." });
|
||||
}
|
||||
if (!emailNorm) {
|
||||
return res.status(400).json({ message: "Email requis." });
|
||||
}
|
||||
// Basic sanity check (not a full RFC validator)
|
||||
if (!/^\S+@\S+\.\S+$/.test(emailNorm)) {
|
||||
return res.status(400).json({ message: "Email invalide." });
|
||||
}
|
||||
|
||||
try {
|
||||
const existingUser = await User.findOne({ email: emailNorm });
|
||||
if (existingUser) {
|
||||
return res.status(409).json({ message: "L'email existe déjà, veuillez en choisir un autre." });
|
||||
}
|
||||
|
||||
const tempPassword = generateTempPassword();
|
||||
const hashedPassword = await bcrypt.hash(tempPassword, 10);
|
||||
const expiresAt = new Date(Date.now() + TEMP_PASSWORD_TTL_MS);
|
||||
|
||||
const user = new User({
|
||||
name: nameNorm,
|
||||
email: emailNorm,
|
||||
password: hashedPassword,
|
||||
role: makeAdmin ? 69 : 0,
|
||||
mustChangePassword: true,
|
||||
tempPasswordIssuedAt: new Date(),
|
||||
tempPasswordExpiresAt: expiresAt,
|
||||
});
|
||||
|
||||
await user.save();
|
||||
|
||||
return res.status(201).json({
|
||||
message: "Utilisateur créé. Mot de passe temporaire généré.",
|
||||
tempPassword,
|
||||
expiresAt: expiresAt.toISOString(),
|
||||
user: { id: String(user._id), name: user.name, email: user.email, admin: user.role === 69, mustChangePassword: true },
|
||||
});
|
||||
} catch (err) {
|
||||
return res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Admin: delete a user (and related playback progress)
|
||||
router.post("/admin/delete", verifyToken, async (req, res) => {
|
||||
if (!isAdminFromDecoded(req.user)) {
|
||||
|
||||
Reference in New Issue
Block a user