user.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. let bcrypt = require('bcryptjs')
  2. let express = require('express')
  3. let router = express.Router()
  4. const Errors = require('../lib/errors.js')
  5. let { User, Post, AdminToken, Thread, Category } = require('../models')
  6. let pagination = require('../lib/pagination.js')
  7. function setUserSession(req, res, username, admin) {
  8. req.session.loggedIn = true
  9. req.session.username = username
  10. res.cookie('username', username)
  11. if(admin) req.session.admin = true
  12. }
  13. router.post('/', async (req, res) => {
  14. let user, adminUser, hash, token
  15. let validationErrors = []
  16. let userParams = {}
  17. try {
  18. //Validations
  19. if(req.body.username === undefined) {
  20. validationErrors.push(Errors.missingParameter('username'))
  21. } else {
  22. if(typeof req.body.username !== 'string') {
  23. validationErrors.push(Errors.invalidParameterType('username', 'string'))
  24. } if(req.body.username.length < 6) {
  25. validationErrors.push(Errors.parameterLengthTooSmall('username', 6))
  26. } if(req.body.username.length > 50) {
  27. validationErrors.push(Errors.parameterLengthTooLarge('username', 50))
  28. }
  29. }
  30. if(req.body.password === undefined) {
  31. validationErrors.push(Errors.missingParameter('password'))
  32. } else {
  33. if(typeof req.body.password !== 'string') {
  34. validationErrors.push(Errors.invalidParameterType('password', 'string'))
  35. } if(req.body.password.length < 6) {
  36. validationErrors.push(Errors.parameterLengthTooSmall('password', 6))
  37. } if(req.body.password.length > 100) {
  38. validationErrors.push(Errors.parameterLengthTooLarge('password', 100))
  39. }
  40. }
  41. if(req.body.token !== undefined && typeof req.body.token !== 'string') {
  42. validationErrors.push(Errors.invalidParameterType('token', 'string'))
  43. }
  44. if(req.body.admin !== undefined && typeof req.body.admin !== 'boolean') {
  45. validationErrors.push(Errors.invalidParameterType('admin', 'boolean'))
  46. }
  47. if(validationErrors.length) throw Errors.VALIDATION_ERROR
  48. if(req.body.admin && !req.body.token) {
  49. adminUser = await User.findOne({ where: {
  50. admin: true
  51. }})
  52. if(adminUser) {
  53. validationErrors.push(Errors.missingParameter('token'))
  54. throw Errors.VALIDATION_ERROR
  55. } else {
  56. userParams.admin = true
  57. }
  58. } else if(req.body.admin && req.body.token) {
  59. token = await AdminToken.findOne({ where: {
  60. token: req.body.token
  61. }})
  62. if(token && token.isValid()) {
  63. userParams.admin = true
  64. } else {
  65. throw Errors.invalidToken
  66. }
  67. }
  68. hash = await bcrypt.hash(req.body.password, 12)
  69. userParams.username = req.body.username
  70. userParams.hash = hash
  71. user = await User.create(userParams)
  72. if(req.body.token) {
  73. await token.destroy()
  74. }
  75. setUserSession(req, res, user.username, userParams.admin)
  76. res.json(user.toJSON())
  77. } catch (err) {
  78. if(err === Errors.VALIDATION_ERROR) {
  79. res.status(400)
  80. res.json({
  81. errors: validationErrors
  82. })
  83. } else if(err.name === 'SequelizeUniqueConstraintError') {
  84. res.status(400)
  85. res.json({
  86. errors: [Errors.accountAlreadyCreated]
  87. })
  88. } else if (err = Errors.invalidToken) {
  89. res.status(401)
  90. res.json({
  91. errors: [Errors.invalidToken]
  92. })
  93. } else {
  94. console.log(e)
  95. res.status(500)
  96. res.json({
  97. errors: [Errors.unknown]
  98. })
  99. }
  100. }
  101. })
  102. router.get('/:username', async (req, res) => {
  103. try {
  104. let queryObj = {
  105. attributes: { exclude: ['hash', 'id'] },
  106. where: { username: req.params.username }
  107. }
  108. if(req.query.posts) {
  109. let { from, limit } = pagination.getPaginationProps(req.query, true)
  110. let postInclude = {
  111. model: Post,
  112. include: Post.includeOptions(),
  113. limit,
  114. order: [['id', 'DESC']]
  115. }
  116. if(from !== null) {
  117. postInclude.where = { id: { $lte: from } }
  118. }
  119. queryObj.include = [postInclude]
  120. let user = await User.findOne(queryObj)
  121. if(!user) throw Errors.accountDoesNotExist
  122. let resUser = user.toJSON()
  123. resUser.meta = {}
  124. let nextId = await pagination.getNextIdDesc(Post, { userId: user.id }, resUser.Posts)
  125. if(nextId === null) {
  126. resUser.meta.nextURL = null
  127. resUser.meta.nextPostsCount = 0
  128. } else {
  129. resUser.meta.nextURL =
  130. `/api/v1/user/${user.username}?posts=true&limit=${limit}&from=${nextId - 1}`
  131. resUser.meta.nextPostsCount = await pagination.getNextCount(
  132. Post, resUser.Posts, limit,
  133. { UserId: user.id },
  134. true
  135. )
  136. }
  137. res.json(resUser)
  138. } else if(req.query.threads) {
  139. let queryString = ''
  140. Object.keys(req.query).forEach(query => {
  141. queryString += `&${query}=${req.query[query]}`
  142. })
  143. res.redirect('/api/v1/category/ALL?username=' + req.params.username + queryString)
  144. } else {
  145. let user = await User.findOne(queryObj)
  146. if(!user) throw Errors.accountDoesNotExist
  147. res.json(user.toJSON())
  148. }
  149. } catch (err) {
  150. if(err === Errors.accountDoesNotExist) {
  151. res.status(400)
  152. res.json({ errors: [err] })
  153. } else {
  154. console.log(err)
  155. res.status(500)
  156. res.json({
  157. errors: [Errors.unknown]
  158. })
  159. }
  160. }
  161. })
  162. router.post('/:username/login', async (req, res) => {
  163. let user, bcryptRes, validationErrors = []
  164. try {
  165. //Validations
  166. if(req.body.password === undefined) {
  167. validationErrors.push(Errors.missingParameter('password'))
  168. } else if(typeof req.body.password !== 'string') {
  169. validationErrors.push(Errors.invalidParameterType('password', 'string'))
  170. }
  171. if(validationErrors.length) throw Errors.VALIDATION_ERROR
  172. user = await User.findOne({
  173. where: {
  174. username: req.params.username,
  175. }
  176. })
  177. if(user) {
  178. bcryptRes = await bcrypt.compare(req.body.password, user.hash)
  179. if(bcryptRes) {
  180. setUserSession(req, res, user.username, user.admin)
  181. res.json({
  182. username: user.username,
  183. success: true
  184. })
  185. } else {
  186. res.status(401)
  187. res.json({
  188. errors: [Errors.invalidLoginCredentials]
  189. })
  190. }
  191. } else {
  192. res.status(401)
  193. res.json({
  194. errors: [Errors.invalidLoginCredentials]
  195. })
  196. }
  197. } catch (err) {
  198. if(err === Errors.VALIDATION_ERROR) {
  199. res.status(400)
  200. res.json({
  201. errors: validationErrors
  202. })
  203. } else {
  204. console.log(err)
  205. res.status(500)
  206. res.json({
  207. errors: [Errors.unknown]
  208. })
  209. }
  210. }
  211. })
  212. router.post('/:username/logout', async (req, res) => {
  213. req.session = null
  214. res.clearCookie('username')
  215. res.json({
  216. success: true
  217. })
  218. })
  219. router.all('*', (req, res, next) => {
  220. if(req.session.username) {
  221. next()
  222. } else {
  223. res.status(401)
  224. res.json({
  225. errors: [Errors.requestNotAuthorized]
  226. })
  227. }
  228. })
  229. router.put('/:username', async (req, res) => {
  230. let validationErrors = []
  231. try {
  232. if(req.session.username !== req.params.username) {
  233. validationErrors.push(Errors.requestNotAuthorized)
  234. throw validationErrors
  235. }
  236. if(req.body.description !== undefined) {
  237. if(typeof req.body.description !== 'string') {
  238. validationErrors.push(Errors.invalidParameterType('description', 'string'))
  239. } else if(req.body.description.length > 1024) {
  240. validationErrors.push(Errors.parameterLengthTooLarge('description', 1024))
  241. }
  242. if(validationErrors.length) throw validationErrors
  243. let user = await User.update({ description: req.body.description }, { where: {
  244. username: req.session.username
  245. }})
  246. res.json({ success: true })
  247. } else if(req.body.newPassword !== undefined) {
  248. if(req.body.currentPassword === undefined) {
  249. validationErrors.push(Errors.missingParameter('current password'))
  250. } if(typeof req.body.currentPassword !== 'string') {
  251. validationErrors.push(Errors.invalidParameterType('currentPassword', 'string'))
  252. } else if(req.body.currentPassword.length < 8) {
  253. validationErrors.push(Errors.parameterLengthTooSmall('current password', 7))
  254. }
  255. if(typeof req.body.newPassword !== 'string') {
  256. validationErrors.push(Errors.invalidParameterType('newPassword', 'string'))
  257. } else {
  258. if(req.body.newPassword.length > 1024) {
  259. validationErrors.push(Errors.parameterLengthTooLarge('new password', 1024))
  260. } if(req.body.newPassword.length < 8) {
  261. validationErrors.push(Errors.parameterLengthTooSmall('new password', 7))
  262. } if(req.body.newPassword === req.body.currentPassword) {
  263. validationErrors.push(Errors.passwordSame)
  264. }
  265. }
  266. if(validationErrors.length) throw validationErrors
  267. let user = await User.findOne({where: {
  268. username: req.session.username
  269. }})
  270. let bcryptRes = await bcrypt.compare(req.body.currentPassword, user.hash)
  271. if(bcryptRes) {
  272. let newHash = await bcrypt.hash(req.body.newPassword, 12)
  273. let user = await User.update({ hash: newHash }, { where: {
  274. username: req.session.username
  275. }})
  276. res.json({ success: true })
  277. } else {
  278. validationErrors.push(Errors.invalidLoginCredentials)
  279. throw validationErrors
  280. }
  281. }
  282. } catch (e) {
  283. if(validationErrors.length) {
  284. res.status(400)
  285. res.json({ errors: validationErrors })
  286. } else {
  287. console.log(e)
  288. res.status(500)
  289. res.json({errors: Errors.unknown })
  290. }
  291. }
  292. })
  293. module.exports = router