Browse Source

Implement banned user route, as well as adding if clause on creating thread/post routes

sbkwgh 8 years ago
parent
commit
2483e88858
4 changed files with 66 additions and 0 deletions
  1. 8 0
      models/user.js
  2. 3 0
      routes/post.js
  3. 4 0
      routes/thread.js
  4. 51 0
      routes/user.js

+ 8 - 0
models/user.js

@@ -56,6 +56,14 @@ module.exports = (sequelize, DataTypes) => {
 				}
 			}
 		},
+		canCreatePosts: {
+			type: DataTypes.BOOLEAN,
+			defaultValue: true
+		},
+		canCreateThreads: {
+			type: DataTypes.BOOLEAN,
+			defaultValue: true
+		},
 		admin: {
 			type: DataTypes.BOOLEAN,
 			defaultValue: false

+ 3 - 0
routes/post.js

@@ -111,6 +111,9 @@ router.post('/', async (req, res) => {
 			username: req.session.username
 		}})
 
+		if(!user.canCreatePosts) throw Errors.sequelizeValidation(Sequelize, {
+			error: 'You have been banned from posting'
+		})
 		if(!thread) throw Errors.sequelizeValidation(Sequelize, {
 			error: 'thread does not exist',
 			path: 'id'

+ 4 - 0
routes/thread.js

@@ -57,6 +57,10 @@ router.post('/', async (req, res) => {
 		let user = await User.findOne({ where: {
 			username: req.session.username	
 		}})
+	
+		if(!user.canCreateThreads) throw Errors.sequelizeValidation(Sequelize, {
+			error: 'You have been banned from creating threads'
+		})
 
 		let thread = await Thread.create({
 			name: req.body.name

+ 51 - 0
routes/user.js

@@ -245,4 +245,55 @@ router.delete('/:username', async (req, res) => {
 	}
 })
 
+router.all('*', (req, res, next) => {
+	if(req.session.admin) {
+		next()
+	} else {
+		res.status(400)
+		res.json({
+			errors: [Errors.requestNotAuthorized]
+		})
+	}
+})
+
+router.put('/:username/permissions', async (req, res) => {
+	try {
+		let update = {}
+		if(typeof req.body.canCreatePosts === 'boolean') {
+			update.canCreatePosts = req.body.canCreatePosts
+		}
+		if(typeof req.body.canCreateThreads === 'boolean') {
+			update.canCreateThreads = req.body.canCreateThreads
+		}
+
+		let affectedRows = await User.update(
+			update,
+			{ where: { username: req.params.username } }
+		)
+
+		//If the number of affected rows is 0
+		//i.e. the username does not match any records
+		if(!affectedRows[0]) { 
+			throw Errors.sequelizeValidation(Sequelize, {
+				error: 'user does not exist',
+				value: req.params.username
+			})
+		} else {
+			res.json({ success: true })
+		}
+	} catch (e) {
+		if(e instanceof Sequelize.ValidationError) {
+			res.status(400)
+			res.json(e)
+		} else {
+			console.log(e)
+
+			res.status(500)
+			res.json({
+				errors: [Errors.unknown]
+			})
+		}
+	}
+})
+
 module.exports = router