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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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. const salt = process.env.APP_SESSION_SALT
  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. // Check the hashedCookie which is our hashedSessionToken string
  75. // validate whether or not the rawAccessToken is still valid, if valid good to go.
  76. // if NOT valid, then we need to reassign accessToken to a newAccessToken
  77. // this.activeSessions = {
  78. // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...hashedSessionToken: {
  79. // accessToken: 'as;dflkja;;dlfkja;sldkf... rawAccessToken'
  80. // }
  81. // }
  82. this.pwd = {
  83. hash: Util.promisify(pwd.hash.bind(pwd)),
  84. verify: Util.promisify(pwd.verify.bind(pwd)),
  85. }
  86. }
  87. /**
  88. * Use knex to find users with id column
  89. * @param {number} id
  90. * @param {*} txn
  91. * @returns
  92. */
  93. async findById(id, txn) {
  94. const { User } = this.server.models()
  95. return await User.query(txn)
  96. .throwIfNotFound()
  97. .first()
  98. .where({ user_id: id })
  99. }
  100. /**
  101. * Use knew to find first user with username
  102. * @param {*} username
  103. * @param {*} txn
  104. * @returns
  105. */
  106. async findByUsername(username, txn) {
  107. const { User } = this.server.models()
  108. return await User.query(txn)
  109. .throwIfNotFound()
  110. .first()
  111. .where({ user_name: username })
  112. }
  113. /**
  114. * Use to find first user with useremail
  115. * @param {*} username
  116. * @param {*} txn
  117. * @returns
  118. */
  119. async findByUserEmail(userEmail, txn) {
  120. const { User } = this.server.models()
  121. const user = await User.query(txn)
  122. .throwIfNotFound()
  123. .first()
  124. .where({ user_email: userEmail })
  125. return user
  126. }
  127. /**
  128. * Signup function
  129. * @param {*} param0
  130. * @param {*} txn
  131. * @returns
  132. */
  133. async signup({ password, userInfo, created_at }, txn) {
  134. const { User, Auth } = this.server.models()
  135. const matchingEmails = await User.query().where(
  136. 'user_email',
  137. userInfo.user_email,
  138. )
  139. if (matchingEmails.length > 0) {
  140. throw `User ${userInfo.user_email} already exists: Cannot create a user without a unique email`
  141. }
  142. // Insert User Info to User table
  143. const insertUser = await User.query().insert(userInfo)
  144. // insert a row with blank password to be updated by changePassword()
  145. await Auth.query().insert({
  146. user_email: insertUser.user_email,
  147. created_at: created_at,
  148. token: null,
  149. })
  150. // update null token with hashed password
  151. await this.changePassword(insertUser.user_email, password, txn)
  152. return {
  153. user_id: insertUser.id,
  154. user_name: insertUser.user_name,
  155. user_email: insertUser.user_email,
  156. is_poster: insertUser.is_poster,
  157. is_admin: insertUser.is_admin,
  158. is_verified: insertUser.is_verified,
  159. }
  160. }
  161. /**
  162. * Updates user's info
  163. * @param {number} id
  164. * @param {*} param1
  165. * @param {*} txn
  166. * @returns
  167. */
  168. async update(id, { password, ...userInfo }, txn) {
  169. const { User } = this.server.models()
  170. if (Object.keys(userInfo).length > 0) {
  171. await User.query(txn)
  172. .throwIfNotFound()
  173. .where({ id })
  174. .patch(userInfo)
  175. }
  176. if (password) {
  177. await this.changePassword(id, password, txn)
  178. }
  179. return id
  180. }
  181. /**
  182. * Self explanatory
  183. * @param {*} param0
  184. * @param {*} txn
  185. * @returns
  186. */
  187. async login({ email, password }, txn) {
  188. const { User, Auth } = this.server.models()
  189. const user = await Auth.query(txn)
  190. .throwIfNotFound()
  191. .first()
  192. .where({ user_email: email })
  193. const bufferPepper = Buffer.from(process.env.PEPPER + password)
  194. /** Uncomment to run password check using SecurePassword */
  195. const passwordCheck = await this.pwd.verify(bufferPepper, user.token)
  196. if (passwordCheck === SecurePassword.VALID_NEEDS_REHASH) {
  197. await this.changePassword(user.user_email, password, txn)
  198. } else if (passwordCheck !== SecurePassword.VALID) {
  199. throw User.createNotFoundError()
  200. }
  201. return user
  202. }
  203. /**
  204. * Create a token to be sent in request headers
  205. * @param {data, expiration}
  206. * @returns {Token}
  207. */
  208. createToken(data, expiration = 600) {
  209. const key = this.server.registrations['main-app-plugin'].options.jwtKey
  210. const obj = {}
  211. Object.assign(obj, { ...data })
  212. return JWT.sign(obj, key, { expiresIn: expiration })
  213. }
  214. /**
  215. * Validates whether a token has expired or not
  216. * @param {User} user
  217. * @returns {Token}
  218. */
  219. validateToken(token) {
  220. const key = this.server.registrations['main-app-plugin'].options.jwtKey
  221. try {
  222. return JWT.verify(token, key)
  223. } catch (err) {
  224. return { payload: null, message: err.message }
  225. }
  226. }
  227. /**
  228. * Uses this.validateToken() to verify hashedSessionToken's
  229. * existence, expiry, and also valdiates accessToken
  230. * @param {User} user
  231. * @returns {Token}
  232. */
  233. // TODO: remove testing console.log() messages once onboarding auth is working
  234. // REFACTOR: Have this function only do one thing (UNIX philsophy)
  235. validateSession(hashedSessionToken) {
  236. console.log('this.activeSessions :=>', this.activeSessions)
  237. if (!this.activeSessions[hashedSessionToken]) {
  238. throw new Error(
  239. 'hashedSessionToken not in activeSessions registry!',
  240. )
  241. }
  242. // BREAK OUT INTO ANOTHER FUNC
  243. const rawSessionToken =
  244. this.activeSessions[hashedSessionToken].sessionToken
  245. const accessToken = this.activeSessions[hashedSessionToken].accessToken
  246. // Weird Edge case...
  247. if (!rawSessionToken) {
  248. throw new Error(
  249. 'hashedSessionToken is in activeSessions registry, but rawSessionToken does not exist',
  250. )
  251. }
  252. // ANOTHER FUNC HERE
  253. const sessionTokenIsValid = this.validateToken(rawSessionToken)
  254. const accessTokenIsValid = this.validateToken(accessToken)
  255. // Both sessionToken and accessToken are expired
  256. // createAccessToken()
  257. //
  258. if (!accessTokenIsValid.payload) {
  259. console.log(
  260. 'sessionToken is valid, but accessToken is null or is expired :=>',
  261. )
  262. const accessToken = this.createToken({
  263. payload: sessionTokenIsValid.payload,
  264. })
  265. this.activeSessions[hashedSessionToken].accessToken = accessToken
  266. }
  267. return {
  268. ...sessionTokenIsValid.payload,
  269. sessionToken: this.activeSessions[hashedSessionToken].sessionToken,
  270. }
  271. }
  272. /**
  273. * Use knex to try to change password entry
  274. * @param {number} id
  275. * @param {string} password
  276. * @param {*} txn
  277. * @returns {number}
  278. */
  279. async changePassword(email, password, txn) {
  280. const { Auth } = this.server.models()
  281. const hashed = await this.pwd.hash(
  282. Buffer.from(process.env.PEPPER + password),
  283. )
  284. await Auth.query(txn)
  285. .throwIfNotFound()
  286. .where({ user_email: email })
  287. .patch({
  288. // user_email: email,
  289. token: hashed,
  290. })
  291. return email
  292. }
  293. async getPassword(email, txn) {
  294. const { Auth } = this.server.models()
  295. const passwordRow = await Auth.query(txn)
  296. .where('user_email', email)
  297. .first()
  298. return passwordRow ? passwordRow.token : null
  299. }
  300. /**
  301. * Sends a Transactional Email via Brevo
  302. * @ returns {Object}
  303. */
  304. async emailSent(userCredentials) {
  305. const hashedSessionToken = await hashToken(userCredentials.sessionToken)
  306. if (Object.keys(this.activeSessions).includes(hashedSessionToken)) {
  307. return new Error('session already in cache!!')
  308. }
  309. // Set expiration time for ten minutes from now
  310. const duration = 600000
  311. this.activeSessions[hashedSessionToken] = {
  312. email: userCredentials.email,
  313. name: userCredentials.name,
  314. seeking: userCredentials.seeking,
  315. sessionToken: userCredentials.sessionToken,
  316. expiration: Date.now() + duration,
  317. accessToken: null,
  318. }
  319. const sendSmtpEmail = {
  320. to: [
  321. {
  322. email: userCredentials.email,
  323. },
  324. ],
  325. templateId: 1,
  326. params: {
  327. // TODO: Change this in production...
  328. link: `localhost:3000/verify/${hashedSessionToken}`,
  329. },
  330. }
  331. return await apiInstance.sendTransacEmail(sendSmtpEmail).then(
  332. data => {
  333. return { wasSuccessfull: true, data: data }
  334. },
  335. error => {
  336. return { wasSuccessfull: false, error: error }
  337. },
  338. )
  339. }
  340. }