import bodyParser = require('body-parser'); import { bold } from 'chalk'; import * as cors from 'cors'; import { config as dconfig } from 'dotenv'; import * as express from 'express'; import * as figlet from 'figlet'; import * as mongoose from 'mongoose'; import { exit } from 'process'; import * as winston from 'winston'; import { config } from './config'; import { GetBeat, GetBeatStats } from './endpoints/beat'; import { getNotification } from './endpoints/notification'; import { GetPhone, PostPhone } from './endpoints/phone'; import { DeleteUser, GetUser, LoginUser, MW_User, PatchUser, PostUser, UserEvents } from './endpoints/user'; import { hashPassword, randomPepper, randomString } from './lib/crypto'; import { EventManager } from './lib/eventManager'; import { RabbitMQ } from './lib/rabbit'; import { UserType } from './models/user/user.interface'; import { User } from './models/user/user.model'; // 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; export let eventManager: EventManager = new EventManager(); 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()), eventToken: randomString(16), 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."); } /** * 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')); // User authentication & actions app.post('/user/login', (req, res) => LoginUser(req, res)); // CRUD user app.get('/user/notification', MW_User, (req, res) => getNotification(req, res)); // Notifications app.get('/user/events', (req, res) => UserEvents(req, res)); app.get('/user/', MW_User, (req, res) => GetUser(req, res)); app.post('/user/', MW_User, (req, res) => PostUser(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)); // Phones app.get('/phone/:id', MW_User, (req, res) => GetPhone(req, res)); app.get('/phone', MW_User, (req, res) => GetPhone(req, res)); app.post('/phone', MW_User, (req, res) => PostPhone(req, res)); // Beats app.get('/beat/', MW_User, (req, res) => GetBeat(req, res)); app.get('/beat/stats', MW_User, (req, res) => GetBeatStats(req, res)); app.listen(config.http.port, config.http.host, () => { logger.info(`HTTP server is running at ${config.http.host}:${config.http.port}`); }); /** * Message broker */ rabbitmq = new RabbitMQ(); //await rabbitmq.init(); //logger.info("Connected with message broker."); } run();