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

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