162 lines
5.3 KiB
TypeScript
162 lines
5.3 KiB
TypeScript
import bodyParser = require('body-parser');
|
|
import { bold } from 'chalk';
|
|
import { config as dconfig } from 'dotenv';
|
|
import * as express from 'express';
|
|
import * as figlet from 'figlet';
|
|
import * as mongoose from 'mongoose';
|
|
import * as cors from 'cors';
|
|
import { exit } from 'process';
|
|
import * as winston from 'winston';
|
|
import { RabbitMQ } from './lib/rabbit';
|
|
|
|
import { config } from './config';
|
|
import { DeleteUser, GetUser, LoginUser, MW_User, PatchUser } from './endpoints/user';
|
|
import { hashPassword, randomPepper, randomString } from './lib/crypto';
|
|
import { UserType } from './models/user/user.interface';
|
|
import { User } from './models/user/user.model';
|
|
import { GetPhone, PostPhone } from './endpoints/phone';
|
|
import { GetBeat } from './endpoints/beat';
|
|
|
|
// Load .env
|
|
dconfig({ debug: true, encoding: 'UTF-8' });
|
|
|
|
export const MONGO_URI = process.env.MONGO_URI || "";
|
|
export const RABBITMQ_URI = process.env.RABBITMQ_URI || "";
|
|
export const JWT_SECRET = process.env.JWT_SECRET || "";
|
|
export const IS_DEBUG = process.env.DEBUG == 'true';
|
|
|
|
export let logger: winston.Logger;
|
|
export let rabbitmq: RabbitMQ;
|
|
|
|
async function run() {
|
|
const { combine, timestamp, label, printf, prettyPrint } = winston.format;
|
|
|
|
const myFormat = printf(({ level, message, label, timestamp }) => {
|
|
return `${timestamp} ${level} ${message}`;
|
|
});
|
|
|
|
/**
|
|
* Printing starting screen
|
|
*/
|
|
console.log(figlet.textSync('Livebeat', {
|
|
font: 'Doom'
|
|
}));
|
|
console.log(`Starting up version ${bold("1.0.0")} of Livebeat ...
|
|
============================================`)
|
|
|
|
/**
|
|
* Setting up logger
|
|
*/
|
|
logger = winston.createLogger({
|
|
level: IS_DEBUG ? 'debug' : 'info',
|
|
levels: winston.config.syslog.levels,
|
|
format: combine(
|
|
timestamp(),
|
|
prettyPrint(),
|
|
myFormat
|
|
),
|
|
defaultMeta: { },
|
|
transports: [
|
|
new winston.transports.File({ filename: 'error.log', level: 'error' }),
|
|
new winston.transports.File({ filename: 'combined.log' })
|
|
]
|
|
});
|
|
|
|
// Adding seperate logger for files (with color)
|
|
logger.add(new winston.transports.Console({
|
|
format: combine(
|
|
winston.format.colorize({ level: true }),
|
|
timestamp(),
|
|
prettyPrint(),
|
|
myFormat
|
|
)
|
|
}));
|
|
|
|
|
|
logger.info("Logger started");
|
|
|
|
if (IS_DEBUG) {
|
|
logger.info("Debug mode is enabled. Do not use this in production!")
|
|
}
|
|
|
|
if (JWT_SECRET == "") {
|
|
logger.crit("No JWT secret was provided. Make sure you add JWT_SECRET=YOUR_SECRET to your .env file.");
|
|
exit(1);
|
|
}
|
|
|
|
if (RABBITMQ_URI == "") {
|
|
logger.crit("No RabbitMQ URI was provided. Make sure you add RABBITMQ_URI=YOUR_URL to your .env file.");
|
|
exit(1);
|
|
}
|
|
|
|
/**
|
|
* Database connection
|
|
*/
|
|
mongoose.set('debug', true);
|
|
const connection = await mongoose.connect(MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true }).catch((err) => {
|
|
logger.crit("Database connection could not be made: ", err);
|
|
exit(1);
|
|
});
|
|
logger.info(`Database connection made to ${mongoose.connection.host}`);
|
|
|
|
// Check if admin account doesn't exists
|
|
if((await User.countDocuments({ type: UserType.ADMIN })) == 0) {
|
|
const randomPassword = "$1" + randomString(12);
|
|
const salt = randomString(config.authentification.salt_length);
|
|
|
|
await User.create({
|
|
name: 'admin',
|
|
password: await hashPassword(randomPassword + salt + randomPepper()),
|
|
salt,
|
|
createdAt: Date.now(),
|
|
lastLogin: 0,
|
|
type: UserType.ADMIN
|
|
});
|
|
logger.info("===================================================");
|
|
logger.info("ADMIN USER HAS BEEN CREATED! Username: admin\tPassword: " + randomPassword);
|
|
logger.info("===================================================");
|
|
} else {
|
|
logger.debug("At least one admin user already exists, skip.");
|
|
}
|
|
|
|
/**
|
|
* Message broker
|
|
*/
|
|
rabbitmq = new RabbitMQ();
|
|
await rabbitmq.init();
|
|
logger.info("Connected with message broker.");
|
|
|
|
/**
|
|
* HTTP server
|
|
*/
|
|
const app = express();
|
|
app.use(express.json());
|
|
app.use(cors());
|
|
app.use(bodyParser.json({ limit: '5kb' }));
|
|
|
|
app.use((req, res, next) => {
|
|
res.on('finish', () => {
|
|
const done = Date.now();
|
|
logger.debug(`${req.method} - ${req.url} ${JSON.stringify(req.body)} -> ${res.statusCode}`);
|
|
});
|
|
next();
|
|
});
|
|
|
|
app.get('/', (req, res) => res.status(200).send('OK'));
|
|
app.get('/user/', MW_User, (req, res) => GetUser(req, res));
|
|
app.get('/user/:id', MW_User, (req, res) => GetUser(req, res));
|
|
app.patch('/user/:id', MW_User, (req, res) => PatchUser(req, res));
|
|
app.delete('/user/:id', MW_User, (req, res) => DeleteUser(req, res));
|
|
app.post('/user/login', (req, res) => LoginUser(req, res));
|
|
|
|
app.get('/phone/:id', (req, res) => GetPhone(req, res));
|
|
app.post('/phone', MW_User, (req, res) => PostPhone(req, res));
|
|
|
|
app.get('/beat/', MW_User, (req, res) => GetBeat(req, res));
|
|
|
|
app.listen(config.http.port, config.http.host, () => {
|
|
logger.info(`HTTP server is running at ${config.http.host}:${config.http.port}`);
|
|
});
|
|
}
|
|
|
|
run(); |