You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. 'use strict'
  2. require('dotenv').config()
  3. const Util = require('util')
  4. const Jwt = require('@hapi/jwt')
  5. const Schmervice = require('@hapipal/schmervice')
  6. const SecurePassword = require('secure-password')
  7. /** Class for methods used in the User plugin */
  8. module.exports = class UserService extends Schmervice.Service {
  9. /**
  10. * Unsure of what our constructor does
  11. * @param {...any} args
  12. */
  13. constructor(...args) {
  14. super(...args)
  15. const pwd = new SecurePassword()
  16. this.pwd = {
  17. hash: Util.promisify(pwd.hash.bind(pwd)),
  18. verify: Util.promisify(pwd.verify.bind(pwd)),
  19. }
  20. }
  21. /**
  22. * Use knex to find users with id column
  23. * @param {number} id
  24. * @param {*} txn
  25. * @returns
  26. */
  27. async findById(id, txn) {
  28. const { User } = this.server.models()
  29. return await User.query(txn)
  30. .throwIfNotFound()
  31. .first()
  32. .where({ user_id: id })
  33. }
  34. /**
  35. * Use knew to find first user with username
  36. * @param {*} username
  37. * @param {*} txn
  38. * @returns
  39. */
  40. async findByUsername(username, txn) {
  41. const { User } = this.server.models()
  42. return await User.query(txn)
  43. .throwIfNotFound()
  44. .first()
  45. .where({ user_name: username })
  46. }
  47. /**
  48. * Signup function
  49. * @param {*} param0
  50. * @param {*} txn
  51. * @returns
  52. */
  53. async signup({ password, userInfo }, txn) {
  54. const { User } = this.server.models()
  55. const matchingEmails = await User.query().where(
  56. 'user_email',
  57. userInfo.user_email,
  58. )
  59. if (matchingEmails.length > 0) {
  60. throw `User ${userInfo.user_email} already exists: Cannot create a user without a unique email`
  61. }
  62. // Library: Secure-Password
  63. const pepper = process.env.PEPPER
  64. // add pepper to pw
  65. const steak = password.trim() + pepper
  66. console.log(steak)
  67. const { Auth } = this.server.models()
  68. // send peppered pw to (argon algorithm) library for salted hash
  69. pwd.hash(steak, function (err, hash) {
  70. if (err) throw err
  71. // Save hash somewhere
  72. pwd.verify(steak, hash, function (err, result) {
  73. if (err) throw err
  74. switch (result) {
  75. case securePassword.INVALID_UNRECOGNIZED_HASH:
  76. return console.error('This hash was not made with secure-password. Attempt legacy algorithm')
  77. case securePassword.INVALID:
  78. return console.log('Invalid password')
  79. case securePassword.VALID:
  80. return console.log('Authenticated')
  81. case securePassword.VALID_NEEDS_REHASH:
  82. console.log('Yay you made it, wait for us to improve your safety')
  83. pwd.hash(userPassword, function (err, improvedHash) {
  84. if (err) console.error('You are authenticated, but we could not improve your safety this time around')
  85. // Save improvedHash somewhere
  86. // insert hash and salt into authentication table (with user, see 73)
  87. const saveHash = Auth.insert({ user_email: matchingEmails})
  88. .into('token')
  89. return saveHash
  90. })
  91. break
  92. }
  93. })
  94. })
  95. // const user = await User.query(txn).insert(userInfo)
  96. // user.user_id = user.id
  97. // delete user.id
  98. // await this.changePassword(id, password, txn)
  99. // return user
  100. }
  101. /**
  102. * Updates user's info
  103. * @param {number} id
  104. * @param {*} param1
  105. * @param {*} txn
  106. * @returns
  107. */
  108. async update(id, { password, ...userInfo }, txn) {
  109. const { User } = this.server.models()
  110. if (Object.keys(userInfo).length > 0) {
  111. await User.query(txn)
  112. .throwIfNotFound()
  113. .where({ id })
  114. .patch(userInfo)
  115. }
  116. if (password) {
  117. await this.changePassword(id, password, txn)
  118. }
  119. return id
  120. }
  121. /**
  122. * Self explanatory
  123. * @param {*} param0
  124. * @param {*} txn
  125. * @returns
  126. */
  127. async login({ email, password }, txn) {
  128. const { User } = this.server.models()
  129. const user = await User.query(txn)
  130. .throwIfNotFound()
  131. .first()
  132. .where({ user_email: email })
  133. /** Uncomment to run password check using SecurePassword */
  134. // const passwordCheck = await this.pwd.verify(Buffer.from(password), user.password)
  135. // if (passwordCheck === SecurePassword.VALID_NEEDS_REHASH) {
  136. // await this.changePassword(user.id, password, txn)
  137. // }
  138. // else if (passwordCheck !== SecurePassword.VALID) {
  139. // throw User.createNotFoundError()
  140. // }
  141. return user
  142. }
  143. /**
  144. * Create a token to be sent in request headers
  145. * @param {User} user
  146. * @returns {Token}
  147. */
  148. createToken(user) {
  149. const key = this.server.registrations['main-app-plugin'].options.jwtKey
  150. return Jwt.token.generate(
  151. {
  152. aud: 'urn:audience:test',
  153. iss: 'urn:issuer:test',
  154. email: user.user_email,
  155. },
  156. {
  157. key: key,
  158. algorithm: 'HS256',
  159. },
  160. {
  161. ttlSec: 4 * 60 * 60, // 7 days
  162. },
  163. )
  164. }
  165. /**
  166. * Use knex to try to change password entry
  167. * @param {number} id
  168. * @param {string} password
  169. * @param {*} txn
  170. * @returns {number}
  171. */
  172. async changePassword(id, password, txn) {
  173. const { User } = this.server.models()
  174. return 'done'
  175. // rework with Auth model
  176. // await User.query(txn)
  177. // .throwIfNotFound()
  178. // .where({ id })
  179. // .patch({
  180. // password: await this.pwd.hash(Buffer.from(password)),
  181. // })
  182. // return id
  183. }
  184. async getPassword(email, txn) {
  185. const { Auth } = this.server.models()
  186. const passwordRow = await Auth.query(txn)
  187. .where('user_email', email)
  188. .first()
  189. return passwordRow ? passwordRow.token : null
  190. }
  191. }