user.controller.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. const handleError = require('../utils/handleError')
  2. const response = require('../utils/responseHandler')
  3. const userModel = require('../model/user.model')
  4. const { validate } = require('../utils/validation')
  5. const { notifWA2 } = require('../utils/notifFunction')
  6. const axios = require('../utils/axios')
  7. const { addDokumen } = require('../utils/dokumenFunction')
  8. const jwt = require('jsonwebtoken')
  9. exports.addUserPublic = handleError(async (req, res) => {
  10. const { no_laporan, pt_id, nama, email, no_hp, alamat, is_private } = req.body
  11. const isValid = validate(res, req.body, {
  12. no_laporan: 'string',
  13. pt_id: 'string',
  14. // nama: 'string',
  15. // email: 'email',
  16. no_hp: 'string',
  17. // alamat: 'string',
  18. is_private: { type: 'string', enum: ['true', 'false'] },
  19. })
  20. if (!isValid) return
  21. const no_hp2 =
  22. no_hp.substring(0, 1) === '0' ? '62' + no_hp.substring(1) : no_hp
  23. const pt = await axios.get(
  24. `https://api.kemdikbud.go.id:8243/pddikti/1.2/pt/${pt_id}`
  25. )
  26. if (pt.length === 0)
  27. return response.error(res, {
  28. message: 'pt_id tidak ditemukan',
  29. })
  30. let foto_id = null
  31. const foto = req.file
  32. if (foto) {
  33. foto_id = await addDokumen(foto)
  34. }
  35. const no_verifikasi = Math.floor(Math.random() * 1000000)
  36. let data = {
  37. nama,
  38. email,
  39. no_hp,
  40. alamat,
  41. isPublic: true,
  42. isPrivate: is_private === 'true',
  43. foto: foto_id,
  44. no_verifikasi,
  45. verified: false,
  46. priority: 'low',
  47. }
  48. if (
  49. no_laporan &&
  50. pt_id &&
  51. nama &&
  52. email &&
  53. no_hp &&
  54. alamat &&
  55. is_private &&
  56. foto_id
  57. ) {
  58. data.priority = 'hight'
  59. }
  60. const user = await userModel.create(data)
  61. await notifWA2(
  62. '37a9ccba-e1bc-4d02-86e0-3be4c718af2a',
  63. { nama: nama || 'rahasia', no_hp: no_hp2 },
  64. [
  65. { key: '1', value: 'pt', value_text: pt[0].nama },
  66. { key: '3', value: 'no_verifikasi', value_text: no_verifikasi },
  67. { key: '2', value: 'no_laporan', value_text: no_laporan },
  68. ]
  69. )
  70. const accessToken = jwt.sign(
  71. { _id: user._id, no_laporan },
  72. process.env.SECRET,
  73. {
  74. expiresIn: '30m',
  75. }
  76. )
  77. data = {
  78. token: `Bearer ${accessToken}`,
  79. }
  80. return response.success(res, {
  81. data: data,
  82. message: 'Berhasil menambah user',
  83. })
  84. })
  85. exports.get = handleError((req, res) => {
  86. const user = req.user
  87. return response.success(res, {
  88. message: 'Berhasil mengambil data user',
  89. data: user,
  90. })
  91. })