Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. // const todayTest = new Date.now()
  91. console.log("password passed to .signup()", password)
  92. const steak = process.env.PEPPER+password
  93. console.log("steak", steak)
  94. console.log("user_email", userInfo.user_email)
  95. const { email } = await Auth.query(txn).insert({
  96. user_email: userInfo.user_email,
  97. created_at: new Date.now(),
  98. })
  99. await this.changePassword(email, steak, txn)
  100. return userInfo.user_email
  101. console.log("signup return finished")
  102. // Library: Secure-Password
  103. // console.log('data type of create_at', )
  104. // add pepper to pw and convert to buffer to prep for hash bytes
  105. // const steak = Buffer.from(password + pepper, 'utf-8')
  106. // console.log("steak", steak)
  107. // send peppered pw to (argon algorithm) library for salted hash
  108. // hashed is actually for logging in
  109. // const hashed = await hasher(this.pwd, steak)
  110. // console.log("hashed", hashed)
  111. // console.log ("user_email", userInfo.user_email)
  112. // const newAuth = await Auth.query(txn).insert({
  113. // user_email: userInfo.user_email,
  114. // created_at: new Date.now(),
  115. // token: steak,
  116. // })
  117. // console.log("newAuth", newAuth)
  118. // return newAuth
  119. // const user = await User.query(txn).insert(userInfo)
  120. // user.user_id = user.id
  121. // delete user.id
  122. // await this.changePassword(id, password, txn)
  123. // return user
  124. }
  125. /**
  126. * Updates user's info
  127. * @param {number} id
  128. * @param {*} param1
  129. * @param {*} txn
  130. * @returns
  131. */
  132. async update(id, { password, ...userInfo }, txn) {
  133. const { User } = this.server.models()
  134. if (Object.keys(userInfo).length > 0) {
  135. await User.query(txn)
  136. .throwIfNotFound()
  137. .where({ id })
  138. .patch(userInfo)
  139. }
  140. if (password) {
  141. await this.changePassword(id, password, txn)
  142. }
  143. return id
  144. }
  145. /**
  146. * Self explanatory
  147. * @param {*} param0
  148. * @param {*} txn
  149. * @returns
  150. */
  151. async login({ email, password }, txn) {
  152. const { User } = this.server.models()
  153. const user = await User.query(txn)
  154. .throwIfNotFound()
  155. .first()
  156. .where({ user_email: email })
  157. /** Uncomment to run password check using SecurePassword */
  158. // const passwordCheck = await this.pwd.verify(Buffer.from(password), user.password)
  159. // if (passwordCheck === SecurePassword.VALID_NEEDS_REHASH) {
  160. // await this.changePassword(user.id, password, txn)
  161. // }
  162. // else if (passwordCheck !== SecurePassword.VALID) {
  163. // throw User.createNotFoundError()
  164. // }
  165. return user
  166. }
  167. /**
  168. * Create a token to be sent in request headers
  169. * @param {User} user
  170. * @returns {Token}
  171. */
  172. createToken(user) {
  173. const key = this.server.registrations['main-app-plugin'].options.jwtKey
  174. return Jwt.token.generate(
  175. {
  176. aud: 'urn:audience:test',
  177. iss: 'urn:issuer:test',
  178. email: user.user_email,
  179. },
  180. {
  181. key: key,
  182. algorithm: 'HS256',
  183. },
  184. {
  185. ttlSec: 4 * 60 * 60, // 7 days
  186. },
  187. )
  188. }
  189. /**
  190. * Use knex to try to change password entry
  191. * @param {number} id
  192. * @param {string} password
  193. * @param {*} txn
  194. * @returns {number}
  195. */
  196. async changePassword(email, password, txn) {
  197. const { User, Auth } = this.server.models()
  198. await Auth.query(txn)
  199. .throwIfNotFound()
  200. .where({ email })
  201. .patch({
  202. // user_email: email,
  203. token: await this.pwd.hash(Buffer.from(password)),
  204. })
  205. console.log("changed pw return", email)
  206. console.log("token created in changePassword", this.pwd.hash(Buffer.from(password)))
  207. return email
  208. // await User.query(txn)
  209. // .throwIfNotFound()
  210. // .where({ id })
  211. // .patch({
  212. // password: await this.pwd.hash(Buffer.from(password)),
  213. // })
  214. // return id
  215. }
  216. async getPassword(email, txn) {
  217. const { Auth } = this.server.models()
  218. const passwordRow = await Auth.query(txn)
  219. .where('user_email', email)
  220. .first()
  221. return passwordRow ? passwordRow.token : null
  222. }
  223. }