AutoCallManu/utils/database.js

70 lines
2.0 KiB
JavaScript

import Sequelize from "sequelize";
import bcrypt from 'bcrypt';
import { permissionBits } from "./permissions.js";
function loadDatabase() {
const sequelize = new Sequelize("database", "user", "password", {
host: "localhost",
dialect: "sqlite",
logging: false,
storage: "database.sqlite",
});
const contactsDB = sequelize.define("contacts", {
phone: {
type: Sequelize.STRING,
primaryKey: true,
},
firstName: {
type: Sequelize.STRING,
},
lastName: {
type: Sequelize.STRING,
},
called: {
type: Sequelize.INTEGER, // 0: not called - 1: called - 2: ongoing call (- 3: no response ?)
defaultValue: false,
},
vote: {
type: Sequelize.BOOLEAN,
defaultValue: false,
},
});
const userDB = sequelize.define("users", {
username: {
type: Sequelize.STRING,
primaryKey: true,
},
password: {
type: Sequelize.STRING,
},
permissions: {
type: Sequelize.INTEGER,
defaultValue: permissionBits.DEFAULT,
},
}, {
hooks: {
beforeCreate: async function(user) {
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(user.password, salt);
},
},
});
userDB.prototype.validPassword = async function(password) {
return await bcrypt.compare(password, this.password);
}
contactsDB.sync();
userDB.sync();
global.database = {};
global.database.contacts = contactsDB;
global.database.users = userDB;
//global.database.users.create({username: "admin", password: "admin", permissions: permissionBits.DEFAULT | permissionBits.CALL | permissionBits.ADMIN})
//global.database.users.create({username: "test", password: "test", permissions: permissionBits.DEFAULT | permissionBits.CALL})
}
export { loadDatabase };