aboutsummaryrefslogtreecommitdiff
path: root/db.js
blob: dbef8f4c9a69895ecc8a3faac0f2a5983affa7d4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const mariadb = require("mariadb");
const bcrypt = require("bcrypt");
const nanoid = require("nanoid");
const fs = require("fs");

class DB {
    constructor() {
        this.pool = mariadb.createPool({
            host: process.env.DBHost,
            user: process.env.DBUser,
            password: process.env.DBPassword,
            database: process.env.DBName,
        });
        this.init();
        this.query("SELECT * FROM users").then((res) => {
            if (res.length === 0) this.initValues();
        });
    }

    connect() {
        return this.pool.getConnection();
    }

    init() {
        fs.readFile(__dirname + "/tables.sql", "utf8", async (err, data) => {
            if (err) throw err;
            const queries = data.split(";");
            queries.pop();
            for (const query of queries) await this.query(query);
            console.log("Tables created!");

            const res = await this.query("SELECT * FROM users");
            if (res.length === 0) this.initValues();
        });
    }

    initValues() {
        fs.readFile(__dirname + "/names.csv", "utf8", (err, data) => {
            if (err) throw err;
            const classes = data.split("--");
            const userPasswords = [];
            classes.forEach((clazz, classIndex) => {
                const students = clazz.split("\n");
                students.forEach(async (student) => {
                    // Fix undefined
                    if (student && student.length > 3) {
                        const [_, surname, name] = student.split(",");
                        const names = name.split(" ");
                        const middlename = names.length > 1 && names[1] ? names.slice(1).join(" ") : null;
                        let username = surname.toLowerCase().slice(0, 6);
                        if (middlename) username += middlename[0].toLowerCase();
                        username += names[0].toLowerCase().slice(0, 2);
                        const pwd = nanoid.nanoid(8);
                        const password = await bcrypt.hash(pwd, 12);
                        userPasswords.push({ username, pwd });
                        await this.query(
                            "INSERT INTO users (username, name, middlename, surname, password, class_id, type_id) VALUE (?,?,?,?,?,?,?)",
                            [username, names[0].replace("\r", ""), middlename, surname, password, classIndex + 1, 2]
                        );
                    }
                });
            });
            fs.writeFile(__dirname + "/users.json", JSON.stringify(userPasswords), console.error);
        });
    }

    async query(query, params) {
        const conn = await this.connect();
        try {
            return await conn.query(query, params);
        } catch (e) {
            throw e;
        } finally {
            conn.release();
        }
    }
}

module.exports = new DB();