Skip to content

Commit

Permalink
database connection and admin panel added
Browse files Browse the repository at this point in the history
  • Loading branch information
basil-reji committed Apr 29, 2023
1 parent ae354d2 commit 4543bb3
Show file tree
Hide file tree
Showing 48 changed files with 6,539 additions and 1,235 deletions.
84 changes: 68 additions & 16 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,52 +1,104 @@
var fs = require('fs');
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var engine = require("express-handlebars");
var logger = require('morgan');
var engine = require("express-handlebars");
var session = require("express-session");
var flash = require("express-flash");
var dotenv = require('dotenv');
var passport = require('passport')

dotenv.config()

var engineHelper = require("./helper/hbsHelper");
var db = require('./database/connection')
var engineHelper = require("./helper/hbs");

var authRouter = require('./routes/auth');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var adminRouter = require('./routes/admins');

var app = express();

// view engine setup
const hbs = engine.create({
extname: "hbs",
defaultLayout: "layout",
layoutsDir: `${__dirname}/views`,
partialsDir: `${__dirname}/views/partials`,
helpers: engineHelper,
extname: "hbs",
defaultLayout: "layout",
layoutsDir: `${__dirname}/views`,
partialsDir: `${__dirname}/views/partials`,
helpers: engineHelper,
});
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.engine("hbs", hbs.engine);

// logger setup
var app_log = fs.createWriteStream('./logs/app.log', {flags: 'a'});
var error_log = fs.createWriteStream('./logs/error.log', {flags: 'a'});
var short_log = fs.createWriteStream('./logs/short.log', {flags: 'a'});

app.use(logger('dev'));
app.use(logger('dev', { stream: error_log }));
app.use(logger('short', { stream: short_log }));
app.use(logger('combined', { stream: app_log }));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// express-session setup
app.use(session({
secret: process.env.SESSION_SECRET,
cookie: { maxAge: parseInt(process.env.SESSION_MAX_AGE) },
store: db.get(),
resave: true,
saveUninitialized: true
}));

app.use(passport.initialize());
app.use(passport.session());
app.use(passport.authenticate('session'));

// express-flash setup
app.use(flash())

//db connection
db.connect((err) => {
if (err) {
console.log(err);
} else {
// console.log("Data Base Connected...");
}
});

app.use('/', authRouter);
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/user', usersRouter);
app.use('/admin', adminRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error', {error:true});
let error = {
code: err.status || 500,
message: err.message,
stack: err.stack,
}
// console.log(error);
res.render('error', {
title: `${error.code} Error | ${process.env.APP_NAME}`,
error
});
});

module.exports = app;
module.exports = app;
80 changes: 80 additions & 0 deletions bin/setup
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#!/usr/bin/env node

const child_process = require("child_process");
const readline = require("readline-sync");
const db = require('../database/connection');
const { models } = require('../database/models');
const { admins } = require('../controller/admin');
var dotenv = require('dotenv');

dotenv.config();

const execute = (command) => {
child_process.exec(command,
function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
process.abort();
}
});
}

const setName = (name) => {
name = name.trim()
name = name.replace(/\s/g, '_')
console.log(`The app name is set to : ${name}`)
}

console.log(`Welcome to ${process.env.APP_NAME}\n`);
console.log("\n----------------------\n");

console.log("First lets update the application to its latest");
execute(`npm update`);
console.log("The packages updates successfully");

console.log("\n----------------------\n");
console.log("Now lets start with configuring the Application");
console.log("\n----------------------\n");

var app_name = readline.question("Enter your application name: ");
setName(app_name);

console.log("\n----------------------\n");
console.log("Now lets check the database connection.");

db.connect((err) => {
if (err) {
console.log("\nPlease install mongo DB atlas to continue...\n");
console.log(err);
process.abort();
}
});

console.log("Data Base Connected sucessfully");
console.log("\n----------------------\n");
console.log("lets add an admin to manage\n");

let user = models.user.super_admin;

user.email = readline.question("Enter admin email: ");

user.password = readline.questionNewPassword(
'Enter a password: ',
{
confirmMessage: 'Confirm password: ',
min: 6
}
)

admins.add(user)
.then((response) => {
console.log("YOU are ready. Follow the following commands to start\n");
console.log("npm start");
process.abort();
})
.catch((error) => {
console.log(error);
process.abort();
})
78 changes: 78 additions & 0 deletions config/authentication.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
var passport = require('passport');
var LocalStrategy = require('passport-local');
const db = require('../database/connection');
const collections = require('../database/collections.json');
const bcrypt = require('bcrypt');
const ObjectId = require('mongodb').ObjectId;

passport.use('local-login', new LocalStrategy(
{
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
},
(req, email, password, done) => {
db.get()
.collection(collections.USER)
.findOne(
{
email: email
},
{
projection: {
email: 1,
password: 1
}
}
)
.then((user) => {
if (user) {
bcrypt
.compare(password, user.password)
.then((status) => {
if (status) {
return done(null, user);
} else {
return done(null, false, req.flash('message', 'Incorrect password'));
}
}).catch((error) => {
return done(error)
});
} else {
return done(null, false, req.flash('message','Incorrect Email'));
}
}).catch((error) => {
return done(error)
})
}
));

passport.serializeUser(function (user, cb) {
process.nextTick(function () {
cb(null, user._id);
});
});

passport.deserializeUser(function (id, cb) {
process.nextTick(function () {
db.get()
.collection(collections.USER)
.findOne(
{
_id: ObjectId(id)
},
{
projection: {
password: 0
}
}
)
.then((user) => {
return cb(null, user)
}).catch((error) => {
return cb(error)
})
});
});

module.exports = passport;
Loading

0 comments on commit 4543bb3

Please sign in to comment.