選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

user.js 9.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. 'use strict'
  2. require('dotenv').config()
  3. const crypto = require('crypto')
  4. const Util = require('util')
  5. const Jwt = require('@hapi/jwt')
  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 defaultClient = SibApiV3Sdk.ApiClient.instance
  11. const apiKey = defaultClient.authentications['api-key']
  12. apiKey.apiKey = process.env.BREVO_KEY
  13. const apiInstance = new SibApiV3Sdk.TransactionalEmailsApi()
  14. const hashEmail = async email => {
  15. try {
  16. return crypto.createHmac('sha256', '').update(email).digest('hex')
  17. } catch (err) {
  18. console.error('ERROR :=>', err)
  19. return undefined
  20. }
  21. }
  22. // const emailsSent = {}
  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: matchingEmails}, ).into('token')
  42. return squirtle
  43. } catch (err) {
  44. console.error(
  45. 'You are authenticated, but we could not improve your safety this time around',
  46. )
  47. }
  48. break
  49. }
  50. }
  51. /** Class for methods used in the User plugin */
  52. module.exports = class UserService extends Schmervice.Service {
  53. /**
  54. * Unsure of what our constructor does
  55. * @param {...any} args
  56. */
  57. constructor(...args) {
  58. super(...args)
  59. const pwd = new SecurePassword()
  60. // TODO: Invalidate this cache somehow after a certain time period has
  61. // passed
  62. this.hashedEmails = {
  63. // NOTE: key is email hash and value is timestamp in ms
  64. // abc123456: '123456689',
  65. }
  66. this.pwd = {
  67. hash: Util.promisify(pwd.hash.bind(pwd)),
  68. verify: Util.promisify(pwd.verify.bind(pwd)),
  69. }
  70. }
  71. /**
  72. * Use knex to find users with id column
  73. * @param {number} id
  74. * @param {*} txn
  75. * @returns
  76. */
  77. async findById(id, txn) {
  78. const { User } = this.server.models()
  79. return await User.query(txn)
  80. .throwIfNotFound()
  81. .first()
  82. .where({ user_id: id })
  83. }
  84. /**
  85. * Use knew to find first user with username
  86. * @param {*} username
  87. * @param {*} txn
  88. * @returns
  89. */
  90. async findByUsername(username, txn) {
  91. const { User } = this.server.models()
  92. return await User.query(txn)
  93. .throwIfNotFound()
  94. .first()
  95. .where({ user_name: username })
  96. }
  97. /**
  98. * Signup function
  99. * @param {*} param0
  100. * @param {*} txn
  101. * @returns
  102. */
  103. async signup({ password, userInfo, created_at }, txn) {
  104. const { User, Auth } = this.server.models()
  105. const matchingEmails = await User.query().where(
  106. 'user_email',
  107. userInfo.user_email,
  108. )
  109. if (matchingEmails.length > 0) {
  110. throw `User ${userInfo.user_email} already exists: Cannot create a user without a unique email`
  111. }
  112. // Insert User Info to User table
  113. const insertUser = await User.query().insert(userInfo)
  114. // insert a row with blank password to be updated by changePassword()
  115. await Auth.query().insert({
  116. user_email: insertUser.user_email,
  117. created_at: created_at,
  118. token: null,
  119. })
  120. // update null token with hashed password
  121. await this.changePassword(insertUser.user_email, password, txn)
  122. return {
  123. user_id: insertUser.id,
  124. user_name: insertUser.user_name,
  125. user_email: insertUser.user_email,
  126. is_poster: insertUser.is_poster,
  127. is_admin: insertUser.is_admin,
  128. is_verified: insertUser.is_verified,
  129. }
  130. }
  131. /**
  132. * Updates user's info
  133. * @param {number} id
  134. * @param {*} param1
  135. * @param {*} txn
  136. * @returns
  137. */
  138. async update(id, { password, ...userInfo }, txn) {
  139. const { User } = this.server.models()
  140. if (Object.keys(userInfo).length > 0) {
  141. await User.query(txn)
  142. .throwIfNotFound()
  143. .where({ id })
  144. .patch(userInfo)
  145. }
  146. if (password) {
  147. await this.changePassword(id, password, txn)
  148. }
  149. return id
  150. }
  151. /**
  152. * Self explanatory
  153. * @param {*} param0
  154. * @param {*} txn
  155. * @returns
  156. */
  157. async login({ email, password }, txn) {
  158. const { User, Auth } = this.server.models()
  159. const user = await Auth.query(txn)
  160. .throwIfNotFound()
  161. .first()
  162. .where({ user_email: email })
  163. const bufferPepper = Buffer.from(process.env.PEPPER + password)
  164. /** Uncomment to run password check using SecurePassword */
  165. const passwordCheck = await this.pwd.verify(bufferPepper, user.token)
  166. if (passwordCheck === SecurePassword.VALID_NEEDS_REHASH) {
  167. await this.changePassword(user.user_email, password, txn)
  168. } else if (passwordCheck !== SecurePassword.VALID) {
  169. throw User.createNotFoundError()
  170. }
  171. return user
  172. }
  173. /**
  174. * Create a token to be sent in request headers
  175. * @param {User} user
  176. * @returns {Token}
  177. */
  178. createToken(user) {
  179. const key = this.server.registrations['main-app-plugin'].options.jwtKey
  180. return Jwt.token.generate(
  181. {
  182. aud: 'urn:audience:test',
  183. iss: 'urn:issuer:test',
  184. email: user.email,
  185. name: user.name,
  186. seeking: user.seeking,
  187. },
  188. {
  189. key: key,
  190. algorithm: 'HS256',
  191. },
  192. {
  193. // ttlSec: 4 * 60 * 60, // 7 days
  194. // ttlSec: 60 * 3, // 3 minutes
  195. ttlSec: user.expiration,
  196. },
  197. )
  198. }
  199. /**
  200. * Validates whether a token has expired or not
  201. * @param {User} user
  202. * @returns {Token}
  203. */
  204. validateToken(token) {
  205. const key = this.server.registrations['main-app-plugin'].options.jwtKey
  206. const decodedToken = Jwt.token.decode(token)
  207. console.log('decodedToken :=>', decodedToken)
  208. // NOTE: reveals email...perhaps unhashed email belongs here instead...
  209. try {
  210. Jwt.token.verify(decodedToken, key)
  211. return { isValid: true, payload: decodedToken.decoded.payload }
  212. } catch (err) {
  213. return { isValid: false, error: err.message }
  214. }
  215. }
  216. /**
  217. * Use knex to try to change password entry
  218. * @param {number} id
  219. * @param {string} password
  220. * @param {*} txn
  221. * @returns {number}
  222. */
  223. async changePassword(email, password, txn) {
  224. const { Auth } = this.server.models()
  225. const hashed = await this.pwd.hash(
  226. Buffer.from(process.env.PEPPER + password),
  227. )
  228. await Auth.query(txn)
  229. .throwIfNotFound()
  230. .where({ user_email: email })
  231. .patch({
  232. // user_email: email,
  233. token: hashed,
  234. })
  235. return email
  236. }
  237. async getPassword(email, txn) {
  238. const { Auth } = this.server.models()
  239. const passwordRow = await Auth.query(txn)
  240. .where('user_email', email)
  241. .first()
  242. return passwordRow ? passwordRow.token : null
  243. }
  244. /**
  245. * Sends a Transactional Email via Brevo
  246. * @ returns {Object}
  247. */
  248. async emailSent(userEmail) {
  249. const hashedEmail = await hashEmail(userEmail)
  250. if (Object.keys(this.hashedEmails).includes(hashedEmail)) {
  251. return new Error('email address already in cache!!')
  252. }
  253. // Set expiration time for five minutes from now
  254. const duration = 1000 * 60 * 5
  255. this.hashedEmails[hashedEmail] = Date.now() + duration
  256. const sendSmtpEmail = {
  257. to: [
  258. {
  259. email: userEmail,
  260. },
  261. ],
  262. templateId: 1,
  263. params: {
  264. // TODO: Change this in production...
  265. link: `localhost:3000/verify/${hashedEmail}`,
  266. },
  267. }
  268. await apiInstance.sendTransacEmail(sendSmtpEmail).then(
  269. data => {
  270. return {
  271. wasSuccessfull: true,
  272. data: data,
  273. }
  274. },
  275. error => {
  276. return {
  277. wasSuccessfull: false,
  278. error: error,
  279. }
  280. },
  281. )
  282. }
  283. }