Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

user.js 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. const { User } = this.server.models()
  105. const user = await User.query(txn)
  106. .throwIfNotFound()
  107. .first()
  108. .where({ user_email: userEmail })
  109. return user
  110. }
  111. /**
  112. * Signup function
  113. * @param {*} param0
  114. * @param {*} txn
  115. * @returns
  116. */
  117. async signup({ password, userInfo, created_at }, txn) {
  118. const { User, Auth } = this.server.models()
  119. const matchingEmails = await User.query().where(
  120. 'user_email',
  121. userInfo.user_email,
  122. )
  123. if (matchingEmails.length > 0) {
  124. throw `User ${userInfo.user_email} already exists: Cannot create a user without a unique email`
  125. }
  126. // Insert User Info to User table
  127. const insertUser = await User.query().insert(userInfo)
  128. // insert a row with blank password to be updated by changePassword()
  129. await Auth.query().insert({
  130. user_email: insertUser.user_email,
  131. created_at: created_at,
  132. token: null,
  133. })
  134. // update null token with hashed password
  135. await this.changePassword(insertUser.user_email, password, txn)
  136. return {
  137. user_id: insertUser.id,
  138. user_name: insertUser.user_name,
  139. user_email: insertUser.user_email,
  140. is_poster: insertUser.is_poster,
  141. is_admin: insertUser.is_admin,
  142. is_verified: insertUser.is_verified,
  143. }
  144. }
  145. /**
  146. * Updates user's info
  147. * @param {number} id
  148. * @param {*} param1
  149. * @param {*} txn
  150. * @returns
  151. */
  152. async update(id, { password, ...userInfo }, txn) {
  153. const { User } = this.server.models()
  154. if (Object.keys(userInfo).length > 0) {
  155. await User.query(txn)
  156. .throwIfNotFound()
  157. .where({ id })
  158. .patch(userInfo)
  159. }
  160. if (password) {
  161. await this.changePassword(id, password, txn)
  162. }
  163. return id
  164. }
  165. /**
  166. * Self explanatory
  167. * @param {*} param0
  168. * @param {*} txn
  169. * @returns
  170. */
  171. async login({ email, password }, txn) {
  172. const { User, Auth } = this.server.models()
  173. const user = await Auth.query(txn)
  174. .throwIfNotFound()
  175. .first()
  176. .where({ user_email: email })
  177. const bufferPepper = Buffer.from(process.env.PEPPER + password)
  178. /** Uncomment to run password check using SecurePassword */
  179. const passwordCheck = await this.pwd.verify(bufferPepper, user.token)
  180. if (passwordCheck === SecurePassword.VALID_NEEDS_REHASH) {
  181. await this.changePassword(user.user_email, password, txn)
  182. } else if (passwordCheck !== SecurePassword.VALID) {
  183. throw User.createNotFoundError()
  184. }
  185. return user
  186. }
  187. /**
  188. * Create a token to be sent in request headers
  189. * @param {User} user
  190. * @returns {Token}
  191. */
  192. createToken(user) {
  193. const key = this.server.registrations['main-app-plugin'].options.jwtKey
  194. const token = Jwt.token.generate(
  195. {
  196. aud: 'urn:audience:test',
  197. iss: 'urn:issuer:test',
  198. email: user.email,
  199. name: user.name,
  200. seeking: user.seeking,
  201. // profile_id: user.profile_id,
  202. },
  203. {
  204. key: key,
  205. algorithm: 'HS256',
  206. },
  207. {
  208. // ttlSec: 4 * 60 * 60, // 7 days
  209. // ttlSec: 60 * 3, // 3 minutes
  210. ttlSec: user.expiration,
  211. },
  212. )
  213. return token
  214. }
  215. /**
  216. * Validates whether a token has expired or not
  217. * @param {User} user
  218. * @returns {Token}
  219. */
  220. validateToken(token) {
  221. const key = this.server.registrations['main-app-plugin'].options.jwtKey
  222. // NOTE: reveals email...perhaps unhashed email belongs here instead...
  223. try {
  224. const decodedToken = Jwt.token.decode(token)
  225. Jwt.token.verify(decodedToken, key)
  226. return { isValid: true, payload: decodedToken.decoded.payload }
  227. } catch (err) {
  228. return { isValid: false, error: err.message }
  229. }
  230. }
  231. /**
  232. * Use knex to try to change password entry
  233. * @param {number} id
  234. * @param {string} password
  235. * @param {*} txn
  236. * @returns {number}
  237. */
  238. async changePassword(email, password, txn) {
  239. const { Auth } = this.server.models()
  240. const hashed = await this.pwd.hash(
  241. Buffer.from(process.env.PEPPER + password),
  242. )
  243. await Auth.query(txn)
  244. .throwIfNotFound()
  245. .where({ user_email: email })
  246. .patch({
  247. // user_email: email,
  248. token: hashed,
  249. })
  250. return email
  251. }
  252. async getPassword(email, txn) {
  253. const { Auth } = this.server.models()
  254. const passwordRow = await Auth.query(txn)
  255. .where('user_email', email)
  256. .first()
  257. return passwordRow ? passwordRow.token : null
  258. }
  259. async checkEmailCache(userEmail) {
  260. const hashedEmail = await hashEmail(userEmail)
  261. const now = Date.now()
  262. const expiration = this.hashedEmails[hashedEmail]
  263. console.log('this.hashedEmails :=>', this.hashedEmails)
  264. const emailIsInCache = Object.keys(this.hashedEmails).includes(
  265. hashedEmail,
  266. )
  267. const emailIsExpired = now > expiration ? true : false
  268. console.log('emailIsInCache :=>', emailIsInCache)
  269. console.log('emailIsExpired :=>', emailIsExpired)
  270. if (emailIsInCache && !emailIsExpired) {
  271. return true
  272. } else {
  273. // try {
  274. // delete this.hashedEmails[hashedEmail]
  275. // } catch (err) {
  276. // console.error('ERROR :=>', err)
  277. // }
  278. return false
  279. }
  280. }
  281. /**
  282. * Sends a Transactional Email via Brevo
  283. * @ returns {Object}
  284. */
  285. async emailSent(userEmail) {
  286. const hashedEmail = await hashEmail(userEmail)
  287. if (Object.keys(this.hashedEmails).includes(hashedEmail)) {
  288. return new Error('email address already in cache!!')
  289. }
  290. // Set expiration time for five minutes from now
  291. const duration = 1000 * 60 * 5
  292. this.hashedEmails[hashedEmail] = Date.now() + duration
  293. const sendSmtpEmail = {
  294. to: [
  295. {
  296. email: userEmail,
  297. },
  298. ],
  299. templateId: 1,
  300. params: {
  301. // TODO: Change this in production...
  302. link: `localhost:3000/verify/${hashedEmail}`,
  303. },
  304. }
  305. await apiInstance.sendTransacEmail(sendSmtpEmail).then(
  306. data => {
  307. return {
  308. wasSuccessfull: true,
  309. data: data,
  310. }
  311. },
  312. error => {
  313. return {
  314. wasSuccessfull: false,
  315. error: error,
  316. }
  317. },
  318. )
  319. }
  320. }