Skip to content

Commit

Permalink
Merge branch 'development' of https://github.com/codeuino/social-plat…
Browse files Browse the repository at this point in the history
…form-donut-backend into development
  • Loading branch information
Rupeshiya committed Aug 18, 2020
2 parents 75aec9c + 134674a commit 299942c
Show file tree
Hide file tree
Showing 21 changed files with 376 additions and 7 deletions.
10 changes: 8 additions & 2 deletions .env.dev
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
PORT=5000
NODE_ENV="development"
JWT_SECRET="thisismysupersecrettokenjustkidding"
DATABASE_URL"mongodb://mongo:27017/donut-development"
DATABASE_URL="mongodb://mongo:27017/donut-development"
SENDGRID_API_KEY='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'
SOCKET_PORT=8810
clientbaseurl = "http://localhost:3000/"
clientbaseurl = "http://localhost:3000"
SOCKET_PORT=8810
REDIS_HOST="redis"
REDIS_PORT=6379
REDIS_PASSWORD="auth"
REDIS_DB=0
REDIS_ACTIVITY_DB=1
2 changes: 2 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ 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 activityRouter = require('./app/routes/activity')

const app = express()
const server = require('http').Server(app)
Expand Down Expand Up @@ -83,6 +84,7 @@ app.use('/comment', commentRouter)
app.use('/project', projectRouter)
app.use('/proposal', proposalRouter)
app.use('/analytics', analyticsRouter)
app.use('/activity', activityRouter)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
Expand Down
32 changes: 32 additions & 0 deletions app/controllers/activity.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const User = require('../models/User')
const Activity = require('../models/Activity')

const HttpStatus = require('http-status-codes')
module.exports = {

getActivity: async (req, res, next) => {
// userID whose activity will be fetched by admin
const { id } = req.params

try {
// Check if user exists
const user = await User.findById(req.user._id)
if (!user) {
return res.status(HttpStatus.BAD_REQUEST).json({ msg: 'No such user exists!' })
}

// check if not admin
if (user.isAdmin !== true) {
return res.status(HttpStatus.BAD_REQUEST).json({ msg: 'You don\'t have permission!' })
}

const data = await Activity.findOne({ userId: id })
return res.status(HttpStatus.OK).json({ activity: data.activity })
} catch (error) {
if (process.env.NODE_ENV !== 'production') {
console.log(error.name, '-', error.message)
}
return res.status(HttpStatus.BAD_REQUEST).json({ error: error.message })
}
}
}
4 changes: 4 additions & 0 deletions app/controllers/auth.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
const User = require('../models/User')
const HttpStatus = require('http-status-codes')
const activityHelper = require('../utils/activity-helper')

module.exports = {
authenticateUser: async (req, res, next) => {
const email = req.body.email
Expand All @@ -13,9 +15,11 @@ module.exports = {
}
},
logout: (req, res, next) => {
activityHelper.addActivityToDb(req, res)
res.status(HttpStatus.OK).json({ success: 'ok' })
},
logoutAll: (req, res, next) => {
activityHelper.addActivityToDb(req, res)
res.status(HttpStatus.OK).json({ success: 'ok' })
}
}
8 changes: 6 additions & 2 deletions app/controllers/comment.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ const HttpStatus = require('http-status-codes')
const CommentModel = require('../models/Comment')
const permission = require('../utils/permission')
const helper = require('../utils/paginate')
const activityTracker = require('../utils/activity-helper')
const collectionTypes = require('../utils/collections')

module.exports = {
// CREATE COMMENT (ISSUE IN CREATE COMMENT )
Expand All @@ -14,7 +16,8 @@ module.exports = {
comment.userId = userId
comment.postId = id // added postId
await comment.save()
res.status(HttpStatus.CREATED).json({ comment: comment })
activityTracker.addToRedis(req, res, next, collectionTypes.COMMENT, comment._id)
return res.status(HttpStatus.CREATED).json({ comment: comment })
} catch (error) {
HANDLER.handleError(res, error)
}
Expand Down Expand Up @@ -63,7 +66,8 @@ module.exports = {
comment[update] = req.body[update]
})
await comment.save()
res.status(HttpStatus.OK).json({ comment: comment })
activityTracker.addToRedis(req, res, next, collectionTypes.COMMENT, comment._id)
return res.status(HttpStatus.OK).json({ comment: comment })
} catch (error) {
HANDLER.handleError(res, error)
}
Expand Down
11 changes: 10 additions & 1 deletion app/controllers/event.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ const permission = require('../utils/permission')
const helper = require('../utils/paginate')
const notificationHelper = require('../utils/notif-helper')
const settingsHelper = require('../utils/settingHelpers')
const activityTracker = require('../utils/activity-helper')
const collectionTypes = require('../utils/collections')

const notification = {
heading: '',
content: '',
Expand All @@ -22,6 +25,7 @@ module.exports = {
notification.content = `${event.eventName} is added!`
notification.tag = 'New!'
notificationHelper.addToNotificationForAll(req, res, notification, next)
activityTracker.addToRedis(req, res, next, collectionTypes.EVENT, event._id)
res.status(HttpStatus.CREATED).json({ event: event })
} catch (error) {
res.status(HttpStatus.BAD_REQUEST).json({ error: error })
Expand Down Expand Up @@ -53,6 +57,7 @@ module.exports = {
notification.content = `${event.eventName} is updated!`
notification.tag = 'Update'
notificationHelper.addToNotificationForAll(req, res, notification, next)
activityTracker.addToRedis(req, res, next, collectionTypes.EVENT, event._id)
res.status(HttpStatus.OK).json({ event: event })
} catch (error) {
HANDLER.handleError(res, error)
Expand Down Expand Up @@ -163,7 +168,11 @@ module.exports = {
notification.content = `Event ${deleteEvent.eventName} is deleted!`
notification.tag = 'Deleted'
notificationHelper.addToNotificationForAll(req, res, notification, next)
return res.status(HttpStatus.OK).json({ deleteEvent: deleteEvent, message: 'Deleted the event' })
activityTracker.addToRedis(req, res, next, collectionTypes.EVENT, deleteEvent._id)
return res.status(HttpStatus.OK).json({
deleteEvent: deleteEvent,
message: 'Deleted the event'
})
}
return res.status(HttpStatus.BAD_REQUEST).json({ msg: 'Not permitted!' })
} catch (error) {
Expand Down
7 changes: 7 additions & 0 deletions app/controllers/organization.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ const Event = require('../models/Event')
const permission = require('../utils/permission')
const TAGS = require('../utils/notificationTags')
const Organisation = require('../models/Organisation')
const activityTracker = require('../utils/activity-helper')
const collectionTypes = require('../utils/collections')

const notification = {
heading: '',
content: '',
Expand All @@ -29,6 +32,7 @@ module.exports = {
notification.content = `${orgData.name} is created!`
notification.tag = TAGS.NEW
notificationHelper.addToNotificationForAll(req, res, notification, next)
activityTracker.addToRedis(req, res, next, collectionTypes.ORG, org._id)
return res.status(HttpStatus.CREATED).json({ orgData })
} catch (error) {
HANDLER.handleError(res, error)
Expand Down Expand Up @@ -71,6 +75,7 @@ module.exports = {
helper.mapToDb(req, org)
}
await org.save()
activityTracker.addToRedis(req, res, next, collectionTypes.ORG, org._id)
return res.status(HttpStatus.OK).json({ organization: org })
} catch (error) {
HANDLER.handleError(res, error)
Expand Down Expand Up @@ -127,6 +132,7 @@ module.exports = {
notification.content = `${org.name} is deleted!`
notification.tag = TAGS.DELETE
notificationHelper.addToNotificationForAll(req, res, notification, next)
activityTracker.addToRedis(req, res, next, collectionTypes.ORG, org._id)
return res.status(HttpStatus.OK).json({ organization: org })
} catch (error) {
HANDLER.handleError(res, error)
Expand Down Expand Up @@ -228,6 +234,7 @@ module.exports = {
.status(HttpStatus.BAD_REQUEST)
.json({ msg: 'Invalid update' })
}
activityTracker.addToRedis(req, res, next, collectionTypes.ORG, organization._id)
// else not admin
return res
.status(HttpStatus.BAD_REQUEST)
Expand Down
3 changes: 3 additions & 0 deletions app/controllers/post.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ const imgUploadHelper = require('../utils/uploader')
const permission = require('../utils/permission')
const helper = require('../utils/paginate')
const settingsHelper = require('../utils/settingHelpers')
const activityTracker = require('../utils/activity-helper')
const collectionTypes = require('../utils/collections')

module.exports = {
// CREATE POST
Expand All @@ -19,6 +21,7 @@ module.exports = {
try {
await post.save()
// req.io.emit('new post created', { data: post.content })
activityTracker.addToRedis(req, res, next, collectionTypes.POST, post._id)
return res.status(HttpStatus.CREATED).json({ post })
} catch (error) {
HANDLER.handleError(res, error)
Expand Down
4 changes: 4 additions & 0 deletions app/controllers/project.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,16 @@ const HttpStatus = require('http-status-codes')
const helper = require('../utils/paginate')
const permission = require('../utils/permission')
const settingsHelper = require('../utils/settingHelpers')
const activityTracker = require('../utils/activity-helper')
const collectionTypes = require('../utils/collections')

module.exports = {
createProject: async (req, res, next) => {
try {
const project = await new Project(req.body)
project.createdBy = req.user._id
await project.save()
activityTracker.addToRedis(req, res, next, collectionTypes.PROJECT, project._id)
return res.status(HttpStatus.CREATED).json({ project })
} catch (error) {
HANDLER.handleError(res, error)
Expand Down Expand Up @@ -98,6 +101,7 @@ module.exports = {
await Project.findByIdAndRemove(id)
return res.status(HttpStatus.OK).json({ msg: 'Project deleted!' })
}
activityTracker.addToRedis(req, res, next, collectionTypes.PROJECT, project._id)
return res.status(HttpStatus.BAD_REQUEST).json({ msg: 'Not permitted!' })
} catch (error) {
HANDLER.handleError(res, error)
Expand Down
10 changes: 10 additions & 0 deletions app/controllers/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ const Events = require('../models/Event')
const Organization = require('../models/Organisation')
const TAGS = require('../utils/notificationTags')
const settingHelper = require('../utils/settingHelpers')
const Activity = require('../models/Activity')
const activityHelper = require('../utils/activity-helper')

const notification = {
heading: '',
content: '',
Expand Down Expand Up @@ -38,6 +41,11 @@ module.exports = {
const token = await user.generateAuthToken()
// Added fn to send email to activate account with warm message
await emailController.sendEmail(req, res, next, token)

// create redis db for activity for the user
const activity = new Activity({ userId: data._id })
await activity.save()

return res.status(HttpStatus.CREATED).json({ user: user, token: token })
} catch (error) {
return res.status(HttpStatus.NOT_ACCEPTABLE).json({ error: error })
Expand Down Expand Up @@ -169,6 +177,8 @@ module.exports = {
try {
req.user.tokens = []
await req.user.save()
// add all activity to db after successfully logged out
activityHelper.addActivityToDb(req, res)
return res.status(HttpStatus.OK).json({ msg: 'User logged out Successfully!' })
} catch (error) {
HANDLER.handleError(res, error)
Expand Down
56 changes: 56 additions & 0 deletions app/middleware/activity.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
const User = require('../models/User')
const redis = require('../../config/redis')

const activity = async (req, res, next) => {
var redisClient = redis.redisClient
var route = req.originalUrl.replace(/\?.*$/, '')
var method = req.method
var userID = req.user.id.toString()
console.log('req.body ', req.body)
console.log('res.locals.data ', res.locals.data)
console.log('route ', route)
console.log('methods ', method)

if (route === '/user/logout') {
var activityData = await redisClient.lrange(userID, 0, -1)
const data = await User.findOne({
_id: userID
})
var activityElement = {
route: '',
method: '',
collectionType: '',
id: '',
timestamp: ''
}
for (let index = 0; index < activityData.length; index++) {
var activityDataElement = activityData[index].split(',')
activityElement.route = activityDataElement[0]
activityElement.method = activityDataElement[1]
activityElement.collectionType = activityDataElement[2]
activityElement.id = activityDataElement[3]
activityElement.timestamp = activityDataElement[4]
data.activity.unshift(activityElement)
}
await data.update()
console.log('DATA')
console.log(data)
// clear data from redis
await redisClient.del(userID)
} else if (method !== 'GET') {
var objectID = res.locals.data._id
userID = objectID
var timeStamp = Date()
var collectionType = res.locals.collectionType
if (typeof res.locals.data.userId !== 'undefined') {
userID = res.locals.data.userId
}
// example /auth/login,POST,user,5ed09e9d446f2b1c208b6ba8,Thu Jul 23 2020 20:28:29 GMT+0530 (India Standard Time)
activityElement = route.concat(',', method, ',', collectionType, ',', objectID, ',', timeStamp)
// userID => [(route, collection, method, objectID), (route,method, collection, objectID) ...]
await redisClient.rpush(userID, activityElement)
next()
}
}

module.exports = activity
33 changes: 33 additions & 0 deletions app/models/Activity.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const mongoose = require('mongoose')
const Schema = mongoose.Schema

const activitySchema = new Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
activity: [{
route: {
type: String,
required: true
},
method: {
type: String,
required: true
},
collectionType: {
type: String,
required: true
},
id: {
type: String,
required: true
},
timestamp: {
type: String,
required: true
}
}]
})

module.exports = mongoose.model('Activity', activitySchema)
16 changes: 16 additions & 0 deletions app/routes/activity.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const express = require('express')
const router = express.Router()

const activityController = require('../controllers/activity')
const isUnderMaintenance = require('../middleware/maintenance')
const auth = require('../middleware/auth')

// get a User activity
router.get(
'/user/:id',
isUnderMaintenance,
auth,
activityController.getActivity
)

module.exports = router
1 change: 0 additions & 1 deletion app/routes/organisation.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ router.post(
'/',
isUnderMaintenance,
uploader.upload.single('image'),
auth,
OrgController.createOrganization
)

Expand Down
Loading

0 comments on commit 299942c

Please sign in to comment.