選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

user.js 6.4KB

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