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 6.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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, created_at }, 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. // Insert User Info to User table
  91. const insertUser = await User.query().insert(userInfo)
  92. // insert a row with blank password to be updated by changePassword()
  93. await Auth.query().insert({
  94. user_email: insertUser.user_email,
  95. created_at: created_at,
  96. token: null,
  97. })
  98. // update null token with hashed password
  99. await this.changePassword(insertUser.user_email, password, txn)
  100. return {
  101. user_id: insertUser.id,
  102. user_name: insertUser.user_name,
  103. user_email: insertUser.user_email,
  104. is_poster: insertUser.is_poster,
  105. is_admin: insertUser.is_admin,
  106. is_verified: insertUser.is_verified,
  107. }
  108. }
  109. /**
  110. * Updates user's info
  111. * @param {number} id
  112. * @param {*} param1
  113. * @param {*} txn
  114. * @returns
  115. */
  116. async update(id, { password, ...userInfo }, txn) {
  117. const { User } = this.server.models()
  118. if (Object.keys(userInfo).length > 0) {
  119. await User.query(txn)
  120. .throwIfNotFound()
  121. .where({ id })
  122. .patch(userInfo)
  123. }
  124. if (password) {
  125. await this.changePassword(id, password, txn)
  126. }
  127. return id
  128. }
  129. /**
  130. * Self explanatory
  131. * @param {*} param0
  132. * @param {*} txn
  133. * @returns
  134. */
  135. async login({ email, password }, txn) {
  136. const { User, Auth } = this.server.models()
  137. const user = await Auth.query(txn)
  138. .throwIfNotFound()
  139. .first()
  140. .where({ user_email: email })
  141. const bufferPepper = Buffer.from(process.env.PEPPER + password)
  142. /** Uncomment to run password check using SecurePassword */
  143. const passwordCheck = await this.pwd.verify(bufferPepper, user.token)
  144. console.log("passwordCheck", passwordCheck)
  145. if (passwordCheck === SecurePassword.VALID_NEEDS_REHASH) {
  146. await this.changePassword(user.user_email, password, txn)
  147. }
  148. else if (passwordCheck !== SecurePassword.VALID) {
  149. throw User.createNotFoundError()
  150. }
  151. return user
  152. }
  153. /**
  154. * Create a token to be sent in request headers
  155. * @param {User} user
  156. * @returns {Token}
  157. */
  158. createToken(user) {
  159. const key = this.server.registrations['main-app-plugin'].options.jwtKey
  160. return Jwt.token.generate(
  161. {
  162. aud: 'urn:audience:test',
  163. iss: 'urn:issuer:test',
  164. email: user.user_email,
  165. },
  166. {
  167. key: key,
  168. algorithm: 'HS256',
  169. },
  170. {
  171. ttlSec: 4 * 60 * 60, // 7 days
  172. },
  173. )
  174. }
  175. /**
  176. * Use knex to try to change password entry
  177. * @param {number} id
  178. * @param {string} password
  179. * @param {*} txn
  180. * @returns {number}
  181. */
  182. async changePassword(email, password, txn) {
  183. const { User, Auth } = this.server.models()
  184. console.log('email passed to changePassword', email)
  185. const hashed = await this.pwd.hash(Buffer.from(process.env.PEPPER + password))
  186. console.log('hashed', hashed)
  187. await Auth.query(txn)
  188. .throwIfNotFound()
  189. .where({ user_email: email })
  190. .patch({
  191. // user_email: email,
  192. token: hashed
  193. })
  194. console.log('changePassword query completed')
  195. return email
  196. // await User.query(txn)
  197. // .throwIfNotFound()
  198. // .where({ id })
  199. // .patch({
  200. // password: await this.pwd.hash(Buffer.from(password)),
  201. // })
  202. // return id
  203. }
  204. async getPassword(email, txn) {
  205. const { Auth } = this.server.models()
  206. const passwordRow = await Auth.query(txn)
  207. .where('user_email', email)
  208. .first()
  209. return passwordRow ? passwordRow.token : null
  210. }
  211. }