Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

user.js 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. 'use strict'
  2. require('dotenv').config()
  3. const crypto = require('crypto')
  4. const Util = require('util')
  5. const JWT = require('jsonwebtoken')
  6. const Schmervice = require('@hapipal/schmervice')
  7. const SecurePassword = require('secure-password')
  8. // Configuration for Brevo
  9. const Brevo = require('@getbrevo/brevo')
  10. const defaultClient = Brevo.ApiClient.instance
  11. const apiKey = defaultClient.authentications['api-key']
  12. apiKey.apiKey = process.env.BREVO_KEY
  13. const apiInstance = new Brevo.TransactionalEmailsApi()
  14. const sendSmtpEmail = new Brevo.SendSmtpEmail()
  15. // TODO: Consider implementing, nice use of SecurePassword,
  16. // but currently not used anywhere...
  17. const hasher = async (pwd, steak) => {
  18. const hash = await pwd.hash(steak)
  19. const result = await pwd.verify(steak, hash)
  20. let squirtle = null
  21. switch (result) {
  22. case SecurePassword.INVALID_UNRECOGNIZED_HASH:
  23. return console.error(
  24. 'This hash was not made with secure-password. Attempt legacy algorithm',
  25. )
  26. case SecurePassword.INVALID:
  27. return console.log('Invalid password')
  28. case SecurePassword.VALID:
  29. return result
  30. case SecurePassword.VALID_NEEDS_REHASH:
  31. console.log('Yay you made it, wait for us to improve your safety')
  32. try {
  33. squirtle = await pwd.hash(steak)
  34. // console.log('improvedHash', squirtle)
  35. // const saveHash = Auth.insert({user_email:
  36. // matchingEmails}).into('token')
  37. return squirtle
  38. } catch (err) {
  39. console.error(
  40. 'You are authenticated, but we could not improve your safety this time around',
  41. )
  42. }
  43. break
  44. }
  45. }
  46. /** Class for methods used in the User plugin */
  47. module.exports = class UserService extends Schmervice.Service {
  48. /**
  49. * Unsure of what our constructor does
  50. * @param {...any} args
  51. */
  52. constructor(...args) {
  53. super(...args)
  54. const pwd = new SecurePassword()
  55. // TODO: Invalidate this application state somehow after a
  56. // certain time period has passed
  57. this.activeSessions = {}
  58. this.pwd = {
  59. hash: Util.promisify(pwd.hash.bind(pwd)),
  60. verify: Util.promisify(pwd.verify.bind(pwd)),
  61. }
  62. }
  63. /**
  64. * Use knex to find users with id column
  65. * @param {number} id
  66. * @param {*} txn
  67. * @returns
  68. */
  69. async findById(id, txn) {
  70. const { User } = this.server.models()
  71. return await User.query(txn)
  72. .throwIfNotFound()
  73. .first()
  74. .where({ user_id: id })
  75. }
  76. /**
  77. * Use knew to find first user with username
  78. * @param {*} username
  79. * @param {*} txn
  80. * @returns
  81. */
  82. async findByUsername(username, txn) {
  83. const { User } = this.server.models()
  84. return await User.query(txn)
  85. .throwIfNotFound()
  86. .first()
  87. .where({ user_name: username })
  88. }
  89. /**
  90. * Use to find first user with useremail
  91. * @param {*} username
  92. * @param {*} txn
  93. * @returns
  94. */
  95. async findByUserEmail(userEmail, txn) {
  96. const { User } = this.server.models()
  97. const user = await User.query(txn)
  98. .throwIfNotFound()
  99. .first()
  100. .where({ user_email: userEmail })
  101. return user
  102. }
  103. hashToken(token) {
  104. const salt = process.env.APP_SESSION_SALT
  105. try {
  106. return crypto.createHmac('sha256', salt).update(token).digest('hex')
  107. } catch (err) {
  108. throw new Error(err.message)
  109. }
  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 {data, expiration}
  190. * @returns {Token}
  191. */
  192. createToken(data, expiration = 600) {
  193. const key = this.server.registrations['main-app-plugin'].options.jwtKey
  194. const obj = {}
  195. Object.assign(obj, { ...data })
  196. return JWT.sign(obj, key, { expiresIn: expiration })
  197. }
  198. async makeUserCredentials(email) {
  199. const user = await this.findByUserEmail(email)
  200. const userCredentials = {
  201. email: user.user_email,
  202. name: user.user_name,
  203. seeking: user.is_poster === 1 ? 'poster' : 'seeker',
  204. }
  205. const token = this.createToken({
  206. payload: userCredentials,
  207. })
  208. return {
  209. userCredentials,
  210. token,
  211. }
  212. }
  213. /**
  214. * Validates whether a token has expired or not
  215. * @param {User} user
  216. * @returns {Token}
  217. */
  218. validateToken(token) {
  219. const key = this.server.registrations['main-app-plugin'].options.jwtKey
  220. try {
  221. return JWT.verify(token, key)
  222. } catch (err) {
  223. return { payload: null, message: err.message }
  224. }
  225. }
  226. /**
  227. * Uses this.validateToken() to verify hashedSessionToken's
  228. * existence, expiry, and also valdiates accessToken
  229. * @param {HashedSessionToken} hashedSessionToken
  230. * @returns {PayloadFromActiveSessions}
  231. */
  232. validateSession(hashedSessionToken) {
  233. const userSession = this.activeSessions[hashedSessionToken]
  234. if (!userSession) {
  235. throw new Error(
  236. 'hashedSessionToken not in activeSessions registry!',
  237. )
  238. }
  239. if (!userSession.emailWasRespondedTo) {
  240. throw new Error('email was never responded to!')
  241. }
  242. const sessionToken = userSession.sessionToken
  243. const sessionTokenIsValid = this.validateToken(sessionToken)
  244. return {
  245. ...sessionTokenIsValid.payload,
  246. sessionToken: this.activeSessions[hashedSessionToken].sessionToken,
  247. }
  248. }
  249. removeSession(hashedSessionToken) {
  250. const userSession = this.activeSessions[hashedSessionToken]
  251. if (!userSession) {
  252. throw new Error(
  253. 'hashedSessionToken not in activeSessions registry!',
  254. )
  255. } else {
  256. delete this.activeSessions[hashedSessionToken]
  257. }
  258. }
  259. /**
  260. * Use knex to try to change password entry
  261. * @param {number} id
  262. * @param {string} password
  263. * @param {*} txn
  264. * @returns {number}
  265. */
  266. async changePassword(email, password, txn) {
  267. const { Auth } = this.server.models()
  268. const hashed = await this.pwd.hash(
  269. Buffer.from(process.env.PEPPER + password),
  270. )
  271. await Auth.query(txn)
  272. .throwIfNotFound()
  273. .where({ user_email: email })
  274. .patch({
  275. // user_email: email,
  276. token: hashed,
  277. })
  278. return email
  279. }
  280. async getPassword(email, txn) {
  281. const { Auth } = this.server.models()
  282. const passwordRow = await Auth.query(txn)
  283. .where('user_email', email)
  284. .first()
  285. return passwordRow ? passwordRow.token : null
  286. }
  287. /**
  288. * Sends a Transactional Email via Brevo
  289. * @ returns {Object}
  290. */
  291. async emailSent(userCredentials) {
  292. const hashedSessionToken = this.hashToken(userCredentials.sessionToken)
  293. if (Object.keys(this.activeSessions).includes(hashedSessionToken)) {
  294. return new Error('session already in cache!!')
  295. }
  296. // Set expiration time for ten minutes from now
  297. const duration = 600000
  298. this.activeSessions[hashedSessionToken] = {
  299. email: userCredentials.email,
  300. name: userCredentials.name,
  301. seeking: userCredentials.seeking,
  302. sessionToken: userCredentials.sessionToken,
  303. expiration: Date.now() + duration,
  304. emailWasRespondedTo: false,
  305. accessToken: null,
  306. }
  307. // NOTE: Although this looks messy, Brevo requries these
  308. // parameters be defined individually like this, attempts
  309. // to configure this in a singel object cause errors on their API
  310. sendSmtpEmail.sender = {
  311. name: 'My Test Company',
  312. email: 'mytestemail@email.com',
  313. }
  314. sendSmtpEmail.subject = 'My Test Company'
  315. sendSmtpEmail.to = [
  316. {
  317. email: userCredentials.email,
  318. },
  319. ]
  320. sendSmtpEmail.templateId = Number(process.env.BREVO_TEMPLATE_ID)
  321. sendSmtpEmail.params = {
  322. link: `${process.env.BREVO_LINK}/verify/${hashedSessionToken}`,
  323. }
  324. return await apiInstance.sendTransacEmail(sendSmtpEmail).then(
  325. data => {
  326. return { wasSuccessfull: true, data: data }
  327. },
  328. error => {
  329. return { wasSuccessfull: false, error: error }
  330. },
  331. )
  332. }
  333. }