UNPKG

@appsemble/node-utils

Version:

NodeJS utilities used by Appsemble internally.

61 lines 3.04 kB
import { hash } from 'bcrypt'; import { Client } from 'pg'; import { v4 as uuid } from 'uuid'; const { DATABASE_HOST = 'localhost', DATABASE_NAME = 'appsemble', DATABASE_PASSWORD = 'password', DATABASE_PORT = 5432, DATABASE_USER = 'admin', } = process.env; async function insert(table, columns, values, client) { const params = columns.map((item, index) => `$${index + 1}`); const query = `INSERT INTO "${table}" (${columns.join(', ')}) VALUES (${params.join(', ')})`; const result = await client.query(query, values); return result; } /** * Creates a new user in the database * * @param name Name of the user * @param email Primary email of the user * @param password Password * @param timezone Timezone of the user * @param clientCredentials Used to make OAuth client credentials for permissions * @param organization Optional organization id to add the user to if it exists */ export async function createUser(name, email, password, timezone, clientCredentials, organization) { if (!DATABASE_HOST || !DATABASE_NAME || !DATABASE_PASSWORD || !DATABASE_PORT || !DATABASE_USER) { throw new Error('Missing database credentials'); } const client = new Client({ database: DATABASE_NAME, host: DATABASE_HOST, port: DATABASE_PORT ? Number(DATABASE_PORT) : undefined, user: DATABASE_USER, password: DATABASE_PASSWORD, }); await client.connect(); const hashedPassword = await hash(password, 10); const userId = uuid(); await insert('User', ['id', 'name', '"primaryEmail"', 'password', 'timezone', 'created', 'updated'], [userId, name, email, hashedPassword, timezone ?? 'Europe/Amsterdam', 'NOW()', 'NOW()'], client); await insert('EmailAuthorization', ['email', 'verified', 'created', 'updated', '"UserId"'], [email, true, 'NOW()', 'NOW()', userId], client); const organizationIds = new Set(['appsemble']); if (organization) { organizationIds.add(organization); } for (const organizationId of organizationIds) { const organizationResult = await client.query('SELECT id FROM "Organization" WHERE id = $1', [organizationId]); if (organizationResult.rows.length > 0) { await insert('OrganizationMember', ['"OrganizationId"', '"UserId"', 'role', 'created', 'updated'], [organizationId, userId, 'Maintainer', 'NOW()', 'NOW()'], client); } } if (clientCredentials) { const [clientId, clientPassword] = clientCredentials.split(':'); const hashedClientPassword = await hash(clientPassword, 10); await insert('OAuth2ClientCredentials', ['id', 'secret', 'description', 'scopes', 'created', '"UserId"'], [ clientId, hashedClientPassword, 'Used for provisioning the review environment', 'apps:write resources:write assets:write blocks:write organizations:write groups:write', 'NOW()', userId, ], client); } await client.end(); } //# sourceMappingURL=createUser.js.map