Initial commit
This commit is contained in:
130
backend/app.ts
Normal file
130
backend/app.ts
Normal file
@@ -0,0 +1,130 @@
|
||||
import { bold } from 'chalk';
|
||||
import * as figlet from 'figlet';
|
||||
import * as mongoose from 'mongoose';
|
||||
import { exit } from 'process';
|
||||
import { hash } from 'argon2';
|
||||
import { config as dconfig } from 'dotenv';
|
||||
import * as winston from 'winston';
|
||||
import * as express from 'express';
|
||||
|
||||
import { User } from './models/user/user.model';
|
||||
import { UserType } from './models/user/user.interface';
|
||||
import bodyParser = require('body-parser');
|
||||
import { DeleteUser, GetUser, LoginUser, MW_User, PatchUser } from './endpoints/user';
|
||||
import { hashPassword, randomPepper, randomString } from './lib/crypto';
|
||||
import { config } from './config';
|
||||
|
||||
// Load .env
|
||||
dconfig({ debug: true, encoding: 'UTF-8' });
|
||||
|
||||
export const MONGO_URI = process.env.MONGO_URI || "";
|
||||
export const JWT_SECRET = process.env.JWT_SECRET;
|
||||
export const IS_DEBUG = process.env.DEBUG == 'true'
|
||||
|
||||
export let logger: winston.Logger;
|
||||
|
||||
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 == undefined) {
|
||||
logger.crit("No JWT secret was provided. Make sure you add JWT_SECRET=YOUR_SECRET to your .env file.");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Database connection
|
||||
*/
|
||||
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.");
|
||||
}
|
||||
|
||||
/**
|
||||
* HTTP server
|
||||
*/
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use(bodyParser.json({ limit: '5kb' }));
|
||||
|
||||
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.listen(config.http.port, config.http.host, () => {
|
||||
logger.info(`HTTP server is running at ${config.http.host}:${config.http.port}`);
|
||||
});
|
||||
}
|
||||
|
||||
run();
|
||||
Reference in New Issue
Block a user