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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. throw new Error(err.message)
  21. }
  22. }
  23. const hasher = async (pwd, steak) => {
  24. const hash = await pwd.hash(steak)
  25. const result = await pwd.verify(steak, hash)
  26. let squirtle = null
  27. switch (result) {
  28. case SecurePassword.INVALID_UNRECOGNIZED_HASH:
  29. return console.error(
  30. 'This hash was not made with secure-password. Attempt legacy algorithm',
  31. )
  32. case SecurePassword.INVALID:
  33. return console.log('Invalid password')
  34. case SecurePassword.VALID:
  35. return result
  36. case SecurePassword.VALID_NEEDS_REHASH:
  37. console.log('Yay you made it, wait for us to improve your safety')
  38. try {
  39. squirtle = await pwd.hash(steak)
  40. // console.log('improvedHash', squirtle)
  41. // const saveHash = Auth.insert({user_email:
  42. // matchingEmails}).into('token')
  43. return squirtle
  44. } catch (err) {
  45. console.error(
  46. 'You are authenticated, but we could not improve your safety this time around',
  47. )
  48. }
  49. break
  50. }
  51. }
  52. /** Class for methods used in the User plugin */
  53. module.exports = class UserService extends Schmervice.Service {
  54. /**
  55. * Unsure of what our constructor does
  56. * @param {...any} args
  57. */
  58. constructor(...args) {
  59. super(...args)
  60. const pwd = new SecurePassword()
  61. // TODO: Invalidate this application state somehow after a
  62. // certain time period has passed
  63. this.activeSessions = {
  64. // abc123456: '123456689',
  65. // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...hashedSessionToken: {
  66. // email: rawEmailString,
  67. // name: 'Joe Doe',
  68. // seeking: 'candidate'
  69. // sessionToken: rawSessionToken, // use for expires instead of expires?
  70. // expires: expirationTime in seconds
  71. // }
  72. }
  73. // Check the hashedCookie which is our hashedSessionToken string
  74. // validate whether or not the rawAccessToken is still valid, if valid good to go.
  75. // if NOT valid, then we need to reassign accessToken to a newAccessToken
  76. // this.activeSessions = {
  77. // eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...hashedSessionToken: {
  78. // accessToken: 'as;dflkja;;dlfkja;sldkf... rawAccessToken'
  79. // }
  80. // }
  81. this.pwd = {
  82. hash: Util.promisify(pwd.hash.bind(pwd)),
  83. verify: Util.promisify(pwd.verify.bind(pwd)),
  84. }
  85. }
  86. /**
  87. * Use knex to find users with id column
  88. * @param {number} id
  89. * @param {*} txn
  90. * @returns
  91. */
  92. async findById(id, txn) {
  93. const { User } = this.server.models()
  94. return await User.query(txn)
  95. .throwIfNotFound()
  96. .first()
  97. .where({ user_id: id })
  98. }
  99. /**
  100. * Use knew to find first user with username
  101. * @param {*} username
  102. * @param {*} txn
  103. * @returns
  104. */
  105. async findByUsername(username, txn) {
  106. const { User } = this.server.models()
  107. return await User.query(txn)
  108. .throwIfNotFound()
  109. .first()
  110. .where({ user_name: username })
  111. }
  112. /**
  113. * Use to find first user with useremail
  114. * @param {*} username
  115. * @param {*} txn
  116. * @returns
  117. */
  118. async findByUserEmail(userEmail, txn) {
  119. const { User } = this.server.models()
  120. const user = await User.query(txn)
  121. .throwIfNotFound()
  122. .first()
  123. .where({ user_email: userEmail })
  124. return user
  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. /**
  214. * Validates whether a token has expired or not
  215. * @param {User} user
  216. * @returns {Token}
  217. */
  218. validateToken(token) {
  219. const key = this.server.registrations['main-app-plugin'].options.jwtKey
  220. try {
  221. return JWT.verify(token, key)
  222. } catch (err) {
  223. return { payload: null, message: err.message }
  224. }
  225. }
  226. /**
  227. * Uses this.validateToken() to verify hashedSessionToken's
  228. * existence, expiry, and also valdiates accessToken
  229. * @param {HashedSessionToken} hashedSessionToken
  230. * @returns {PayloadFromActiveSessions}
  231. */
  232. validateSession(hashedAccessToken) {
  233. const userSession = this.activeSessions[hashedAccessToken]
  234. if (!userSession) {
  235. throw new Error(
  236. 'hashedSessionToken not in activeSessions registry!',
  237. )
  238. }
  239. const accessToken = userSession.accessToken
  240. const accessTokenIsValid = this.validateToken(accessToken)
  241. return {
  242. ...accessTokenIsValid.payload,
  243. accessToken: this.activeSessions[hashedAccessToken].accessToken,
  244. }
  245. }
  246. /**
  247. * Use knex to try to change password entry
  248. * @param {number} id
  249. * @param {string} password
  250. * @param {*} txn
  251. * @returns {number}
  252. */
  253. async changePassword(email, password, txn) {
  254. const { Auth } = this.server.models()
  255. const hashed = await this.pwd.hash(
  256. Buffer.from(process.env.PEPPER + password),
  257. )
  258. await Auth.query(txn)
  259. .throwIfNotFound()
  260. .where({ user_email: email })
  261. .patch({
  262. // user_email: email,
  263. token: hashed,
  264. })
  265. return email
  266. }
  267. async getPassword(email, txn) {
  268. const { Auth } = this.server.models()
  269. const passwordRow = await Auth.query(txn)
  270. .where('user_email', email)
  271. .first()
  272. return passwordRow ? passwordRow.token : null
  273. }
  274. /**
  275. * Sends a Transactional Email via Brevo
  276. * @ returns {Object}
  277. */
  278. async emailSent(userCredentials) {
  279. const hashedAccessToken = await hashToken(userCredentials.accessToken)
  280. if (Object.keys(this.activeSessions).includes(hashedAccessToken)) {
  281. return new Error('session already in cache!!')
  282. }
  283. // Set expiration time for ten minutes from now
  284. const duration = 600000
  285. this.activeSessions[hashedAccessToken] = {
  286. email: userCredentials.email,
  287. name: userCredentials.name,
  288. seeking: userCredentials.seeking,
  289. accessToken: userCredentials.accessToken,
  290. expiration: Date.now() + duration,
  291. sessionToken: null,
  292. }
  293. const sendSmtpEmail = {
  294. to: [
  295. {
  296. email: userCredentials.email,
  297. },
  298. ],
  299. templateId: 1,
  300. params: {
  301. // TODO: Change this in production...
  302. link: `localhost:3000/verify/${hashedAccessToken}`,
  303. },
  304. }
  305. return await apiInstance.sendTransacEmail(sendSmtpEmail).then(
  306. data => {
  307. return { wasSuccessfull: true, data: data }
  308. },
  309. error => {
  310. return { wasSuccessfull: false, error: error }
  311. },
  312. )
  313. }
  314. }