user.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. let bcrypt = require('bcryptjs')
  2. let express = require('express')
  3. let router = express.Router()
  4. const Errors = require('../lib/errors.js')
  5. let Models = require('../models')
  6. let User = Models.User
  7. let AdminToken = Models.AdminToken
  8. function setUserSession(req, res, username, admin) {
  9. req.session.loggedIn = true
  10. req.session.username = username
  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, 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. queryObj.include = [{
  111. model: Models.Post,
  112. include: Models.Post.includeOptions()
  113. }]
  114. }
  115. let user = await User.findOne(queryObj)
  116. if(!user) throw Errors.accountDoesNotExist
  117. res.json(user.toJSON())
  118. } catch (err) {
  119. if(err === Errors.accountDoesNotExist) {
  120. res.status(400)
  121. res.json({ errors: [err] })
  122. } else {
  123. res.status(500)
  124. res.json({
  125. errors: [Errors.unknown]
  126. })
  127. }
  128. }
  129. })
  130. router.post('/:username/login', async (req, res) => {
  131. let user, bcryptRes, validationErrors = []
  132. try {
  133. //Validations
  134. if(req.body.password === undefined) {
  135. validationErrors.push(Errors.missingParameter('password'))
  136. } else if(typeof req.body.password !== 'string') {
  137. validationErrors.push(Errors.invalidParameterType('password', 'string'))
  138. }
  139. if(validationErrors.length) throw Errors.VALIDATION_ERROR
  140. user = await User.findOne({
  141. where: {
  142. username: req.params.username,
  143. }
  144. })
  145. if(user) {
  146. bcryptRes = await bcrypt.compare(req.body.password, user.hash)
  147. if(bcryptRes) {
  148. setUserSession(req, res, user.username, user.admin)
  149. res.json({
  150. username: user.username,
  151. success: true
  152. })
  153. } else {
  154. res.status(401)
  155. res.json({
  156. errors: [Errors.invalidLoginCredentials]
  157. })
  158. }
  159. } else {
  160. res.status(401)
  161. res.json({
  162. errors: [Errors.invalidLoginCredentials]
  163. })
  164. }
  165. } catch (err) {
  166. if(err === Errors.VALIDATION_ERROR) {
  167. res.status(400)
  168. res.json({
  169. errors: validationErrors
  170. })
  171. } else {
  172. console.log(err)
  173. res.status(500)
  174. res.json({
  175. errors: [Errors.unknown]
  176. })
  177. }
  178. }
  179. })
  180. router.post('/:username/logout', async (req, res) => {
  181. req.session = null
  182. res.clearCookie('username')
  183. res.json({
  184. success: true
  185. })
  186. })
  187. module.exports = router