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.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. 'use strict'
  2. require('dotenv').config()
  3. const crypto = require('crypto')
  4. const Util = require('util')
  5. const Jwt = require('@hapi/jwt')
  6. const Schmervice = require('@hapipal/schmervice')
  7. const SecurePassword = require('secure-password')
  8. // Configuration for Brevo
  9. const SibApiV3Sdk = require('sib-api-v3-sdk')
  10. const defaultClient = SibApiV3Sdk.ApiClient.instance
  11. const apiKey = defaultClient.authentications['api-key']
  12. apiKey.apiKey = process.env.BREVO_KEY
  13. const apiInstance = new SibApiV3Sdk.TransactionalEmailsApi()
  14. const hashEmail = async email => {
  15. try {
  16. return crypto.createHmac('sha256', '').update(email).digest('hex')
  17. } catch (err) {
  18. console.error('ERROR :=>', err)
  19. return undefined
  20. }
  21. }
  22. const hasher = async (pwd, steak) => {
  23. const hash = await pwd.hash(steak)
  24. const result = await pwd.verify(steak, hash)
  25. let squirtle = null
  26. switch (result) {
  27. case SecurePassword.INVALID_UNRECOGNIZED_HASH:
  28. return console.error(
  29. 'This hash was not made with secure-password. Attempt legacy algorithm',
  30. )
  31. case SecurePassword.INVALID:
  32. return console.log('Invalid password')
  33. case SecurePassword.VALID:
  34. return result
  35. case SecurePassword.VALID_NEEDS_REHASH:
  36. console.log('Yay you made it, wait for us to improve your safety')
  37. try {
  38. squirtle = await pwd.hash(steak)
  39. // console.log('improvedHash', squirtle)
  40. // const saveHash = Auth.insert({user_email: matchingEmails}, ).into('token')
  41. return squirtle
  42. } catch (err) {
  43. console.error(
  44. 'You are authenticated, but we could not improve your safety this time around',
  45. )
  46. }
  47. break
  48. }
  49. }
  50. /** Class for methods used in the User plugin */
  51. module.exports = class UserService extends Schmervice.Service {
  52. /**
  53. * Unsure of what our constructor does
  54. * @param {...any} args
  55. */
  56. constructor(...args) {
  57. super(...args)
  58. const pwd = new SecurePassword()
  59. this.hashedEmail = ''
  60. this.pwd = {
  61. hash: Util.promisify(pwd.hash.bind(pwd)),
  62. verify: Util.promisify(pwd.verify.bind(pwd)),
  63. }
  64. }
  65. /**
  66. * Use knex to find users with id column
  67. * @param {number} id
  68. * @param {*} txn
  69. * @returns
  70. */
  71. async findById(id, txn) {
  72. const { User } = this.server.models()
  73. return await User.query(txn)
  74. .throwIfNotFound()
  75. .first()
  76. .where({ user_id: id })
  77. }
  78. /**
  79. * Use knew to find first user with username
  80. * @param {*} username
  81. * @param {*} txn
  82. * @returns
  83. */
  84. async findByUsername(username, txn) {
  85. const { User } = this.server.models()
  86. return await User.query(txn)
  87. .throwIfNotFound()
  88. .first()
  89. .where({ user_name: username })
  90. }
  91. /**
  92. * Signup function
  93. * @param {*} param0
  94. * @param {*} txn
  95. * @returns
  96. */
  97. async signup({ password, userInfo, created_at }, txn) {
  98. const { User, Auth } = this.server.models()
  99. const matchingEmails = await User.query().where(
  100. 'user_email',
  101. userInfo.user_email,
  102. )
  103. if (matchingEmails.length > 0) {
  104. throw `User ${userInfo.user_email} already exists: Cannot create a user without a unique email`
  105. }
  106. // Insert User Info to User table
  107. const insertUser = await User.query().insert(userInfo)
  108. // insert a row with blank password to be updated by changePassword()
  109. await Auth.query().insert({
  110. user_email: insertUser.user_email,
  111. created_at: created_at,
  112. token: null,
  113. })
  114. // update null token with hashed password
  115. await this.changePassword(insertUser.user_email, password, txn)
  116. return {
  117. user_id: insertUser.id,
  118. user_name: insertUser.user_name,
  119. user_email: insertUser.user_email,
  120. is_poster: insertUser.is_poster,
  121. is_admin: insertUser.is_admin,
  122. is_verified: insertUser.is_verified,
  123. }
  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, Auth } = this.server.models()
  153. const user = await Auth.query(txn)
  154. .throwIfNotFound()
  155. .first()
  156. .where({ user_email: email })
  157. const bufferPepper = Buffer.from(process.env.PEPPER + password)
  158. /** Uncomment to run password check using SecurePassword */
  159. const passwordCheck = await this.pwd.verify(bufferPepper, user.token)
  160. if (passwordCheck === SecurePassword.VALID_NEEDS_REHASH) {
  161. await this.changePassword(user.user_email, password, txn)
  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 { Auth } = this.server.models()
  198. const hashed = await this.pwd.hash(
  199. Buffer.from(process.env.PEPPER + password),
  200. )
  201. await Auth.query(txn)
  202. .throwIfNotFound()
  203. .where({ user_email: email })
  204. .patch({
  205. // user_email: email,
  206. token: hashed,
  207. })
  208. return email
  209. }
  210. async getPassword(email, txn) {
  211. const { Auth } = this.server.models()
  212. const passwordRow = await Auth.query(txn)
  213. .where('user_email', email)
  214. .first()
  215. return passwordRow ? passwordRow.token : null
  216. }
  217. /**
  218. * Sends a Transactional Email via Brevo
  219. * @ returns {Object}
  220. */
  221. async emailSent(userEmail) {
  222. const sendSmtpEmail = {
  223. to: [
  224. {
  225. email: userEmail,
  226. },
  227. ],
  228. templateId: 1,
  229. params: {
  230. // TODO: Change this in production...
  231. link: `localhost:3000/verify/${await hashEmail(userEmail)}`,
  232. },
  233. }
  234. await apiInstance.sendTransacEmail(sendSmtpEmail).then(
  235. data => {
  236. return {
  237. wasSuccessfull: true,
  238. data: data,
  239. }
  240. },
  241. error => {
  242. return {
  243. wasSuccessfull: false,
  244. error: error,
  245. }
  246. },
  247. )
  248. this.hashedEmail = hashEmail(userEmail)
  249. }
  250. }