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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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 { access, accessSync } = require('fs')
  11. const defaultClient = SibApiV3Sdk.ApiClient.instance
  12. const apiKey = defaultClient.authentications['api-key']
  13. apiKey.apiKey = process.env.BREVO_KEY
  14. const apiInstance = new SibApiV3Sdk.TransactionalEmailsApi()
  15. const hashToken = async token => {
  16. // QUESTION: How to best create random salt...?
  17. const salt = crypto.randomBytes(16).toString('base64')
  18. try {
  19. return crypto.createHmac('sha256', salt).update(token).digest('hex')
  20. } catch (err) {
  21. // console.error('ERROR :=>', err)
  22. throw new Error(err.message)
  23. }
  24. }
  25. const hasher = async (pwd, steak) => {
  26. const hash = await pwd.hash(steak)
  27. const result = await pwd.verify(steak, hash)
  28. let squirtle = null
  29. switch (result) {
  30. case SecurePassword.INVALID_UNRECOGNIZED_HASH:
  31. return console.error(
  32. 'This hash was not made with secure-password. Attempt legacy algorithm',
  33. )
  34. case SecurePassword.INVALID:
  35. return console.log('Invalid password')
  36. case SecurePassword.VALID:
  37. return result
  38. case SecurePassword.VALID_NEEDS_REHASH:
  39. console.log('Yay you made it, wait for us to improve your safety')
  40. try {
  41. squirtle = await pwd.hash(steak)
  42. // console.log('improvedHash', squirtle)
  43. // const saveHash = Auth.insert({user_email:
  44. // matchingEmails}).into('token')
  45. return squirtle
  46. } catch (err) {
  47. console.error(
  48. 'You are authenticated, but we could not improve your safety this time around',
  49. )
  50. }
  51. break
  52. }
  53. }
  54. /** Class for methods used in the User plugin */
  55. module.exports = class UserService extends Schmervice.Service {
  56. /**
  57. * Unsure of what our constructor does
  58. * @param {...any} args
  59. */
  60. constructor(...args) {
  61. super(...args)
  62. const pwd = new SecurePassword()
  63. // TODO: Invalidate this application state somehow after a
  64. // certain time period has passed
  65. this.activeSessions = {
  66. // abc123456: '123456689',
  67. // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...hashedSessionToken: {
  68. // email: rawEmailString,
  69. // name: 'Joe Doe',
  70. // seeking: 'candidate'
  71. // sessionToken: rawSessionToken, // use for expires instead of expires?
  72. // expires: expirationTime in seconds
  73. // }
  74. }
  75. this.pwd = {
  76. hash: Util.promisify(pwd.hash.bind(pwd)),
  77. verify: Util.promisify(pwd.verify.bind(pwd)),
  78. }
  79. }
  80. /**
  81. * Use knex to find users with id column
  82. * @param {number} id
  83. * @param {*} txn
  84. * @returns
  85. */
  86. async findById(id, txn) {
  87. const { User } = this.server.models()
  88. return await User.query(txn)
  89. .throwIfNotFound()
  90. .first()
  91. .where({ user_id: id })
  92. }
  93. /**
  94. * Use knew to find first user with username
  95. * @param {*} username
  96. * @param {*} txn
  97. * @returns
  98. */
  99. async findByUsername(username, txn) {
  100. const { User } = this.server.models()
  101. return await User.query(txn)
  102. .throwIfNotFound()
  103. .first()
  104. .where({ user_name: username })
  105. }
  106. /**
  107. * Use to find first user with useremail
  108. * @param {*} username
  109. * @param {*} txn
  110. * @returns
  111. */
  112. async findByUserEmail(userEmail, txn) {
  113. const { User } = this.server.models()
  114. const user = await User.query(txn)
  115. .throwIfNotFound()
  116. .first()
  117. .where({ user_email: userEmail })
  118. return user
  119. }
  120. /**
  121. * Signup function
  122. * @param {*} param0
  123. * @param {*} txn
  124. * @returns
  125. */
  126. async signup({ password, userInfo, created_at }, txn) {
  127. const { User, Auth } = this.server.models()
  128. const matchingEmails = await User.query().where(
  129. 'user_email',
  130. userInfo.user_email,
  131. )
  132. if (matchingEmails.length > 0) {
  133. throw `User ${userInfo.user_email} already exists: Cannot create a user without a unique email`
  134. }
  135. // Insert User Info to User table
  136. const insertUser = await User.query().insert(userInfo)
  137. // insert a row with blank password to be updated by changePassword()
  138. await Auth.query().insert({
  139. user_email: insertUser.user_email,
  140. created_at: created_at,
  141. token: null,
  142. })
  143. // update null token with hashed password
  144. await this.changePassword(insertUser.user_email, password, txn)
  145. return {
  146. user_id: insertUser.id,
  147. user_name: insertUser.user_name,
  148. user_email: insertUser.user_email,
  149. is_poster: insertUser.is_poster,
  150. is_admin: insertUser.is_admin,
  151. is_verified: insertUser.is_verified,
  152. }
  153. }
  154. /**
  155. * Updates user's info
  156. * @param {number} id
  157. * @param {*} param1
  158. * @param {*} txn
  159. * @returns
  160. */
  161. async update(id, { password, ...userInfo }, txn) {
  162. const { User } = this.server.models()
  163. if (Object.keys(userInfo).length > 0) {
  164. await User.query(txn)
  165. .throwIfNotFound()
  166. .where({ id })
  167. .patch(userInfo)
  168. }
  169. if (password) {
  170. await this.changePassword(id, password, txn)
  171. }
  172. return id
  173. }
  174. /**
  175. * Self explanatory
  176. * @param {*} param0
  177. * @param {*} txn
  178. * @returns
  179. */
  180. async login({ email, password }, txn) {
  181. const { User, Auth } = this.server.models()
  182. const user = await Auth.query(txn)
  183. .throwIfNotFound()
  184. .first()
  185. .where({ user_email: email })
  186. const bufferPepper = Buffer.from(process.env.PEPPER + password)
  187. /** Uncomment to run password check using SecurePassword */
  188. const passwordCheck = await this.pwd.verify(bufferPepper, user.token)
  189. if (passwordCheck === SecurePassword.VALID_NEEDS_REHASH) {
  190. await this.changePassword(user.user_email, password, txn)
  191. } else if (passwordCheck !== SecurePassword.VALID) {
  192. throw User.createNotFoundError()
  193. }
  194. return user
  195. }
  196. /**
  197. * Create a token to be sent in request headers
  198. * @param {data, expiration}
  199. * @returns {Token}
  200. */
  201. createToken(data, expiration = 600) {
  202. const key = this.server.registrations['main-app-plugin'].options.jwtKey
  203. const obj = {}
  204. Object.assign(obj, { ...data })
  205. return JWT.sign(obj, key, { expiresIn: expiration })
  206. }
  207. /**
  208. * Validates whether a token has expired or not
  209. * @param {User} user
  210. * @returns {Token}
  211. */
  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. return { payload: null, message: err.message }
  218. }
  219. }
  220. /**
  221. * Uses this.validateToken() to verify hashedSessionToken's
  222. * existence, expiry, and also valdiates accessToken
  223. * @param {User} user
  224. * @returns {Token}
  225. */
  226. // TODO: remove testing console.log() messages once onboarding auth is working
  227. validateSession(hashedSessionToken) {
  228. console.log('this.activeSessions :=>', this.activeSessions)
  229. if (!this.activeSessions[hashedSessionToken]) {
  230. throw new Error(
  231. 'hashedSessionToken not in activeSessions registry!',
  232. )
  233. }
  234. const rawSessionToken =
  235. this.activeSessions[hashedSessionToken].sessionToken
  236. const accessToken = this.activeSessions[hashedSessionToken].accessToken
  237. // Weird Edge case...
  238. if (!rawSessionToken) {
  239. throw new Error(
  240. 'hashedSessionToken is in activeSessions registry, but rawSessionToken does not exist',
  241. )
  242. }
  243. const sessionTokenIsValid = this.validateToken(rawSessionToken)
  244. console.log('sessionTokenIsValid :=>', sessionTokenIsValid)
  245. const accessTokenIsValid = this.validateToken(accessToken)
  246. console.log('accessTokenIsValid :=>', accessTokenIsValid)
  247. // Both sessionToken and accessToken are expired
  248. if (!sessionTokenIsValid.payload && !accessTokenIsValid.payload) {
  249. console.log('session is expired! kicking you off!')
  250. return sessionTokenIsValid
  251. }
  252. if (sessionTokenIsValid.payload && !accessTokenIsValid.payload) {
  253. console.log(
  254. 'sessionToken is valid, but accessToken is null or is expired :=>',
  255. )
  256. const accessToken = this.createToken({
  257. payload: sessionTokenIsValid.payload,
  258. })
  259. this.activeSessions[hashedSessionToken].accessToken = accessToken
  260. } else if (!sessionTokenIsValid.payload && accessTokenIsValid.payload) {
  261. console.log(
  262. 'accessToken is valid, but sessionToken has expired :=>',
  263. )
  264. const newSessionToken = this.createToken({
  265. payload: accessTokenIsValid.payload,
  266. })
  267. this.activeSessions[hashedSessionToken].sessionToken =
  268. newSessionToken
  269. }
  270. return {
  271. ...sessionTokenIsValid.payload,
  272. sessionToken: this.activeSessions[hashedSessionToken].sessionToken,
  273. }
  274. }
  275. /**
  276. * Use knex to try to change password entry
  277. * @param {number} id
  278. * @param {string} password
  279. * @param {*} txn
  280. * @returns {number}
  281. */
  282. async changePassword(email, password, txn) {
  283. const { Auth } = this.server.models()
  284. const hashed = await this.pwd.hash(
  285. Buffer.from(process.env.PEPPER + password),
  286. )
  287. await Auth.query(txn)
  288. .throwIfNotFound()
  289. .where({ user_email: email })
  290. .patch({
  291. // user_email: email,
  292. token: hashed,
  293. })
  294. return email
  295. }
  296. async getPassword(email, txn) {
  297. const { Auth } = this.server.models()
  298. const passwordRow = await Auth.query(txn)
  299. .where('user_email', email)
  300. .first()
  301. return passwordRow ? passwordRow.token : null
  302. }
  303. /**
  304. * Sends a Transactional Email via Brevo
  305. * @ returns {Object}
  306. */
  307. async emailSent(userCredentials) {
  308. const hashedSessionToken = await hashToken(userCredentials.sessionToken)
  309. if (Object.keys(this.activeSessions).includes(hashedSessionToken)) {
  310. return new Error('session already in cache!!')
  311. }
  312. // Set expiration time for ten minutes from now
  313. const duration = 600000
  314. this.activeSessions[hashedSessionToken] = {
  315. email: userCredentials.email,
  316. name: userCredentials.name,
  317. seeking: userCredentials.seeking,
  318. sessionToken: userCredentials.sessionToken,
  319. expiration: Date.now() + duration,
  320. accessToken: null,
  321. }
  322. const sendSmtpEmail = {
  323. to: [
  324. {
  325. email: userCredentials.email,
  326. },
  327. ],
  328. templateId: 1,
  329. params: {
  330. // TODO: Change this in production...
  331. link: `localhost:3000/verify/${hashedSessionToken}`,
  332. },
  333. }
  334. return await apiInstance.sendTransacEmail(sendSmtpEmail).then(
  335. data => {
  336. return { wasSuccessfull: true, data: data }
  337. },
  338. error => {
  339. return { wasSuccessfull: false, error: error }
  340. },
  341. )
  342. }
  343. }