Skip to content

Commit

Permalink
Merge pull request #151 from codeuino/development
Browse files Browse the repository at this point in the history
updating master with developement
  • Loading branch information
devesh-verma authored Jul 14, 2020
2 parents 0870d96 + 6a859e3 commit 119722b
Show file tree
Hide file tree
Showing 67 changed files with 5,614 additions and 222 deletions.
3 changes: 3 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
.git
.github
4 changes: 3 additions & 1 deletion .env.dev
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
PORT=5000
NODE_ENV="development"
JWT_SECRET="thisismysupersecrettokenjustkidding"
DATABASE_URL="mongodb://localhost:27017/donut-development"
DATABASE_URL="mongodb://mongo:27017/donut-development"
SENDGRID_API_KEY='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'
SOCKET_PORT=8810
4 changes: 3 additions & 1 deletion .env.test
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
PORT=3000
NODE_ENV=testing
JWT_SECRET=thisismysupersecrettokenjustkidding
DATABASE_URL=mongodb+srv://donut-admin:[email protected]/donut-testing?retryWrites=true&w=majority
DATABASE_URL=mongodb+srv://donut-admin:[email protected]/donut-testing?retryWrites=true&w=majority
SENDGRID_API_KEY = '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'
SOCKET_PORT = 8810
39 changes: 39 additions & 0 deletions .github/workflows/image-workflow.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
name: donut-server-image-ci

on:
push:
branches:
- development

tags:
- v*

env:
IMAGE_NAME: donut-server:latest
REPO_NAME: codeuino1
REGISTRY_NAME: registry.hub.docker.com

jobs:
push:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2

- name: Build image
run: docker build . --file Dockerfile.prod --tag $IMAGE_NAME

- name: Log into registry
run: docker login --username {{ secrets.DOCKER_USERNAME }} --password {{ secrets.DOCKER_PASSWORD }}
- name: Push image
run: |
IMAGE_ID=$REGISTRY_NAME/$REPO_NAME/$IMAGE_NAME
[[ "${{ github.ref }}" == "refs/tags/"* ]] && VERSION=$(echo $VERSION | sed -e 's/^v//')
echo IMAGE_ID=$IMAGE_ID
echo VERSION=$VERSION
docker tag $IMAGE_NAME $IMAGE_ID:$VERSION
docker push $IMAGE_ID:$VERSION
docker tag $IMAGE_NAME $IMAGE_ID:latest
docker push $IMAGE_ID:$VERSION
21 changes: 21 additions & 0 deletions Dockerfile.dev
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
FROM node:14

ENV NODE_ENV="development"

# Copy package.json file into container
COPY package.json package.json
COPY package-lock.json package-lock.json

# Install node modules
RUN npm install && \
npm install --only=dev && \
npm cache clean --force --loglevel=error

# Volume to mount source code into container
VOLUME [ "/server" ]

# move to the source code directory
WORKDIR /server

# Start the server
CMD mv ../node_modules . && npm run dev
16 changes: 16 additions & 0 deletions Dockerfile.prod
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
FROM node:14

ENV NODE_ENV="production"

WORKDIR /server

RUN git clone https://github.com/codeuino/social-platform-donut-backend.git

WORKDIR /server/social-platform-donut-backend

RUN npm install && \
npm install pm2@latest -g && \
npm cache clean --force --loglevel=error

# Start the server
CMD [ "pm2", "start", "./bin/www", "--time", "--no-daemon" ]
46 changes: 44 additions & 2 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,44 @@ const logger = 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')
const fileConstants = require('./config/fileHandlingConstants')

const indexRouter = require('./app/routes/index')
const authRouter = require('./app/routes/auth')
const usersRouter = require('./app/routes/user')
const postRouter = require('./app/routes/post')
const eventRouter = require('./app/routes/event')
const shortUrlRouter = require('./app/routes/urlShortner')
const organizationRouter = require('./app/routes/organisation')
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 app = express()
const server = require('http').Server(app)

app.use(cors())

app.use(bodyParser.json({ limit: '200mb' }))
app.use(bodyParser.urlencoded(fileConstants.fileParameters))

const memoryStorage = multer.memoryStorage()
app.use(multer({ storage: memoryStorage }).single('file'))

server.listen(process.env.SOCKET_PORT || 8810)
// WARNING: app.listen(80) will NOT work here!

const io = socket.listen(server)
let count = 0
io.on('connection', (socket) => {
console.log('socket connected count ', count++)
io.emit('user connected')
})

// view engine setup
app.set('views', path.join(__dirname, 'views'))
Expand All @@ -21,15 +52,26 @@ app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))
app.use((req, res, next) => {
req.io = io
next()
})

app.use('/notification', notificationRouter)
app.use('/', indexRouter)
app.use('/auth', authRouter)
app.use('/user', usersRouter)
app.use('/post', postRouter)
app.use('/org', organizationRouter)
app.use('/event', eventRouter)
app.use('/shortUrl', shortUrlRouter)
app.use('/comment', commentRouter)
app.use('/project', projectRouter)
app.use('/proposal', proposalRouter)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404, 'route doesn\'t exist'))
next(createError(404, "route doesn't exist"))
})

// error handler
Expand All @@ -43,4 +85,4 @@ app.use(function (err, req, res, next) {
res.render('error')
})

module.exports = app
module.exports = { app, io }
10 changes: 5 additions & 5 deletions app/controllers/auth.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const User = require('../models/User')

const HttpStatus = require('http-status-codes')
module.exports = {
authenticateUser: async (req, res, next) => {
const email = req.body.email
Expand All @@ -10,15 +10,15 @@ module.exports = {
res.send({ user: user, token: token })
} catch (error) {
if (process.env.NODE_ENV !== 'production') {
// console.log('error ', error)
console.log(error.name, '-', error.message)
}
res.status(400).send({ error: error })
res.status(HttpStatus.BAD_REQUEST).json({ error: error.message })
}
},
logout: (req, res, next) => {
res.json({ success: 'ok' })
res.status(HttpStatus.OK).json({ success: 'ok' })
},
logoutAll: (req, res, next) => {
res.json({ success: 'ok' })
res.status(HttpStatus.OK).json({ success: 'ok' })
}
}
151 changes: 151 additions & 0 deletions app/controllers/comment.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
const HANDLER = require('../utils/response-helper')
const HttpStatus = require('http-status-codes')
const CommentModel = require('../models/Comment')
const permission = require('../utils/permission')
const helper = require('../utils/paginate')

module.exports = {
// CREATE COMMENT (ISSUE IN CREATE COMMENT )
comment: async (req, res, next) => {
const { id } = req.params
const userId = req.user.id.toString()
try {
const comment = new CommentModel(req.body)
comment.userId = userId
comment.postId = id // added postId
await comment.save()
res.status(HttpStatus.CREATED).json({ comment: comment })
} catch (error) {
HANDLER.handleError(res, error)
}
},

// DELETE COMMENT
delete: async (req, res, next) => {
const { id } = req.params
try {
const comment = await CommentModel.findById(id)
if (!comment) {
return res.status(HttpStatus.NOT_FOUND).json({ error: 'No comment exist' })
}
// Add rights for admins and moderators as well (TODO)
if (!permission.check(req, res, comment.userId)) {
return res.status(HttpStatus.FORBIDDEN).json({ message: 'Bad delete request' })
}
await CommentModel.findByIdAndRemove(id)
res.status(HttpStatus.OK).json({ comment: comment })
} catch (error) {
HANDLER.handleError(res, error)
}
},

// UPDATE COMMENT
update: async (req, res, next) => {
const { id } = req.params
const updates = Object.keys(req.body)
const valid = ['content']
const isValidOperation = updates.every((update) => {
return valid.includes(update)
})
if (!isValidOperation) {
return res.status(HttpStatus.BAD_REQUEST).json({ error: 'Wrong Update Request' })
}
try {
const comment = await CommentModel.findById(id)
if (!comment) {
return res.status(HttpStatus.NOT_FOUND).json({ error: 'No comment exist' })
}
// also add admin or moderator control (TODO)
if (!permission.check(req, res, comment.userId)) {
return res.status(HttpStatus.BAD_REQUEST).json({ error: 'Wrong update' })
}
updates.forEach(update => {
comment[update] = req.body[update]
})
await comment.save()
res.status(HttpStatus.OK).json({ comment: comment })
} catch (error) {
HANDLER.handleError(res, error)
}
},

// GET ALL COMMENTS OF A POST BY postId
getCommentByPost: async (req, res, next) => {
const { id } = req.params
try {
const comments = await CommentModel.find({ postId: id }, {}, helper.paginate(req))
.populate('userId', ['name.firstName', 'name.lastName'])
.sort({ updatedAt: -1 })
.lean()
.exec()
if (!comments) {
return res.status(HttpStatus.NOT_FOUND).json({ error: 'No such post' })
}
res.status(HttpStatus.OK).json({ comments: comments })
} catch (error) {
HANDLER.handleError(res, error)
}
},

// UPVOTE COMMENT
upvote: async (req, res, next) => {
const { id } = req.params
const userId = req.user.id.toString()
try {
const comment = await CommentModel.findById(id)
if (!comment) {
return res.status(HttpStatus.NOT_FOUND).json({ error: 'No comment found' })
}
// CHECKS IF THE USER HAS ALREADY UPVOTED THE COMMENT
comment.votes.upVotes.user.filter(user => {
if (JSON.stringify(user) === JSON.stringify(userId)) {
return res.status(HttpStatus.BAD_REQUEST).json({
error: 'Bad request'
})
}
})
// CHECKS IF THE USER HAS ALREADY DOWNVOTED THE COMMENT
comment.votes.downVotes.user.filter(user => {
if (JSON.stringify(user) === JSON.stringify(userId)) {
comment.votes.downVotes.user.remove(user)
}
})
comment.votes.upVotes.user.unshift(userId)
await comment.save()
res.status(HttpStatus.OK).json({ comment: comment })
} catch (error) {
HANDLER.handleError(res, error)
}
},

// DOWNVOTE COMMENT
downvote: async (req, res, next) => {
const { id } = req.params
const userId = req.user.id.toString()
try {
const comment = await CommentModel.findById(id)
if (!comment) {
return res.status(HttpStatus.NOT_FOUND).json({ error: 'No comment found' })
}
// CHECKS IF THE USER HAS ALREADY DOWNVOTED THE COMMENT
comment.votes.downVotes.user.filter(user => {
if (JSON.stringify(user) === JSON.stringify(userId)) {
return res.status(HttpStatus.BAD_REQUEST).json({
error: 'Bad request'
})
}
})
// CHECKS IF THE USER HAS ALREADY UPVOTED THE COMMENT
comment.votes.upVotes.user.filter(user => {
if (JSON.stringify(user) === JSON.stringify(userId)) {
comment.votes.upVotes.user.remove(user)
}
})
comment.votes.downVotes.user.unshift(userId)
await comment.save()
res.status(HttpStatus.OK).json({ comment: comment })
} catch (error) {
HANDLER.handleError(res, error)
}
}
}
35 changes: 35 additions & 0 deletions app/controllers/email.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const sendgridMail = require('@sendgrid/mail')
const ejs = require('ejs')
const path = require('path')
const sendGridApi = process.env.SENDGRID_API_KEY || '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'

sendgridMail.setApiKey(sendGridApi)

module.exports = {
sendEmail: async (req, res, next, token) => {
const filePath = path.join(__dirname, '/../../views/emailTemplate.ejs')
ejs.renderFile(filePath, { token: token }, (err, data) => {
if (err) {
console.log('Error in renderFile ', err)
} else {
const message = {
to: req.body.email,
from: '[email protected]',
subject: `Welcome to Donut ${req.body.name.firstName}`,
html: data
}
sendgridMail.send(message).then(
() => {
console.log('sending email')
},
(error) => {
console.log('error in sending email ', error)
if (error.response) {
console.error(error.response.body)
}
}
)
}
})
}
}
Loading

0 comments on commit 119722b

Please sign in to comment.