Skip to content

Commit

Permalink
frontend sync master gsoc (#169)
Browse files Browse the repository at this point in the history
* added update restrictions, techStacks in project and orgId to a user

* added edit restriction mechanism

* intial deactivation mechanism

* intial logging mechanism and deactive account

* issue fix

* fixing org creation issue

* Fixes issues in testing (#160)

* fix failing test file user.test.js

* fixes EADDRINUSE while testing

* fixes issues in prposal route

* fixed issues in org route and added new tests

* Moving Google Analytics requests to backend (#154)

* Moving Google Analytics requetss to backend

* Requested Changes

* Minor changes

* Adding code to prevent attacks (#153)

* modified user's api (#168)

* modified user's api

* login options during login

* Changes for reactions (#166)

Co-authored-by: Rupeshiya <[email protected]>
Co-authored-by: Devesh Verma <[email protected]>
Co-authored-by: Kumar Saurabh Raj <[email protected]>
Co-authored-by: Asel Peiris <[email protected]>
Co-authored-by: pranjals149 <[email protected]>
  • Loading branch information
6 people authored Aug 7, 2020
1 parent 119722b commit 940a3fa
Show file tree
Hide file tree
Showing 33 changed files with 1,393 additions and 109 deletions.
1 change: 1 addition & 0 deletions .env.dev
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ JWT_SECRET="thisismysupersecrettokenjustkidding"
DATABASE_URL="mongodb://mongo:27017/donut-development"
SENDGRID_API_KEY='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'
SOCKET_PORT=8810
clientbaseurl = "http://localhost:3000/"
55 changes: 52 additions & 3 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
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')
const authRouter = require('./app/routes/auth')
const usersRouter = require('./app/routes/user')
Expand All @@ -21,6 +24,7 @@ const commentRouter = require('./app/routes/comment')
const projectRouter = require('./app/routes/project')
const notificationRouter = require('./app/routes/notification')
const proposalRouter = require('./app/routes/proposal')
const analyticsRouter = require('./app/routes/analytics')

const app = express()
const server = require('http').Server(app)
Expand All @@ -33,7 +37,9 @@ app.use(bodyParser.urlencoded(fileConstants.fileParameters))
const memoryStorage = multer.memoryStorage()
app.use(multer({ storage: memoryStorage }).single('file'))

server.listen(process.env.SOCKET_PORT || 8810)
if (process.env.NODE_ENV !== 'testing') {
server.listen(process.env.SOCKET_PORT || 8810)
}
// WARNING: app.listen(80) will NOT work here!

const io = socket.listen(server)
Expand All @@ -43,11 +49,41 @@ io.on('connection', (socket) => {
io.emit('user connected')
})

app.use(helmet());
app.use(hpp());

const csrfMiddleware = csurf({
cookie: true
});

app.use(session({
secret: 'codeuino',
resave: false,
saveUninitialized: true,
cookie: {
secure: true,
httpOnly: true
}
}));

app.use(cookieParser());
app.use(csrfMiddleware);

// view engine setup
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())
Expand All @@ -68,6 +104,7 @@ app.use('/shortUrl', shortUrlRouter)
app.use('/comment', commentRouter)
app.use('/project', projectRouter)
app.use('/proposal', proposalRouter)
app.use('/analytics', analyticsRouter)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
Expand All @@ -80,9 +117,21 @@ 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')
console.error(err.stack)
})
next()
})

module.exports = { app, io }
104 changes: 104 additions & 0 deletions app/controllers/analytics.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
const { google } = require('googleapis')
const analytics = google.analytics('v3')
const jwt = require('../../config/gAnalytics')
const viewId = process.env.VIEW_ID
const HANDLER = require('../utils/response-helper')
const HttpStatus = require('http-status-codes')

module.exports = {
getBrowser: async (req, res, next) => {
const { startDate, endDate, proposalId } = req.body
console.log(req.body)
try {
const result = await analytics.data.ga.get({
auth: jwt,
ids: `ga:${viewId}`,
metrics: 'ga:users',
dimensions: ['ga:browser'],
'start-date': startDate,
'end-date': endDate,
filters: `ga:pagePath==/${proposalId}`
})
res.status(HttpStatus.OK).json({ analytics: result.data.rows })
} catch (error) {
HANDLER.handleError(res, error)
}
},

getCountries: async (req, res, next) => {
const { startDate, endDate, proposalId } = req.body

try {
const result = await analytics.data.ga.get({
auth: jwt,
ids: `ga:${viewId}`,
metrics: 'ga:users',
dimensions: ['ga:country'],
'start-date': startDate,
'end-date': endDate,
filters: `ga:pagePath==/${proposalId}`
})
res.status(HttpStatus.OK).json({ analytics: result.data.rows })
} catch (error) {
HANDLER.handleError(res, error)
}
},

getDevice: async (req, res, next) => {
const { startDate, endDate, proposalId } = req.body

try {
const result = await analytics.data.ga.get({
auth: jwt,
ids: `ga:${viewId}`,
metrics: 'ga:users',
dimensions: ['ga:deviceCategory'],
'start-date': startDate,
'end-date': endDate,
filters: `ga:pagePath==/${proposalId}`
})
res.status(HttpStatus.OK).json({ analytics: result.data.rows })
} catch (error) {
HANDLER.handleError(res, error)
}
},

getTopProposals: async (req, res, next) => {
const { startDate, endDate } = req.body

try {
const result = await analytics.data.ga.get({
auth: jwt,
ids: `ga:${viewId}`,
metrics: 'ga:pageviews',
dimensions: ['ga:pagePath'],
'start-date': startDate,
'end-date': endDate,
filters: 'ga:pagePath!=/homepage'
})
res.status(HttpStatus.OK).json({ analytics: result.data })
} catch (error) {
HANDLER.handleError(res, error)
}
},

getProposalViews: async (req, res, next) => {
const { startDate, endDate, proposalId } = req.body

try {
const result = await analytics.data.ga.get({
auth: jwt,
ids: `ga:${viewId}`,
metrics: 'ga:pageviews',
dimensions: ['ga:date'],
'start-date': startDate,
'end-date': endDate,
filters: `ga:pagePath==/${proposalId}`
})

res.status(HttpStatus.OK).json({ analytics: result.data.rows })
} catch (error) {
HANDLER.handleError(res, error)
}
}
}
3 changes: 0 additions & 3 deletions app/controllers/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 })
}
},
Expand Down
4 changes: 2 additions & 2 deletions app/controllers/comment.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ module.exports = {
})
comment.votes.upVotes.user.unshift(userId)
await comment.save()
res.status(HttpStatus.OK).json({ comment: comment })
return res.status(HttpStatus.OK).json({ comment: comment })
} catch (error) {
HANDLER.handleError(res, error)
}
Expand Down Expand Up @@ -143,7 +143,7 @@ module.exports = {
})
comment.votes.downVotes.user.unshift(userId)
await comment.save()
res.status(HttpStatus.OK).json({ comment: comment })
return res.status(HttpStatus.OK).json({ comment: comment })
} catch (error) {
HANDLER.handleError(res, error)
}
Expand Down
18 changes: 13 additions & 5 deletions app/controllers/event.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const HttpStatus = require('http-status-codes')
const permission = require('../utils/permission')
const helper = require('../utils/paginate')
const notificationHelper = require('../utils/notif-helper')
const settingsHelper = require('../utils/settingHelpers')
const notification = {
heading: '',
content: '',
Expand Down Expand Up @@ -33,10 +34,17 @@ module.exports = {
try {
const event = await Event.findById(id)
if (!event) {
return res.status(HttpStatus.BAD_REQUEST).json({ message: 'No post exists' })
return res.status(HttpStatus.BAD_REQUEST).json({ msg: 'No post exists' })
}
// check for permission (TODO AFTER PREVIOUS PR MERGED)
updates.forEach(update => {
// check for permission and edit permission
if (!permission.check(req, res, event.createdBy) || (!settingsHelper.canEdit())) {
return res.status(HttpStatus.FORBIDDEN).json({ msg: 'Bad update request' })
}
// if edit allowed check allowed limit time
if (!settingsHelper.isEditAllowedNow(event.createdAt)) {
return res.status(HttpStatus.BAD_REQUEST).json({ msg: 'Edit limit expired!' })
}
updates.forEach((update) => {
event[update] = req.body[update]
})
await event.save()
Expand Down Expand Up @@ -168,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)
Expand All @@ -177,7 +184,8 @@ module.exports = {

getAllEventByUser: async (req, res, next) => {
try {
const events = await Event.find({ createdBy: req.user._id }, {}, helper.paginate(req))
const { id } = req.params
const events = await Event.find({ createdBy: id }, {}, helper.paginate(req))
.sort({ eventDate: -1 })
.populate('createdBy', '_id name.firstName name.lastName')
.exec()
Expand Down
1 change: 0 additions & 1 deletion app/controllers/notification.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading

0 comments on commit 940a3fa

Please sign in to comment.