user.controller.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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 level = 1
  37. if (
  38. no_laporan &&
  39. pt_id &&
  40. nama &&
  41. email &&
  42. no_hp &&
  43. alamat &&
  44. is_private &&
  45. foto_id
  46. ) {
  47. level = 3
  48. }
  49. const user = await userModel.create({
  50. nama,
  51. email,
  52. no_hp,
  53. alamat,
  54. isPublic: true,
  55. isPrivate: is_private === 'true',
  56. foto: foto_id,
  57. no_verifikasi,
  58. verified: false,
  59. })
  60. await notifWA2(
  61. '37a9ccba-e1bc-4d02-86e0-3be4c718af2a',
  62. { nama: nama || 'rahasia', no_hp: no_hp2 },
  63. [
  64. { key: '1', value: 'pt', value_text: pt[0].nama },
  65. { key: '3', value: 'no_verifikasi', value_text: no_verifikasi },
  66. { key: '2', value: 'no_laporan', value_text: no_laporan },
  67. ]
  68. )
  69. const accessToken = jwt.sign(
  70. { _id: user._id, no_laporan, level },
  71. process.env.SECRET,
  72. {
  73. expiresIn: '30m',
  74. }
  75. )
  76. data = {
  77. token: `Bearer ${accessToken}`,
  78. }
  79. return response.success(res, {
  80. data: data,
  81. message: 'Berhasil menambah user',
  82. })
  83. })
  84. exports.get = handleError((req, res) => {
  85. const user = req.user
  86. return response.success(res, {
  87. message: 'Berhasil mengambil data user',
  88. data: user,
  89. })
  90. })