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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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. // TODO: Remove hashedEmails in preference of activeSessions
  63. this.hashedEmails = {
  64. // NOTE: key is email hash and value is timestamp in ms
  65. // abc123456: '123456689',
  66. }
  67. // this.activeSessions = [
  68. // {
  69. // user: {
  70. // useremail: email,
  71. // hashedEmail: hashedEmail,
  72. // username: name,
  73. // },
  74. // expiration: 1203984710234
  75. // },
  76. // token: 'tokenString + expirationDate + salt'
  77. // ]
  78. this.pwd = {
  79. hash: Util.promisify(pwd.hash.bind(pwd)),
  80. verify: Util.promisify(pwd.verify.bind(pwd)),
  81. }
  82. }
  83. /**
  84. * Use knex to find users with id column
  85. * @param {number} id
  86. * @param {*} txn
  87. * @returns
  88. */
  89. async findById(id, txn) {
  90. const { User } = this.server.models()
  91. return await User.query(txn)
  92. .throwIfNotFound()
  93. .first()
  94. .where({ user_id: id })
  95. }
  96. /**
  97. * Use knew to find first user with username
  98. * @param {*} username
  99. * @param {*} txn
  100. * @returns
  101. */
  102. async findByUsername(username, txn) {
  103. const { User } = this.server.models()
  104. return await User.query(txn)
  105. .throwIfNotFound()
  106. .first()
  107. .where({ user_name: username })
  108. }
  109. /**
  110. * Use knew to find first user with useremail
  111. * @param {*} username
  112. * @param {*} txn
  113. * @returns
  114. */
  115. async findByUserEmail(userEmail, txn) {
  116. const { User } = this.server.models()
  117. const user = await User.query(txn)
  118. .throwIfNotFound()
  119. .first()
  120. .where({ user_email: userEmail })
  121. return user
  122. }
  123. /**
  124. * Signup function
  125. * @param {*} param0
  126. * @param {*} txn
  127. * @returns
  128. */
  129. async signup({ password, userInfo, created_at }, txn) {
  130. const { User, Auth } = this.server.models()
  131. const matchingEmails = await User.query().where(
  132. 'user_email',
  133. userInfo.user_email,
  134. )
  135. if (matchingEmails.length > 0) {
  136. throw `User ${userInfo.user_email} already exists: Cannot create a user without a unique email`
  137. }
  138. // Insert User Info to User table
  139. const insertUser = await User.query().insert(userInfo)
  140. // insert a row with blank password to be updated by changePassword()
  141. await Auth.query().insert({
  142. user_email: insertUser.user_email,
  143. created_at: created_at,
  144. token: null,
  145. })
  146. // update null token with hashed password
  147. await this.changePassword(insertUser.user_email, password, txn)
  148. return {
  149. user_id: insertUser.id,
  150. user_name: insertUser.user_name,
  151. user_email: insertUser.user_email,
  152. is_poster: insertUser.is_poster,
  153. is_admin: insertUser.is_admin,
  154. is_verified: insertUser.is_verified,
  155. }
  156. }
  157. /**
  158. * Updates user's info
  159. * @param {number} id
  160. * @param {*} param1
  161. * @param {*} txn
  162. * @returns
  163. */
  164. async update(id, { password, ...userInfo }, txn) {
  165. const { User } = this.server.models()
  166. if (Object.keys(userInfo).length > 0) {
  167. await User.query(txn)
  168. .throwIfNotFound()
  169. .where({ id })
  170. .patch(userInfo)
  171. }
  172. if (password) {
  173. await this.changePassword(id, password, txn)
  174. }
  175. return id
  176. }
  177. /**
  178. * Self explanatory
  179. * @param {*} param0
  180. * @param {*} txn
  181. * @returns
  182. */
  183. async login({ email, password }, txn) {
  184. const { User, Auth } = this.server.models()
  185. const user = await Auth.query(txn)
  186. .throwIfNotFound()
  187. .first()
  188. .where({ user_email: email })
  189. const bufferPepper = Buffer.from(process.env.PEPPER + password)
  190. /** Uncomment to run password check using SecurePassword */
  191. const passwordCheck = await this.pwd.verify(bufferPepper, user.token)
  192. if (passwordCheck === SecurePassword.VALID_NEEDS_REHASH) {
  193. await this.changePassword(user.user_email, password, txn)
  194. } else if (passwordCheck !== SecurePassword.VALID) {
  195. throw User.createNotFoundError()
  196. }
  197. return user
  198. }
  199. /**
  200. * Create a token to be sent in request headers
  201. * @param {User} user
  202. * @returns {Token}
  203. */
  204. // TODO: Put this logic in the routes, NOT here
  205. // createSessionToken(user, payload)
  206. // createAccessToken()
  207. //
  208. createToken(user) {
  209. const key = this.server.registrations['main-app-plugin'].options.jwtKey
  210. let token = Jwt.token.generate(
  211. {
  212. aud: 'urn:audience:test',
  213. iss: 'urn:issuer:test',
  214. // ...payload,
  215. email: user.email,
  216. name: user.name,
  217. seeking: user.seeking,
  218. salt: 'a;ldfkjas;l/dfkafnml;/cjkf',
  219. // profile_id: user.profile_id,
  220. },
  221. {
  222. key: key,
  223. algorithm: 'HS256',
  224. },
  225. {
  226. ttlSec: 4 * 60 * 60, // 7 days
  227. },
  228. )
  229. console.log('token :=>', token)
  230. token = Jwt.token.generate(
  231. {
  232. aud: 'urn:audience:test',
  233. iss: 'urn:issuer:test',
  234. // ...payload,
  235. email: user.email,
  236. name: user.name,
  237. seeking: user.seeking,
  238. salt: 'qpowieurpqowytqpoieryu',
  239. // profile_id: user.profile_id,
  240. },
  241. {
  242. key: key,
  243. algorithm: 'HS256',
  244. },
  245. {
  246. ttlSec: 4 * 60 * 60, // 7 days
  247. },
  248. )
  249. console.log('\n')
  250. console.log('token :=>', token)
  251. token = Jwt.token.generate(
  252. {
  253. aud: 'urn:audience:test',
  254. iss: 'urn:issuer:test',
  255. // ...payload,
  256. email: user.email,
  257. name: user.name,
  258. seeking: user.seeking,
  259. salt: 'a;ldfkjas;l/dfkafnml;/cjkf',
  260. // profile_id: user.profile_id,
  261. },
  262. {
  263. key: key,
  264. algorithm: 'HS256',
  265. },
  266. {
  267. ttlSec: 6 * 60 * 60, // 7 days
  268. },
  269. )
  270. console.log('token :=>', token)
  271. token = Jwt.token.generate(
  272. {
  273. aud: 'urn:audience:test',
  274. iss: 'urn:issuer:test',
  275. // ...payload,
  276. email: user.email,
  277. name: user.name,
  278. seeking: user.seeking,
  279. salt: 'a;ldfkjas;l/dfkafnml;/cjkf',
  280. // profile_id: user.profile_id,
  281. },
  282. {
  283. key: key,
  284. algorithm: 'HS256',
  285. },
  286. {
  287. ttlSec: 7 * 60 * 60, // 7 days
  288. },
  289. )
  290. console.log('token :=>', token)
  291. // TODO: keep userinfo and it's association with the sessionToken in state/memory
  292. // registerSession(user, sessionToken) // useremail, token
  293. // this.registerSession(user, token)
  294. return token
  295. }
  296. async registerSession(user, hashedEmail, token) {
  297. const sessionRequester = {
  298. user: user,
  299. hashedEmail: hashedEmail,
  300. token: token,
  301. }
  302. const alreadyExists = this.activeSessions.find(
  303. sessionRequester => sessionRequester.hashedEmail === hashedEmail,
  304. )
  305. if (!alreadyExists) {
  306. this.activeSessions.push(sessionRequester)
  307. }
  308. }
  309. /**
  310. * Validates whether a token has expired or not
  311. * @param {User} user
  312. * @returns {Token}
  313. */
  314. validateToken(token) {
  315. const key = this.server.registrations['main-app-plugin'].options.jwtKey
  316. // NOTE: reveals email...perhaps unhashed email belongs here instead...
  317. try {
  318. const decodedToken = Jwt.token.decode(token)
  319. Jwt.token.verify(decodedToken, key)
  320. return { isValid: true, payload: decodedToken.decoded.payload }
  321. } catch (err) {
  322. return { isValid: false, error: err.message }
  323. }
  324. }
  325. /**
  326. * Use knex to try to change password entry
  327. * @param {number} id
  328. * @param {string} password
  329. * @param {*} txn
  330. * @returns {number}
  331. */
  332. async changePassword(email, password, txn) {
  333. const { Auth } = this.server.models()
  334. const hashed = await this.pwd.hash(
  335. Buffer.from(process.env.PEPPER + password),
  336. )
  337. await Auth.query(txn)
  338. .throwIfNotFound()
  339. .where({ user_email: email })
  340. .patch({
  341. // user_email: email,
  342. token: hashed,
  343. })
  344. return email
  345. }
  346. async getPassword(email, txn) {
  347. const { Auth } = this.server.models()
  348. const passwordRow = await Auth.query(txn)
  349. .where('user_email', email)
  350. .first()
  351. return passwordRow ? passwordRow.token : null
  352. }
  353. async checkEmailCache(userEmail) {
  354. const hashedEmail = await hashEmail(userEmail)
  355. const now = Date.now()
  356. // hashedEmail needs to be derived by email, salt
  357. const expiration = this.hashedEmails[hashedEmail]
  358. console.log('this.hashedEmails :=>', this.hashedEmails)
  359. const emailIsInCache = Object.keys(this.hashedEmails).includes(
  360. hashedEmail,
  361. )
  362. const emailIsExpired = now > expiration ? true : false
  363. console.log('emailIsInCache :=>', emailIsInCache)
  364. console.log('emailIsExpired :=>', emailIsExpired)
  365. if (emailIsInCache && !emailIsExpired) {
  366. return true
  367. } else {
  368. // try {
  369. // delete this.hashedEmails[hashedEmail]
  370. // } catch (err) {
  371. // console.error('ERROR :=>', err)
  372. // }
  373. return false
  374. }
  375. }
  376. /**
  377. * Sends a Transactional Email via Brevo
  378. * @ returns {Object}
  379. */
  380. async emailSent(userEmail) {
  381. const hashedEmail = await hashEmail(userEmail)
  382. if (Object.keys(this.hashedEmails).includes(hashedEmail)) {
  383. return new Error('email address already in cache!!')
  384. }
  385. // Set expiration time for five minutes from now
  386. const duration = 1000 * 60 * 5
  387. this.hashedEmails[hashedEmail] = Date.now() + duration
  388. const sendSmtpEmail = {
  389. to: [
  390. {
  391. email: userEmail,
  392. },
  393. ],
  394. templateId: 1,
  395. params: {
  396. // TODO: Change this in production...
  397. link: `localhost:3000/verify/${hashedEmail}`,
  398. },
  399. }
  400. await apiInstance.sendTransacEmail(sendSmtpEmail).then(
  401. data => {
  402. return {
  403. wasSuccessfull: true,
  404. data: data,
  405. }
  406. },
  407. error => {
  408. return {
  409. wasSuccessfull: false,
  410. error: error,
  411. }
  412. },
  413. )
  414. }
  415. }