Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

intial logging mechanism and deactive account #156

Merged
merged 2 commits into from
Jul 26, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
require('./config/mongoose')
const express = require('express')
const logger = require('morgan')
const morgan = require('morgan')
const cookieParser = require('cookie-parser')
const createError = require('http-errors')
const path = require('path')
const socket = require('socket.io')
const multer = require('multer')
const bodyParser = require('body-parser')
const cors = require('cors')
var winston = require('./config/winston')
const fileConstants = require('./config/fileHandlingConstants')

const indexRouter = require('./app/routes/index')
@@ -47,7 +48,17 @@ io.on('connection', (socket) => {
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')

app.use(logger('tiny'))
morgan.token('data', (req, res) => {
return JSON.stringify(req.body)
})

app.use(
morgan(
':remote-addr - :remote-user [:date[clf]] ":method :url" :status :res[content-length] ":referrer" ":user-agent" :data',
{ stream: winston.stream }
)
)

app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
@@ -80,9 +91,15 @@ app.use(function (err, req, res, next) {
res.locals.message = err.message
res.locals.error = req.app.get('env') === 'development' ? err : {}

// To include winston logging (Error)
winston.error(
`${err.status || 500} - ${err.message} - ${req.originalUrl} - ${req.method} - ${req.ip} - ${req.body}`
)

// render the error page
res.status(err.status || 500)
res.render('error')

// Socket event error handler (On max event)
req.io.on('error', function (err) {
console.error('------REQ ERROR')
3 changes: 0 additions & 3 deletions app/controllers/auth.js
Original file line number Diff line number Diff line change
@@ -9,9 +9,6 @@ module.exports = {
const token = await user.generateAuthToken()
res.send({ user: user, token: token })
} catch (error) {
if (process.env.NODE_ENV !== 'production') {
console.log(error.name, '-', error.message)
}
res.status(HttpStatus.BAD_REQUEST).json({ error: error.message })
}
},
1 change: 0 additions & 1 deletion app/controllers/event.js
Original file line number Diff line number Diff line change
@@ -176,7 +176,6 @@ module.exports = {
const events = await Event.find({ eventDate: { $gt: Date.now() } }, {}, helper.paginate(req))
.sort({ eventDate: -1 })
.exec()
console.log('Upcoming events ', events)
return res.status(HttpStatus.OK).json({ events })
} catch (error) {
HANDLER.handleError(res, next)
1 change: 0 additions & 1 deletion app/controllers/notification.js
Original file line number Diff line number Diff line change
@@ -46,7 +46,6 @@ module.exports = {
getProposalNotifications: async (req, res, next) => {
try {
const notifications = await ProposalNotifications.find({})
console.log(notifications)
return res.status(HttpStatus.OK).json({ notifications })
} catch (error) {
HANDLER.handleError(res, error)
2 changes: 0 additions & 2 deletions app/controllers/organization.js
Original file line number Diff line number Diff line change
@@ -208,7 +208,6 @@ module.exports = {
.json({ msg: 'No Organization found!' })
}
const updates = Object.keys(req.body)
console.log('req.body ', req.body)
const allowedUpdates = ['settings', 'permissions', 'authentication']
// if admin then check if valid update
if (req.user.isAdmin === true) {
@@ -307,7 +306,6 @@ module.exports = {
// console.log('Permitted to removeAdmin')
// REMOVE ADMINS FROM ADMINS LIST
const admins = org.adminInfo.adminId
console.log('adminIds ', admins)
const removableIndex = admins.indexOf(userId)
if (removableIndex === -1) {
return res
2 changes: 0 additions & 2 deletions app/controllers/proposal.js
Original file line number Diff line number Diff line change
@@ -131,7 +131,6 @@ module.exports = {
try {
const proposalId = req.body.proposalId

console.log(proposalId)
const result = await ProposalModel.findByIdAndDelete(proposalId)
const creator = result.creator

@@ -214,7 +213,6 @@ module.exports = {
},

getAllProposals: async (req, res, next) => {
console.log('All proposals called')
try {
const proposals = await ProposalModel.find({})
if (!proposals.length) {
24 changes: 12 additions & 12 deletions app/controllers/user.js
Original file line number Diff line number Diff line change
@@ -40,7 +40,6 @@ module.exports = {
await emailController.sendEmail(req, res, next, token)
return res.status(HttpStatus.CREATED).json({ user: user, token: token })
} catch (error) {
console.log(error)
return res.status(HttpStatus.NOT_ACCEPTABLE).json({ error: error })
}
},
@@ -63,7 +62,8 @@ module.exports = {
const allowedUpdates = [
'phone',
'info',
'about'
'about',
'isDeactivated'
]
// added control as per org settings
if (settingHelper.canChangeName()) {
@@ -103,9 +103,6 @@ module.exports = {
await user.save()
return res.status(HttpStatus.OK).json({ success: true, token })
} catch (error) {
if (process.env.NODE_ENV !== 'production' && error) {
console.log('Error in forgotPasswordRequest ', error)
}
return res.status(HttpStatus.BAD_REQUEST).json({ error })
}
},
@@ -135,15 +132,9 @@ module.exports = {
notificationHelper.addToNotificationForUser(id, res, notification, next)
return res.status(HttpStatus.OK).json({ updated: true })
} else {
if (process.env.NODE_ENV !== 'production') {
console.log('token expired')
}
res.status(HttpStatus.BAD_REQUEST).json({ error: 'Token expired' })
}
} catch (error) {
if (process.env.NODE_ENV !== 'production' && error) {
console.log('Something went wrong ', error)
}
res.status(HttpStatus.BAD_REQUEST).json({ error })
}
},
@@ -374,7 +365,6 @@ module.exports = {
if (user.isAdmin === true) {
const blockedIds = user.blocked.map(item => item._id)
const unblockIndex = blockedIds.indexOf(id)
console.log('UnblockIndex ', unblockIndex)
if (unblockIndex !== -1) {
user.blocked.splice(unblockIndex, 1)
await user.save()
@@ -419,5 +409,15 @@ module.exports = {
} catch (error) {
HANDLER.handleError(res, error)
}
},
// DEACTIVATE ACCOUNT (BY USER ITSELF)
deactivateAccount: async (req, res, next) => {
try {
req.user.isActivated = !req.user.isActivated
const user = await req.user.save()
return res.status(HttpStatus.OK).json({ user })
} catch (error) {
HANDLER.handleError(error)
}
}
}
2 changes: 1 addition & 1 deletion app/middleware/auth.js
Original file line number Diff line number Diff line change
@@ -32,7 +32,7 @@ const auth = async (req, res, next) => {
'isAdmin'
])
.exec()
console.log(user)
// console.log(user)

if (!user) {
throw new Error()
8 changes: 8 additions & 0 deletions app/routes/user.js
Original file line number Diff line number Diff line change
@@ -130,4 +130,12 @@ router.patch(
userController.removeUser
)

// DEACTIVATE ACCOUNT BY USER
router.patch(
'/deactivate/toggler',
isUnderMaintenance,
auth,
userController.deactivateAccount
)

module.exports = router
71 changes: 71 additions & 0 deletions config/winston.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
var appRoot = require('app-root-path')
var winston = require('winston')

const { combine, colorize, printf, timestamp } = winston.format

const logFormat = printf((info) => {
return `[${info.timestamp}] ${info.level}: ${info.message}`
})

const rawFormat = printf((info) => {
return `[${info.timestamp}] ${info.level}: ${info.message}`
})

// define the custom settings for each transport (file, console)
var options = {
file: {
level: 'info',
filename: `${appRoot}/logs/app.log`,
handleExceptions: true,
json: true,
maxsize: 5242880, // 5MB
maxFiles: 5,
colorize: false
},
errorFile: {
level: 'error',
name: 'file.error',
filename: `${appRoot}/logs/error.log`,
handleExceptions: true,
json: true,
maxsize: 5242880, // 5MB
maxFiles: 100,
colorize: true
},
console: {
level: 'debug',
handleExceptions: true,
json: false,
format: combine(colorize(), rawFormat)
}
}

// instantiate a new Winston Logger with the settings defined above
var logger = winston.createLogger({
format: combine(
timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
logFormat
),
transports: [
new winston.transports.File(options.file),
new winston.transports.Console(options.console)
],
exitOnError: false // do not exit on handled exceptions
})

// create a stream object with a 'write' function that will be used by `morgan`
logger.stream = {
write: function (message, encoding) {
// use the 'info' log level so the output will be picked up by both transports (file and console)
logger.info(message)
}
}

winston.addColors({
debug: 'white',
error: 'red',
info: 'green',
warn: 'yellow'
})

module.exports = logger
192 changes: 192 additions & 0 deletions package-lock.json
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -11,6 +11,7 @@
},
"dependencies": {
"@sendgrid/mail": "^7.0.0",
"app-root-path": "^3.0.0",
"aws-sdk": "^2.691.0",
"bcrypt": "^3.0.6",
"body-parser": "^1.19.0",
@@ -28,7 +29,8 @@
"morgan": "^1.9.1",
"multer": "^1.4.2",
"socket.io": "^2.3.0",
"validator": "^10.11.0"
"validator": "^10.11.0",
"winston": "^3.3.3"
},
"jest": {
"testEnvironment": "node",