Files
web-antrean/server/api/users/create.post.ts
T
2025-12-16 10:42:45 +07:00

125 lines
3.6 KiB
TypeScript
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.
// server/api/users/create.post.ts
// Create new user (manual creation)
import Database from 'better-sqlite3';
import { join } from 'path';
import { existsSync, mkdirSync } from 'fs';
const getDbPath = () => {
const dbDir = join(process.cwd(), 'data');
if (!existsSync(dbDir)) {
mkdirSync(dbDir, { recursive: true });
}
return join(dbDir, 'users.db');
};
const initDb = () => {
const dbPath = getDbPath();
const db = new Database(dbPath);
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
namaLengkap TEXT NOT NULL,
namaUser TEXT UNIQUE NOT NULL,
email TEXT,
tipeUser TEXT DEFAULT '',
lastLogin INTEGER,
roles TEXT DEFAULT '[]',
realmRoles TEXT DEFAULT '[]',
accountRoles TEXT DEFAULT '[]',
resourceRoles TEXT DEFAULT '[]',
groups TEXT DEFAULT '[]',
given_name TEXT,
family_name TEXT,
createdAt INTEGER DEFAULT (strftime('%s', 'now')),
updatedAt INTEGER DEFAULT (strftime('%s', 'now'))
)
`);
// Migration: Add new columns if they don't exist
try {
db.exec(`
ALTER TABLE users ADD COLUMN realmRoles TEXT DEFAULT '[]';
ALTER TABLE users ADD COLUMN accountRoles TEXT DEFAULT '[]';
ALTER TABLE users ADD COLUMN resourceRoles TEXT DEFAULT '[]';
ALTER TABLE users ADD COLUMN lastLogin INTEGER;
`);
} catch (e: any) {
if (!e.message?.includes('duplicate column')) {
console.warn('Migration note:', e.message);
}
}
return db;
};
export default defineEventHandler(async (event) => {
const body = await readBody(event);
console.log(" Create user endpoint called");
if (!body.namaLengkap || !body.username) {
throw createError({
statusCode: 400,
statusMessage: "namaLengkap and username are required",
});
}
try {
const db = initDb();
// Generate ID if not provided (for manual creation)
const userId = body.id || `manual-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
// Check if username already exists
const existingUser = db.prepare('SELECT * FROM users WHERE namaUser = ?').get(body.username) as any;
if (existingUser) {
db.close();
throw createError({
statusCode: 409,
statusMessage: "Username already exists",
});
}
// Insert new user
db.prepare(`
INSERT INTO users (
id, namaLengkap, namaUser, email, tipeUser, lastLogin,
roles, realmRoles, accountRoles, resourceRoles, groups, given_name, family_name
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
userId,
body.namaLengkap,
body.username,
body.email || null,
body.tipeUser || '',
body.lastLogin || Math.floor(Date.now() / 1000),
JSON.stringify(Array.isArray(body.roles) ? body.roles : []),
JSON.stringify(Array.isArray(body.realmRoles) ? body.realmRoles : []),
JSON.stringify(Array.isArray(body.accountRoles) ? body.accountRoles : []),
JSON.stringify(Array.isArray(body.resourceRoles) ? body.resourceRoles : []),
JSON.stringify(Array.isArray(body.groups) ? body.groups : []),
body.given_name || null,
body.family_name || null
);
db.close();
console.log(`✅ User created: ${userId}`);
return {
success: true,
message: 'User created successfully',
id: userId
};
} catch (error: any) {
console.error("❌ Error creating user:", error);
throw createError({
statusCode: error.statusCode || 500,
statusMessage: error.message || "Failed to create user",
});
}
});