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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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 emailsSent = {}
  23. const hasher = async (pwd, steak) => {
  24. const hash = await pwd.hash(steak)
  25. const result = await pwd.verify(steak, hash)
  26. let squirtle = null
  27. switch (result) {
  28. case SecurePassword.INVALID_UNRECOGNIZED_HASH:
  29. return console.error(
  30. 'This hash was not made with secure-password. Attempt legacy algorithm',
  31. )
  32. case SecurePassword.INVALID:
  33. return console.log('Invalid password')
  34. case SecurePassword.VALID:
  35. return result
  36. case SecurePassword.VALID_NEEDS_REHASH:
  37. console.log('Yay you made it, wait for us to improve your safety')
  38. try {
  39. squirtle = await pwd.hash(steak)
  40. // console.log('improvedHash', squirtle)
  41. // const saveHash = Auth.insert({user_email: matchingEmails}, ).into('token')
  42. return squirtle
  43. } catch (err) {
  44. console.error(
  45. 'You are authenticated, but we could not improve your safety this time around',
  46. )
  47. }
  48. break
  49. }
  50. }
  51. /** Class for methods used in the User plugin */
  52. module.exports = class UserService extends Schmervice.Service {
  53. /**
  54. * Unsure of what our constructor does
  55. * @param {...any} args
  56. */
  57. constructor(...args) {
  58. super(...args)
  59. const pwd = new SecurePassword()
  60. // TODO: Invalidate this cache somehow after a certain time period has
  61. // passed
  62. this.hashedEmails = {
  63. // NOTE: key is email hash and value is timestamp in ms
  64. // abc123456: '123456689',
  65. }
  66. this.pwd = {
  67. hash: Util.promisify(pwd.hash.bind(pwd)),
  68. verify: Util.promisify(pwd.verify.bind(pwd)),
  69. }
  70. }
  71. /**
  72. * Use knex to find users with id column
  73. * @param {number} id
  74. * @param {*} txn
  75. * @returns
  76. */
  77. async findById(id, txn) {
  78. const { User } = this.server.models()
  79. return await User.query(txn)
  80. .throwIfNotFound()
  81. .first()
  82. .where({ user_id: id })
  83. }
  84. /**
  85. * Use knew to find first user with username
  86. * @param {*} username
  87. * @param {*} txn
  88. * @returns
  89. */
  90. async findByUsername(username, txn) {
  91. const { User } = this.server.models()
  92. return await User.query(txn)
  93. .throwIfNotFound()
  94. .first()
  95. .where({ user_name: username })
  96. }
  97. /**
  98. * Use knew to find first user with useremail
  99. * @param {*} username
  100. * @param {*} txn
  101. * @returns
  102. */
  103. async findByUserEmail(userEmail, txn) {
  104. console.log('userEmail :=>', userEmail)
  105. const { User } = this.server.models()
  106. const user = await User.query(txn)
  107. .throwIfNotFound()
  108. .first()
  109. .where({ user_email: userEmail })
  110. console.log('user :=>', user)
  111. return user
  112. }
  113. /**
  114. * Signup function
  115. * @param {*} param0
  116. * @param {*} txn
  117. * @returns
  118. */
  119. async signup({ password, userInfo, created_at }, txn) {
  120. const { User, Auth } = this.server.models()
  121. const matchingEmails = await User.query().where(
  122. 'user_email',
  123. userInfo.user_email,
  124. )
  125. if (matchingEmails.length > 0) {
  126. throw `User ${userInfo.user_email} already exists: Cannot create a user without a unique email`
  127. }
  128. // Insert User Info to User table
  129. const insertUser = await User.query().insert(userInfo)
  130. // insert a row with blank password to be updated by changePassword()
  131. await Auth.query().insert({
  132. user_email: insertUser.user_email,
  133. created_at: created_at,
  134. token: null,
  135. })
  136. // update null token with hashed password
  137. await this.changePassword(insertUser.user_email, password, txn)
  138. return {
  139. user_id: insertUser.id,
  140. user_name: insertUser.user_name,
  141. user_email: insertUser.user_email,
  142. is_poster: insertUser.is_poster,
  143. is_admin: insertUser.is_admin,
  144. is_verified: insertUser.is_verified,
  145. }
  146. }
  147. /**
  148. * Updates user's info
  149. * @param {number} id
  150. * @param {*} param1
  151. * @param {*} txn
  152. * @returns
  153. */
  154. async update(id, { password, ...userInfo }, txn) {
  155. const { User } = this.server.models()
  156. if (Object.keys(userInfo).length > 0) {
  157. await User.query(txn)
  158. .throwIfNotFound()
  159. .where({ id })
  160. .patch(userInfo)
  161. }
  162. if (password) {
  163. await this.changePassword(id, password, txn)
  164. }
  165. return id
  166. }
  167. /**
  168. * Self explanatory
  169. * @param {*} param0
  170. * @param {*} txn
  171. * @returns
  172. */
  173. async login({ email, password }, txn) {
  174. const { User, Auth } = this.server.models()
  175. const user = await Auth.query(txn)
  176. .throwIfNotFound()
  177. .first()
  178. .where({ user_email: email })
  179. const bufferPepper = Buffer.from(process.env.PEPPER + password)
  180. /** Uncomment to run password check using SecurePassword */
  181. const passwordCheck = await this.pwd.verify(bufferPepper, user.token)
  182. if (passwordCheck === SecurePassword.VALID_NEEDS_REHASH) {
  183. await this.changePassword(user.user_email, password, txn)
  184. } else if (passwordCheck !== SecurePassword.VALID) {
  185. throw User.createNotFoundError()
  186. }
  187. return user
  188. }
  189. /**
  190. * Create a token to be sent in request headers
  191. * @param {User} user
  192. * @returns {Token}
  193. */
  194. createToken(user) {
  195. const key = this.server.registrations['main-app-plugin'].options.jwtKey
  196. const token = Jwt.token.generate(
  197. {
  198. aud: 'urn:audience:test',
  199. iss: 'urn:issuer:test',
  200. email: user.email,
  201. name: user.name,
  202. seeking: user.seeking,
  203. // profile_id: user.profile_id,
  204. },
  205. {
  206. key: key,
  207. algorithm: 'HS256',
  208. },
  209. {
  210. // ttlSec: 4 * 60 * 60, // 7 days
  211. // ttlSec: 60 * 3, // 3 minutes
  212. ttlSec: user.expiration,
  213. },
  214. )
  215. return token
  216. }
  217. /**
  218. * Validates whether a token has expired or not
  219. * @param {User} user
  220. * @returns {Token}
  221. */
  222. validateToken(token) {
  223. const key = this.server.registrations['main-app-plugin'].options.jwtKey
  224. const decodedToken = Jwt.token.decode(token)
  225. // NOTE: reveals email...perhaps unhashed email belongs here instead...
  226. try {
  227. Jwt.token.verify(decodedToken, key)
  228. return { isValid: true, payload: decodedToken.decoded.payload }
  229. } catch (err) {
  230. return { isValid: false, error: err.message }
  231. }
  232. }
  233. /**
  234. * Use knex to try to change password entry
  235. * @param {number} id
  236. * @param {string} password
  237. * @param {*} txn
  238. * @returns {number}
  239. */
  240. async changePassword(email, password, txn) {
  241. const { Auth } = this.server.models()
  242. const hashed = await this.pwd.hash(
  243. Buffer.from(process.env.PEPPER + password),
  244. )
  245. await Auth.query(txn)
  246. .throwIfNotFound()
  247. .where({ user_email: email })
  248. .patch({
  249. // user_email: email,
  250. token: hashed,
  251. })
  252. return email
  253. }
  254. async getPassword(email, txn) {
  255. const { Auth } = this.server.models()
  256. const passwordRow = await Auth.query(txn)
  257. .where('user_email', email)
  258. .first()
  259. return passwordRow ? passwordRow.token : null
  260. }
  261. async checkEmailCache(userEmail) {
  262. const hashedEmail = await hashEmail(userEmail)
  263. const now = Date.now()
  264. const expiration = this.hashedEmails[hashedEmail]
  265. console.log('this.hashedEmails :=>', this.hashedEmails)
  266. const emailIsInCache = Object.keys(this.hashedEmails).includes(
  267. hashedEmail,
  268. )
  269. const emailIsExpired = now > expiration ? true : false
  270. console.log('emailIsInCache :=>', emailIsInCache)
  271. console.log('emailIsExpired :=>', emailIsExpired)
  272. if (emailIsInCache && !emailIsExpired) {
  273. return true
  274. } else {
  275. // try {
  276. // delete this.hashedEmails[hashedEmail]
  277. // } catch (err) {
  278. // console.error('ERROR :=>', err)
  279. // }
  280. return false
  281. }
  282. }
  283. /**
  284. * Sends a Transactional Email via Brevo
  285. * @ returns {Object}
  286. */
  287. async emailSent(userEmail) {
  288. const hashedEmail = await hashEmail(userEmail)
  289. if (Object.keys(this.hashedEmails).includes(hashedEmail)) {
  290. return new Error('email address already in cache!!')
  291. }
  292. // Set expiration time for five minutes from now
  293. const duration = 1000 * 60 * 5
  294. this.hashedEmails[hashedEmail] = Date.now() + duration
  295. const sendSmtpEmail = {
  296. to: [
  297. {
  298. email: userEmail,
  299. },
  300. ],
  301. templateId: 1,
  302. params: {
  303. // TODO: Change this in production...
  304. link: `localhost:3000/verify/${hashedEmail}`,
  305. },
  306. }
  307. await apiInstance.sendTransacEmail(sendSmtpEmail).then(
  308. data => {
  309. return {
  310. wasSuccessfull: true,
  311. data: data,
  312. }
  313. },
  314. error => {
  315. return {
  316. wasSuccessfull: false,
  317. error: error,
  318. }
  319. },
  320. )
  321. }
  322. }