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 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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 hashToken = async token => {
  15. // QUESTION: How to best create random salt...?
  16. const salt = crypto.randomBytes(16).toString('base64')
  17. try {
  18. return crypto.createHmac('sha256', salt).update(token).digest('hex')
  19. } catch (err) {
  20. // console.error('ERROR :=>', err)
  21. throw new Error(err.message)
  22. }
  23. }
  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:
  43. // matchingEmails}).into('token')
  44. return squirtle
  45. } catch (err) {
  46. console.error(
  47. 'You are authenticated, but we could not improve your safety this time around',
  48. )
  49. }
  50. break
  51. }
  52. }
  53. /** Class for methods used in the User plugin */
  54. module.exports = class UserService extends Schmervice.Service {
  55. /**
  56. * Unsure of what our constructor does
  57. * @param {...any} args
  58. */
  59. constructor(...args) {
  60. super(...args)
  61. const pwd = new SecurePassword()
  62. // TODO: Invalidate this application state somehow after a
  63. // certain time period has passed
  64. this.activeSessions = {
  65. // abc123456: '123456689',
  66. // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...hashedSessionToken: {
  67. // email: rawEmailString,
  68. // name: 'Joe Doe',
  69. // seeking: 'candidate'
  70. // sessionToken: rawSessionToken, // use for expires instead of expires?
  71. // expires: expirationTime in seconds
  72. // }
  73. }
  74. this.pwd = {
  75. hash: Util.promisify(pwd.hash.bind(pwd)),
  76. verify: Util.promisify(pwd.verify.bind(pwd)),
  77. }
  78. }
  79. /**
  80. * Use knex to find users with id column
  81. * @param {number} id
  82. * @param {*} txn
  83. * @returns
  84. */
  85. async findById(id, txn) {
  86. const { User } = this.server.models()
  87. return await User.query(txn)
  88. .throwIfNotFound()
  89. .first()
  90. .where({ user_id: id })
  91. }
  92. /**
  93. * Use knew to find first user with username
  94. * @param {*} username
  95. * @param {*} txn
  96. * @returns
  97. */
  98. async findByUsername(username, txn) {
  99. const { User } = this.server.models()
  100. return await User.query(txn)
  101. .throwIfNotFound()
  102. .first()
  103. .where({ user_name: username })
  104. }
  105. /**
  106. * Use knew to find first user with useremail
  107. * @param {*} username
  108. * @param {*} txn
  109. * @returns
  110. */
  111. async findByUserEmail(userEmail, txn) {
  112. const { User } = this.server.models()
  113. const user = await User.query(txn)
  114. .throwIfNotFound()
  115. .first()
  116. .where({ user_email: userEmail })
  117. return user
  118. }
  119. /**
  120. * Signup function
  121. * @param {*} param0
  122. * @param {*} txn
  123. * @returns
  124. */
  125. async signup({ password, userInfo, created_at }, txn) {
  126. const { User, Auth } = this.server.models()
  127. const matchingEmails = await User.query().where(
  128. 'user_email',
  129. userInfo.user_email,
  130. )
  131. if (matchingEmails.length > 0) {
  132. throw `User ${userInfo.user_email} already exists: Cannot create a user without a unique email`
  133. }
  134. // Insert User Info to User table
  135. const insertUser = await User.query().insert(userInfo)
  136. // insert a row with blank password to be updated by changePassword()
  137. await Auth.query().insert({
  138. user_email: insertUser.user_email,
  139. created_at: created_at,
  140. token: null,
  141. })
  142. // update null token with hashed password
  143. await this.changePassword(insertUser.user_email, password, txn)
  144. return {
  145. user_id: insertUser.id,
  146. user_name: insertUser.user_name,
  147. user_email: insertUser.user_email,
  148. is_poster: insertUser.is_poster,
  149. is_admin: insertUser.is_admin,
  150. is_verified: insertUser.is_verified,
  151. }
  152. }
  153. /**
  154. * Updates user's info
  155. * @param {number} id
  156. * @param {*} param1
  157. * @param {*} txn
  158. * @returns
  159. */
  160. async update(id, { password, ...userInfo }, txn) {
  161. const { User } = this.server.models()
  162. if (Object.keys(userInfo).length > 0) {
  163. await User.query(txn)
  164. .throwIfNotFound()
  165. .where({ id })
  166. .patch(userInfo)
  167. }
  168. if (password) {
  169. await this.changePassword(id, password, txn)
  170. }
  171. return id
  172. }
  173. /**
  174. * Self explanatory
  175. * @param {*} param0
  176. * @param {*} txn
  177. * @returns
  178. */
  179. async login({ email, password }, txn) {
  180. const { User, Auth } = this.server.models()
  181. const user = await Auth.query(txn)
  182. .throwIfNotFound()
  183. .first()
  184. .where({ user_email: email })
  185. const bufferPepper = Buffer.from(process.env.PEPPER + password)
  186. /** Uncomment to run password check using SecurePassword */
  187. const passwordCheck = await this.pwd.verify(bufferPepper, user.token)
  188. if (passwordCheck === SecurePassword.VALID_NEEDS_REHASH) {
  189. await this.changePassword(user.user_email, password, txn)
  190. } else if (passwordCheck !== SecurePassword.VALID) {
  191. throw User.createNotFoundError()
  192. }
  193. return user
  194. }
  195. /**
  196. * Create a token to be sent in request headers
  197. * @param {User} user
  198. * @returns {Token}
  199. */
  200. createToken(data) {
  201. const key = this.server.registrations['main-app-plugin'].options.jwtKey
  202. const obj = {}
  203. Object.assign(obj, { ...data })
  204. return JWT.sign(obj, key, { expiresIn: data.expires })
  205. }
  206. /**
  207. * Validates whether a token has expired or not
  208. * @param {User} user
  209. * @returns {Token}
  210. */
  211. // TODO: Move this ino the auth strategies
  212. validateToken(token) {
  213. const key = this.server.registrations['main-app-plugin'].options.jwtKey
  214. try {
  215. return JWT.verify(token, key)
  216. } catch (err) {
  217. throw new Error(err.message)
  218. }
  219. }
  220. /**
  221. * Use knex to try to change password entry
  222. * @param {number} id
  223. * @param {string} password
  224. * @param {*} txn
  225. * @returns {number}
  226. */
  227. async changePassword(email, password, txn) {
  228. const { Auth } = this.server.models()
  229. const hashed = await this.pwd.hash(
  230. Buffer.from(process.env.PEPPER + password),
  231. )
  232. await Auth.query(txn)
  233. .throwIfNotFound()
  234. .where({ user_email: email })
  235. .patch({
  236. // user_email: email,
  237. token: hashed,
  238. })
  239. return email
  240. }
  241. async getPassword(email, txn) {
  242. const { Auth } = this.server.models()
  243. const passwordRow = await Auth.query(txn)
  244. .where('user_email', email)
  245. .first()
  246. return passwordRow ? passwordRow.token : null
  247. }
  248. // TODO: rewrite for new activeSessions object
  249. async checkEmailRegistry(userEmail) {
  250. const hashedEmail = await hashEmail(userEmail)
  251. const now = Date.now()
  252. // hashedEmail needs to be derived by email, salt
  253. const expiration = this.hashedEmails[hashedEmail]
  254. console.log('this.hashedEmails :=>', this.hashedEmails)
  255. const emailIsRegistered = Object.keys(this.hashedEmails).includes(
  256. hashedEmail,
  257. )
  258. const emailIsExpired = now > expiration ? true : false
  259. console.log('emailIsRegistered :=>', emailIsRegistered)
  260. console.log('emailIsExpired :=>', emailIsExpired)
  261. if (emailIsRegistered && !emailIsExpired) {
  262. return true
  263. } else {
  264. return false
  265. }
  266. }
  267. /**
  268. * Sends a Transactional Email via Brevo
  269. * @ returns {Object}
  270. */
  271. async emailSent(userCredentials) {
  272. const hashedSessionToken = await hashToken(userCredentials.sessionToken)
  273. if (Object.keys(this.activeSessions).includes(hashedSessionToken)) {
  274. return new Error('session already in cache!!')
  275. }
  276. // Set expiration time for ten minutes from now
  277. // QUESTION: should we use the sessionToken's expiration time instead?
  278. const duration = 600000
  279. this.activeSessions[hashedSessionToken] = {
  280. email: userCredentials.email,
  281. name: userCredentials.name,
  282. seeking: userCredentials.seeking,
  283. sessionToken: userCredentials.sessionToken,
  284. expiration: Date.now() + duration,
  285. }
  286. const sendSmtpEmail = {
  287. to: [
  288. {
  289. email: userCredentials.email,
  290. },
  291. ],
  292. templateId: 1,
  293. params: {
  294. // TODO: Change this in production...
  295. link: `localhost:3000/verify/${hashedSessionToken}`,
  296. },
  297. }
  298. return await apiInstance.sendTransacEmail(sendSmtpEmail).then(
  299. data => {
  300. return { wasSuccessfull: true, data: data }
  301. },
  302. error => {
  303. return { wasSuccessfull: false, error: error }
  304. },
  305. )
  306. }
  307. }