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.

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