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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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, created_at }, txn) {
  54. const { User, Auth } = 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. // Insert User Info to User table
  63. const insertUser = await User.query().insert(userInfo)
  64. // insert a row with blank password to be updated by changePassword()
  65. await Auth.query().insert({
  66. user_email: insertUser.user_email,
  67. created_at: created_at,
  68. token: null,
  69. })
  70. // update null token with hashed password
  71. await this.changePassword(insertUser.user_email, password, txn)
  72. return {
  73. user_id: insertUser.id,
  74. user_name: insertUser.user_name,
  75. user_email: insertUser.user_email,
  76. is_poster: insertUser.is_poster,
  77. is_admin: insertUser.is_admin,
  78. is_verified: insertUser.is_verified,
  79. }
  80. }
  81. /**
  82. * Updates user's info
  83. * @param {number} id
  84. * @param {*} param1
  85. * @param {*} txn
  86. * @returns
  87. */
  88. async update(id, { password, ...userInfo }, txn) {
  89. const { User } = this.server.models()
  90. if (Object.keys(userInfo).length > 0) {
  91. await User.query(txn)
  92. .throwIfNotFound()
  93. .where({ id })
  94. .patch(userInfo)
  95. }
  96. if (password) {
  97. await this.changePassword(id, password, txn)
  98. }
  99. return id
  100. }
  101. /**
  102. * Self explanatory
  103. * @param {*} param0
  104. * @param {*} txn
  105. * @returns
  106. */
  107. async login({ email, password }, txn) {
  108. const { User, Auth } = this.server.models()
  109. const user = await Auth.query(txn)
  110. .throwIfNotFound()
  111. .first()
  112. .where({ user_email: email })
  113. const bufferPepper = Buffer.from(process.env.PEPPER + password)
  114. /** Uncomment to run password check using SecurePassword */
  115. const passwordCheck = await this.pwd.verify(bufferPepper, user.token)
  116. if (passwordCheck === SecurePassword.VALID_NEEDS_REHASH) {
  117. await this.changePassword(user.user_email, password, txn)
  118. } else if (passwordCheck !== SecurePassword.VALID) {
  119. throw User.createNotFoundError()
  120. }
  121. return user
  122. }
  123. /**
  124. * Create a token to be sent in request headers
  125. * @param {User} user
  126. * @returns {Token}
  127. */
  128. createToken(user) {
  129. const key = this.server.registrations['main-app-plugin'].options.jwtKey
  130. return Jwt.token.generate(
  131. {
  132. aud: 'urn:audience:test',
  133. iss: 'urn:issuer:test',
  134. email: user.user_email,
  135. },
  136. {
  137. key: key,
  138. algorithm: 'HS256',
  139. },
  140. {
  141. ttlSec: 14400, // 4 hours
  142. },
  143. )
  144. }
  145. /**
  146. * Use knex to try to change password entry
  147. * @param {number} id
  148. * @param {string} password
  149. * @param {*} txn
  150. * @returns {number}
  151. */
  152. async changePassword(email, password, txn) {
  153. const { Auth } = this.server.models()
  154. const hashed = await this.pwd.hash(
  155. Buffer.from(process.env.PEPPER + password),
  156. )
  157. await Auth.query(txn)
  158. .throwIfNotFound()
  159. .where({ user_email: email })
  160. .patch({
  161. // user_email: email,
  162. token: hashed,
  163. })
  164. return email
  165. }
  166. async getPassword(email, txn) {
  167. const { Auth } = this.server.models()
  168. const passwordRow = await Auth.query(txn)
  169. .where('user_email', email)
  170. .first()
  171. return passwordRow ? passwordRow.token : null
  172. }
  173. }