user.js 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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 } = require('../models')
  6. function setUserSession(req, res, username, admin) {
  7. req.session.loggedIn = true
  8. req.session.username = username
  9. res.cookie('username', username)
  10. if(admin) req.session.admin = true
  11. }
  12. router.post('/', async (req, res) => {
  13. let user, adminUser, hash, token
  14. let validationErrors = []
  15. let userParams = {}
  16. try {
  17. //Validations
  18. if(req.body.username === undefined) {
  19. validationErrors.push(Errors.missingParameter('username'))
  20. } else {
  21. if(typeof req.body.username !== 'string') {
  22. validationErrors.push(Errors.invalidParameterType('username', 'string'))
  23. } if(req.body.username.length < 6) {
  24. validationErrors.push(Errors.parameterLengthTooSmall('username', 6))
  25. } if(req.body.username.length > 50) {
  26. validationErrors.push(Errors.parameterLengthTooLarge('username', 50))
  27. }
  28. }
  29. if(req.body.password === undefined) {
  30. validationErrors.push(Errors.missingParameter('password'))
  31. } else {
  32. if(typeof req.body.password !== 'string') {
  33. validationErrors.push(Errors.invalidParameterType('password', 'string'))
  34. } if(req.body.password.length < 6) {
  35. validationErrors.push(Errors.parameterLengthTooSmall('password', 6))
  36. } if(req.body.password.length > 100) {
  37. validationErrors.push(Errors.parameterLengthTooLarge('password', 100))
  38. }
  39. }
  40. if(req.body.token !== undefined && typeof req.body.token !== 'string') {
  41. validationErrors.push(Errors.invalidParameterType('token', 'string'))
  42. }
  43. if(req.body.admin !== undefined && typeof req.body.admin !== 'boolean') {
  44. validationErrors.push(Errors.invalidParameterType('admin', 'boolean'))
  45. }
  46. if(validationErrors.length) throw Errors.VALIDATION_ERROR
  47. if(req.body.admin && !req.body.token) {
  48. adminUser = await User.findOne({ where: {
  49. admin: true
  50. }})
  51. if(adminUser) {
  52. validationErrors.push(Errors.missingParameter('token'))
  53. throw Errors.VALIDATION_ERROR
  54. } else {
  55. userParams.admin = true
  56. }
  57. } else if(req.body.admin && req.body.token) {
  58. token = await AdminToken.findOne({ where: {
  59. token: req.body.token
  60. }})
  61. if(token && token.isValid()) {
  62. userParams.admin = true
  63. } else {
  64. throw Errors.invalidToken
  65. }
  66. }
  67. hash = await bcrypt.hash(req.body.password, 12)
  68. userParams.username = req.body.username
  69. userParams.hash = hash
  70. user = await User.create(userParams)
  71. if(req.body.token) {
  72. await token.destroy()
  73. }
  74. setUserSession(req, res, user.username, userParams.admin)
  75. res.json(user.toJSON())
  76. } catch (err) {
  77. if(err === Errors.VALIDATION_ERROR) {
  78. res.status(400)
  79. res.json({
  80. errors: validationErrors
  81. })
  82. } else if(err.name === 'SequelizeUniqueConstraintError') {
  83. res.status(400)
  84. res.json({
  85. errors: [Errors.accountAlreadyCreated]
  86. })
  87. } else if (err = Errors.invalidToken) {
  88. res.status(401)
  89. res.json({
  90. errors: [Errors.invalidToken]
  91. })
  92. } else {
  93. console.log(e)
  94. res.status(500)
  95. res.json({
  96. errors: [Errors.unknown]
  97. })
  98. }
  99. }
  100. })
  101. router.get('/:username', async (req, res) => {
  102. try {
  103. let queryObj = {
  104. attributes: { exclude: ['hash', 'id'] },
  105. where: { username: req.params.username }
  106. }
  107. if(req.query.posts) {
  108. let lastId = 0
  109. let limit = 10
  110. if(+req.query.lastId > 0) lastId = +req.query.lastId
  111. if(+req.query.limit > 0) limit = +req.query.limit
  112. queryObj.include = [{
  113. model: Post,
  114. include: Post.includeOptions()
  115. }]
  116. let user = await User.findOne(queryObj)
  117. if(!user) throw Errors.accountDoesNotExist
  118. let maxId = await Post.max('id', { where: { userId: user.id } })
  119. let resUser = user.toJSON()
  120. let lastPost = user.Posts.slice(-1)[0]
  121. resUser.meta = {}
  122. if(!lastPost || maxId === lastPost.id) {
  123. resUser.meta.nextURL = null
  124. } else {
  125. resUser.meta.nextURL =
  126. `/api/v1/user/${user.id}?posts?=true&limit=${limit}&lastId=${lastPost.id}`
  127. }
  128. res.json(user)
  129. } else {
  130. let user = await User.findOne(queryObj)
  131. if(!user) throw Errors.accountDoesNotExist
  132. res.json(user.toJSON())
  133. }
  134. } catch (err) {
  135. if(err === Errors.accountDoesNotExist) {
  136. res.status(400)
  137. res.json({ errors: [err] })
  138. } else {
  139. console.log(err)
  140. res.status(500)
  141. res.json({
  142. errors: [Errors.unknown]
  143. })
  144. }
  145. }
  146. })
  147. router.post('/:username/login', async (req, res) => {
  148. let user, bcryptRes, validationErrors = []
  149. try {
  150. //Validations
  151. if(req.body.password === undefined) {
  152. validationErrors.push(Errors.missingParameter('password'))
  153. } else if(typeof req.body.password !== 'string') {
  154. validationErrors.push(Errors.invalidParameterType('password', 'string'))
  155. }
  156. if(validationErrors.length) throw Errors.VALIDATION_ERROR
  157. user = await User.findOne({
  158. where: {
  159. username: req.params.username,
  160. }
  161. })
  162. if(user) {
  163. bcryptRes = await bcrypt.compare(req.body.password, user.hash)
  164. if(bcryptRes) {
  165. setUserSession(req, res, user.username, user.admin)
  166. res.json({
  167. username: user.username,
  168. success: true
  169. })
  170. } else {
  171. res.status(401)
  172. res.json({
  173. errors: [Errors.invalidLoginCredentials]
  174. })
  175. }
  176. } else {
  177. res.status(401)
  178. res.json({
  179. errors: [Errors.invalidLoginCredentials]
  180. })
  181. }
  182. } catch (err) {
  183. if(err === Errors.VALIDATION_ERROR) {
  184. res.status(400)
  185. res.json({
  186. errors: validationErrors
  187. })
  188. } else {
  189. console.log(err)
  190. res.status(500)
  191. res.json({
  192. errors: [Errors.unknown]
  193. })
  194. }
  195. }
  196. })
  197. router.post('/:username/logout', async (req, res) => {
  198. req.session = null
  199. res.clearCookie('username')
  200. res.json({
  201. success: true
  202. })
  203. })
  204. module.exports = router