freightdesk/webapp/src/routes/setup.js

33 lines
1.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const supabase = require('../services/supabase');
// GET /setup show wizard if no admin exists
router.get('/', async (req, res) => {
const { count } = await supabase.from('portal_users').select('*', { count: 'exact', head: true }).eq('role', 'admin');
if (count > 0) return res.redirect('/login'); // admin already exists
res.render('pages/setup', { error: null });
});
// POST /setup create first admin securely
router.post('/', async (req, res) => {
const { username, password } = req.body;
if (!username || !password) return res.render('pages/setup', { error: 'All fields are required' });
// ensure admin does not already exist (racecondition safety)
const { data: existing } = await supabase.from('portal_users').select('id').eq('role', 'admin').single();
if (existing) return res.render('pages/setup', { error: 'Admin already configured' });
const hash = await bcrypt.hash(password, 12);
await supabase.from('portal_users').insert({
username,
password_hash: hash,
role: 'admin',
is_active: true,
});
// redirect to login after creation
res.redirect('/login');
});
module.exports = router;