Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

user.js 11KB

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