Skip to content

Instantly share code, notes, and snippets.

@taylortom
Last active October 13, 2022 12:31
Show Gist options
  • Save taylortom/bb633f5a5aef0f58cd0f8b8256d16e17 to your computer and use it in GitHub Desktop.
Save taylortom/bb633f5a5aef0f58cd0f8b8256d16e17 to your computer and use it in GitHub Desktop.
Script to register a new super user account in AAT v1.0.0
import path from 'path';
import { pathToFileURL } from 'url';
import { spawn } from 'child_process';
/**
* Handles installing/removing the npm dependencies for this script
*/
function deps(command) {
return new Promise((resolve, reject) => {
let error = '';
const npm = spawn(`npm ${command} prompts`, { shell: true })
npm.stderr.on('data', d => error += d);
npm.on('close', code => code === 0 ? resolve() : reject(error));
});
}
async function registerSuperUser() {
process.env.NODE_ENV = 'production';
try {
/**
* Install dependency required by this script
*/
await deps('install');
/**
* Get app instance
*/
const { App } = await import(pathToFileURL(path.join(process.cwd(), 'node_modules', 'adapt-authoring-core', 'index.js')));
process.env.ADAPT_AUTHORING_LOGGER__mute = true
const app = await App.instance.onReady();
/**
* Check for existing super users
*/
const [localauth, roles, users] = await app.waitForModule('localauth', 'roles', 'users');
const superUserId = (await roles.find({ shortName: 'superuser' }))[0]._id.toString();
const existing = await users.find({ roles: superUserId });
if(existing.length) {
throw new Error(`Super user accounts already exist: ${existing.map(u => u.email).join(', ')}. Please create further users in the UI.`);
}
/**
* Get user input
*/
const { default: prompts } = await import('prompts');
const { email, password } = await prompts([{
type: 'text',
name: 'email',
message: 'Enter an email address to be used as a login for the Super User account'
}, {
type: 'password',
name: 'password',
message: 'Enter a password for the Super User account'
}]);
await prompts([{
type: 'password',
name: 'passwordMatch',
message: 'Please type the password again to confirm',
validate: val => val !== password ? `Passwords don't match. Please try again` : true
}]);
/**
* Save user to DB
*/
const user = await localauth.register(Object.assign({}, { email, password }, {
firstName: 'Super',
lastName: 'User',
roles: [superUserId]
}));
console.log(`Successfully registered ${user.email}`);
} catch(e) {
console.log(e);
}
/**
* Remove dependency
*/
await deps('remove');
process.exit();
}
registerSuperUser();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment