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.

user.js 7.5KB

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