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.

user.js 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. return undefined
  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. // TODO: Put this logic in the routes, NOT here
  203. // createSessionToken(user, payload)
  204. // createAccessToken()
  205. //
  206. createToken(user) {
  207. const key = this.server.registrations['main-app-plugin'].options.jwtKey
  208. const obj = {}
  209. Object.assign(obj, { ...user })
  210. return JWT.sign(obj, key)
  211. }
  212. async registerSession(user, hashedEmail, token) {
  213. const sessionRequester = {
  214. user: user,
  215. hashedEmail: hashedEmail,
  216. token: token,
  217. }
  218. const alreadyExists = this.activeSessions.find(
  219. sessionRequester => sessionRequester.hashedEmail === hashedEmail,
  220. )
  221. if (!alreadyExists) {
  222. this.activeSessions.push(sessionRequester)
  223. }
  224. }
  225. /**
  226. * Validates whether a token has expired or not
  227. * @param {User} user
  228. * @returns {Token}
  229. */
  230. validateToken(token) {
  231. console.log('token :=>', token)
  232. const key = this.server.registrations['main-app-plugin'].options.jwtKey
  233. try {
  234. const decodedToken = JWT.verify(token, key)
  235. console.log('decodedToken :=>', decodedToken)
  236. return { isValid: true, payload: decodedToken }
  237. } catch (err) {
  238. console.error('ERROR :=>', err)
  239. return { isValid: false, error: err.message }
  240. }
  241. }
  242. /**
  243. * Use knex to try to change password entry
  244. * @param {number} id
  245. * @param {string} password
  246. * @param {*} txn
  247. * @returns {number}
  248. */
  249. async changePassword(email, password, txn) {
  250. const { Auth } = this.server.models()
  251. const hashed = await this.pwd.hash(
  252. Buffer.from(process.env.PEPPER + password),
  253. )
  254. await Auth.query(txn)
  255. .throwIfNotFound()
  256. .where({ user_email: email })
  257. .patch({
  258. // user_email: email,
  259. token: hashed,
  260. })
  261. return email
  262. }
  263. async getPassword(email, txn) {
  264. const { Auth } = this.server.models()
  265. const passwordRow = await Auth.query(txn)
  266. .where('user_email', email)
  267. .first()
  268. return passwordRow ? passwordRow.token : null
  269. }
  270. async checkEmailRegistry(userEmail) {
  271. const hashedEmail = await hashEmail(userEmail)
  272. const now = Date.now()
  273. // hashedEmail needs to be derived by email, salt
  274. const expiration = this.hashedEmails[hashedEmail]
  275. console.log('this.hashedEmails :=>', this.hashedEmails)
  276. const emailIsRegistered = Object.keys(this.hashedEmails).includes(
  277. hashedEmail,
  278. )
  279. const emailIsExpired = now > expiration ? true : false
  280. console.log('emailIsRegistered :=>', emailIsRegistered)
  281. console.log('emailIsExpired :=>', emailIsExpired)
  282. if (emailIsRegistered && !emailIsExpired) {
  283. return true
  284. } else {
  285. // try {
  286. // delete this.hashedEmails[hashedEmail]
  287. // } catch (err) {
  288. // console.error('ERROR :=>', err)
  289. // }
  290. return false
  291. }
  292. }
  293. /**
  294. * Sends a Transactional Email via Brevo
  295. * @ returns {Object}
  296. */
  297. async emailSent(userEmail) {
  298. const hashedEmail = await hashEmail(userEmail)
  299. if (Object.keys(this.hashedEmails).includes(hashedEmail)) {
  300. return new Error('email address already in cache!!')
  301. }
  302. // Set expiration time for five minutes from now
  303. const duration = 1000 * 60 * 5
  304. this.hashedEmails[hashedEmail] = Date.now() + duration
  305. const sendSmtpEmail = {
  306. to: [
  307. {
  308. email: userEmail,
  309. },
  310. ],
  311. templateId: 1,
  312. params: {
  313. // TODO: Change this in production...
  314. link: `localhost:3000/verify/${hashedEmail}`,
  315. },
  316. }
  317. await apiInstance.sendTransacEmail(sendSmtpEmail).then(
  318. data => {
  319. return { wasSuccessfull: true, data: data }
  320. },
  321. error => {
  322. return { wasSuccessfull: false, error: error }
  323. },
  324. )
  325. }
  326. }