Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. 'use strict';
  2. const Util = require('util');
  3. const Jwt = require('@hapi/jwt');
  4. const Schmervice = require('@hapipal/schmervice');
  5. const SecurePassword = require('secure-password');
  6. module.exports = class UserService extends Schmervice.Service {
  7. constructor(...args) {
  8. super(...args)
  9. const pwd = new SecurePassword()
  10. this.pwd = {
  11. hash: Util.promisify(pwd.hash.bind(pwd)),
  12. verify: Util.promisify(pwd.verify.bind(pwd))
  13. }
  14. }
  15. async findById(id, txn) {
  16. const { User } = this.server.models()
  17. return await User.query(txn).throwIfNotFound().findById(id)
  18. }
  19. async findByUsername(username, txn) {
  20. const { User } = this.server.models()
  21. return await User.query(txn).throwIfNotFound().first().where({ username })
  22. }
  23. async signup({ password, ...userInfo }, txn) {
  24. const { User } = this.server.models()
  25. const { id } = await User.query(txn).insert(userInfo)
  26. await this.changePassword(id, password, txn)
  27. return id
  28. }
  29. async update(id, { password, ...userInfo }, txn) {
  30. const { User } = this.server.models()
  31. if (Object.keys(userInfo).length > 0) {
  32. await User.query(txn).throwIfNotFound().where({ id }).patch(userInfo)
  33. }
  34. if (password) {
  35. await this.changePassword(id, password, txn)
  36. }
  37. return id
  38. }
  39. async login({ email, password }, txn) {
  40. const { User } = this.server.models()
  41. const user = await User.query(txn)
  42. .throwIfNotFound()
  43. .first()
  44. .where({ user_email: email })
  45. // Uncomment to run password check using SecurePassword
  46. // const passwordCheck = await this.pwd.verify(Buffer.from(password), user.password)
  47. // if (passwordCheck === SecurePassword.VALID_NEEDS_REHASH) {
  48. // await this.changePassword(user.id, password, txn)
  49. // }
  50. // else if (passwordCheck !== SecurePassword.VALID) {
  51. // throw User.createNotFoundError()
  52. // }
  53. return user
  54. }
  55. createToken(user) {
  56. const key = this.server.registrations['main-app-plugin'].options.jwtKey
  57. return Jwt.token.generate({
  58. aud: 'urn:audience:test',
  59. iss: 'urn:issuer:test',
  60. email: user.user_email
  61. },
  62. {
  63. key: key,
  64. algorithm: 'HS256'
  65. }, {
  66. ttlSec: 4 * 60 * 60 // 7 days
  67. })
  68. }
  69. async changePassword(id, password, txn) {
  70. const { User } = this.server.models()
  71. await User.query(txn).throwIfNotFound().where({ id }).patch({
  72. password: await this.pwd.hash(Buffer.from(password))
  73. })
  74. return id
  75. }
  76. }