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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. /**
  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. if (!userSession.emailWasRespondedTo) {
  240. throw new Error('email was never responded to!')
  241. }
  242. const accessToken = userSession.accessToken
  243. const accessTokenIsValid = this.validateToken(accessToken)
  244. return {
  245. ...accessTokenIsValid.payload,
  246. accessToken: this.activeSessions[hashedAccessToken].accessToken,
  247. }
  248. }
  249. removeSession(hashedAccessToken) {
  250. const userSession = this.activeSessions[hashedAccessToken]
  251. if (!userSession) {
  252. throw new Error(
  253. 'hashedSessionToken not in activeSessions registry!',
  254. )
  255. } else {
  256. delete this.activeSessions[hashedAccessToken]
  257. }
  258. }
  259. /**
  260. * Use knex to try to change password entry
  261. * @param {number} id
  262. * @param {string} password
  263. * @param {*} txn
  264. * @returns {number}
  265. */
  266. async changePassword(email, password, txn) {
  267. const { Auth } = this.server.models()
  268. const hashed = await this.pwd.hash(
  269. Buffer.from(process.env.PEPPER + password),
  270. )
  271. await Auth.query(txn)
  272. .throwIfNotFound()
  273. .where({ user_email: email })
  274. .patch({
  275. // user_email: email,
  276. token: hashed,
  277. })
  278. return email
  279. }
  280. async getPassword(email, txn) {
  281. const { Auth } = this.server.models()
  282. const passwordRow = await Auth.query(txn)
  283. .where('user_email', email)
  284. .first()
  285. return passwordRow ? passwordRow.token : null
  286. }
  287. /**
  288. * Sends a Transactional Email via Brevo
  289. * @ returns {Object}
  290. */
  291. async emailSent(userCredentials) {
  292. const hashedAccessToken = await this.hashToken(
  293. userCredentials.accessToken,
  294. )
  295. if (Object.keys(this.activeSessions).includes(hashedAccessToken)) {
  296. return new Error('session already in cache!!')
  297. }
  298. // Set expiration time for ten minutes from now
  299. const duration = 600000
  300. this.activeSessions[hashedAccessToken] = {
  301. email: userCredentials.email,
  302. name: userCredentials.name,
  303. seeking: userCredentials.seeking,
  304. accessToken: userCredentials.accessToken,
  305. expiration: Date.now() + duration,
  306. emailWasRespondedTo: false,
  307. sessionToken: null,
  308. }
  309. const sendSmtpEmail = {
  310. to: [
  311. {
  312. email: userCredentials.email,
  313. },
  314. ],
  315. templateId: 1,
  316. params: {
  317. // TODO: Change this in production...
  318. link: `localhost:3000/verify/${hashedAccessToken}`,
  319. },
  320. }
  321. return await apiInstance.sendTransacEmail(sendSmtpEmail).then(
  322. data => {
  323. return { wasSuccessfull: true, data: data }
  324. },
  325. error => {
  326. return { wasSuccessfull: false, error: error }
  327. },
  328. )
  329. }
  330. }