user.service.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // ./api/users/user.service.js
  2. import bcrypt from "bcrypt";
  3. import { v4 as uuidv4 } from "uuid";
  4. import BaseService from "../../services/base.service.js";
  5. import EmailService from "../emails/email.service.js";
  6. import User from "./user.model.js";
  7. class UsersService extends BaseService {
  8. getModel() {
  9. return User;
  10. }
  11. async update(id, accountId, data) {
  12. return this.getModel().findOneAndUpdate(
  13. { _id: id, accountId: accountId },
  14. data,
  15. { new: true }
  16. );
  17. }
  18. async delete(id, accountId) {
  19. return this.getModel().findOneAndDelete({ _id: id, accountId: accountId });
  20. }
  21. async create(data, sendConfirm = false) {
  22. // const sendForgot = false
  23. // const sendConfirm = false
  24. // if (data.password && data.password !== '') {
  25. // const salt = bcrypt.genSaltSync(10)
  26. // const hash = bcrypt.hashSync(data.password, salt)
  27. // data.password = hash
  28. // } else {
  29. // data.passwordResetToken = (Math.floor(100000 + Math.random() * 900000)).toString()
  30. // data.passwordResetExpires = new Date(Date.now() + 3600000)
  31. // sendForgot = true
  32. // }
  33. if (sendConfirm) {
  34. data.confirmationToken = Math.floor(
  35. 100000 + Math.random() * 900000
  36. ).toString();
  37. } else {
  38. data.active = true;
  39. }
  40. if (data.password && data.password !== "") {
  41. const salt = bcrypt.genSaltSync(10);
  42. const hash = bcrypt.hashSync(data.password, salt);
  43. data.password = hash;
  44. } else {
  45. data.password = "justaplaceholder";
  46. }
  47. data.sso = uuidv4();
  48. const user = new User(data);
  49. await user.save();
  50. // if (sendForgot) {
  51. // EmailService.forgotPasswordLink(data)
  52. // }
  53. if (sendConfirm) {
  54. EmailService.sendActivationEmail(data);
  55. }
  56. EmailService.activated(data);
  57. return user.toObject();
  58. }
  59. async updatePassword(userId, password) {
  60. const user = await this.byId(userId, {});
  61. const salt = bcrypt.genSaltSync(10);
  62. const hash = bcrypt.hashSync(password, salt);
  63. user.password = hash;
  64. await user.save();
  65. }
  66. }
  67. export default new UsersService();