user.js 9.4 KB

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