2021-11-30 19:44:58 -05:00
|
|
|
import { Factory, Seeder } from 'typeorm-seeding';
|
2021-12-01 22:18:26 -05:00
|
|
|
import { Connection } from 'typeorm';
|
2021-11-30 19:44:58 -05:00
|
|
|
import { User } from '../entities/user.entity';
|
2021-12-01 22:18:26 -05:00
|
|
|
import { Role, RoleKey } from '../entities/role.entity';
|
2021-11-30 19:44:58 -05:00
|
|
|
import * as dotenv from 'dotenv';
|
|
|
|
import * as bcrypt from 'bcrypt';
|
|
|
|
import { UserRole } from '../entities/user_role.entity';
|
|
|
|
dotenv.config();
|
|
|
|
|
|
|
|
export default class Seeds implements Seeder {
|
|
|
|
public async run(factory: Factory, connection: Connection): Promise<any> {
|
|
|
|
// CREATE ROLES
|
|
|
|
console.log('\nCreating Roles');
|
2021-12-01 22:18:26 -05:00
|
|
|
|
2021-11-30 19:44:58 -05:00
|
|
|
const roleObjects = Role.ROLES.map((key) => ({ key }));
|
|
|
|
const roleRepository = connection.getRepository(Role);
|
|
|
|
for (const roleObj of roleObjects) {
|
|
|
|
// only insert roles if not present already
|
|
|
|
const role = await roleRepository.findOne(roleObj);
|
|
|
|
if (!role) {
|
2021-12-03 16:46:44 -05:00
|
|
|
console.log(`Creating role '${roleObj.key}'`);
|
2021-11-30 19:44:58 -05:00
|
|
|
await roleRepository.insert(roleObj);
|
|
|
|
} else {
|
|
|
|
console.log(`Role '${role.key}' already exists`);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// CREATE ADMIN USER
|
|
|
|
const userRepository = connection.getRepository(User);
|
|
|
|
let adminUser = await userRepository.findOne({ email: process.env.ADMIN_EMAIL });
|
|
|
|
if (!adminUser) {
|
2021-12-01 22:18:26 -05:00
|
|
|
const adminRole = await roleRepository.findOne({ key: RoleKey.ADMIN });
|
2021-11-30 19:44:58 -05:00
|
|
|
console.log(`\nCreating Admin User with email ${process.env.ADMIN_EMAIL}`);
|
|
|
|
console.log(adminRole);
|
|
|
|
const passwordHash = await bcrypt.hash(process.env.ADMIN_PASSWORD, 10);
|
|
|
|
adminUser = new User();
|
|
|
|
adminUser.email = process.env.ADMIN_EMAIL;
|
|
|
|
adminUser.passwordHash = passwordHash;
|
2021-12-03 20:31:24 -05:00
|
|
|
adminUser.firstName = 'Admin';
|
|
|
|
adminUser.lastName = 'Site';
|
2021-11-30 19:44:58 -05:00
|
|
|
const adminUserRole = new UserRole();
|
|
|
|
adminUserRole.role = adminRole;
|
|
|
|
adminUser.userRoles = [adminUserRole];
|
|
|
|
await userRepository.save(adminUser);
|
|
|
|
} else {
|
|
|
|
console.log(`\nAdmin User with email ${process.env.ADMIN_EMAIL} already exists`);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|