user.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. const UserModel = require('../model/user');
  2. const ChatModel = require('../model/chat');
  3. const MessageModel = require('../model/message');
  4. const ContactModel = require('../model/contact');
  5. const fs = require('fs').promises;
  6. const Jimp = require('jimp');
  7. const path = require('path');
  8. const jwt = require('jsonwebtoken');
  9. const createFolderIsExist = require('../helpers/create-directory');
  10. require('dotenv').config();
  11. const s3 = require('../helpers/aws');
  12. const client = require('../helpers/twilio');
  13. const phoneToken = require('generate-sms-verification-code');
  14. const SECRET_KEY = process.env.JWT_SECRET;
  15. const AWS_BUCKET_NAME = process.env.AWS_BUCKET_NAME;
  16. const createNewUser = async (req, res, next) => {
  17. try {
  18. const code = phoneToken(4, { type: 'number' });
  19. const color = `#${Math.floor(Math.random() * 16777215).toString(16)}`;
  20. const { number, country } = req.body;
  21. const isExist = await UserModel.findByNumber(number);
  22. if (isExist) {
  23. await UserModel.updateUser(isExist._id, { code });
  24. } else {
  25. await UserModel.createUser({ number, country, color, code });
  26. }
  27. client.messages.create({
  28. body: `${code}`,
  29. to: `${number}`,
  30. from: '+18305875860',
  31. });
  32. return res.status(201).json({
  33. status: 'success',
  34. code: 201,
  35. data: String(code),
  36. });
  37. } catch (e) {
  38. next(e);
  39. }
  40. };
  41. const logIn = async (req, res, next) => {
  42. try {
  43. const { number, code } = req.body;
  44. const user = await UserModel.findByNumber(number);
  45. if (!user || user.code !== code)
  46. return res.status(401).json({
  47. status: 'error',
  48. code: 401,
  49. data: 'UNAUTHORIZED',
  50. message: 'Invalid credentials',
  51. });
  52. const id = user._id;
  53. const payload = { id };
  54. const token = jwt.sign(payload, SECRET_KEY, { expiresIn: '24h' });
  55. let registered = true;
  56. if (!user.originalName || !user.originalLastName) registered = false;
  57. const online = true;
  58. await UserModel.updateUser(id, { token, code: '', online });
  59. await ChatModel.updateCompanionsChat(id, { online });
  60. return res.status(200).json({
  61. status: 'success',
  62. code: 200,
  63. data: {
  64. token,
  65. registered,
  66. },
  67. });
  68. } catch (e) {
  69. next(e);
  70. }
  71. };
  72. const logOut = async (req, res, next) => {
  73. try {
  74. const id = req.user.id;
  75. const user = await UserModel.findById(id);
  76. const online = new Date();
  77. if (!user)
  78. return res.status(401).json({
  79. status: 'error',
  80. code: 401,
  81. data: 'UNAUTHORIZED',
  82. message: 'Invalid credentials',
  83. });
  84. await UserModel.updateUser(id, { token: null, online });
  85. await ChatModel.updateCompanionsChat(id, { online });
  86. return res.status(204).json({});
  87. } catch (e) {
  88. next(e);
  89. }
  90. };
  91. const online = async (req, res, next) => {
  92. try {
  93. const id = req.user.id;
  94. const user = await UserModel.findById(id);
  95. const online = new Date();
  96. if (!user)
  97. return res.status(401).json({
  98. status: 'error',
  99. code: 401,
  100. data: 'UNAUTHORIZED',
  101. message: 'Invalid credentials',
  102. });
  103. await ChatModel.updateCompanionsChat(id, { online });
  104. await UserModel.updateUser(id, { online });
  105. return res.status(204).json({});
  106. } catch (e) {
  107. next(e);
  108. }
  109. };
  110. const getCurrent = async (req, res, next) => {
  111. try {
  112. const user = req.user;
  113. if (!user)
  114. return res.status(401).json({
  115. status: 'error',
  116. code: 401,
  117. data: 'UNAUTHORIZED',
  118. message: 'Invalid credentials',
  119. });
  120. const id = req.user.id;
  121. const online = true;
  122. await UserModel.updateUser(id, { online });
  123. await ChatModel.updateCompanionsChat(id, { online });
  124. const updatedUser = await UserModel.findById(id);
  125. return res.status(200).json({
  126. status: 'success',
  127. code: 200,
  128. data: updatedUser,
  129. });
  130. } catch (e) {
  131. next(e);
  132. }
  133. };
  134. const updateCredentials = async (req, res, next) => {
  135. try {
  136. const user = req.user;
  137. const { id, token } = user;
  138. const { name, lastName, originalName, originalLastName } = req.body;
  139. await UserModel.updateUser(id, req.body);
  140. await ChatModel.updateCompanionsChat(id, {
  141. originalName,
  142. originalLastName,
  143. });
  144. await MessageModel.updateOwnerMessages(
  145. { companionIdFlow: { $eq: id }, owner: id },
  146. { name, lastName }
  147. );
  148. await MessageModel.updateOwnerMessages(
  149. {
  150. replyName: { $eq: user.name },
  151. replyLastName: { $eq: user.lastName },
  152. owner: id,
  153. },
  154. { replyName: name, replyLastName: lastName }
  155. );
  156. return res.status(200).json({
  157. data: {
  158. token,
  159. },
  160. });
  161. } catch (e) {
  162. next(e);
  163. }
  164. };
  165. const updateUser = async (req, res, next) => {
  166. try {
  167. const { id } = req.user;
  168. await UserModel.updateUser(id, req.body);
  169. return res.status(200).json({
  170. data: {},
  171. });
  172. } catch (e) {
  173. next(e);
  174. }
  175. };
  176. const removeAvatar = async (req, res, next) => {
  177. try {
  178. const { id, avatarsArr, number } = req.user;
  179. const index = Number(req.params.index);
  180. const toDelete = avatarsArr[index];
  181. let filteredAvatars;
  182. let avatarUrl;
  183. if (index === 0 && avatarsArr.length === 1) {
  184. filteredAvatars = [];
  185. avatarUrl = null;
  186. } else if (index >= 0 && avatarsArr.length > 1) {
  187. filteredAvatars = [...avatarsArr].filter(
  188. ({ avatarUrl }) => avatarUrl !== toDelete.avatarUrl
  189. );
  190. avatarUrl = filteredAvatars[0].avatarUrl;
  191. }
  192. const params = {
  193. Bucket: AWS_BUCKET_NAME,
  194. Key: `${toDelete.avatarUrl}`,
  195. };
  196. s3.deleteObject(params, async function (err, _data) {
  197. if (err) throw err;
  198. });
  199. await UserModel.updateUser(id, {
  200. avatarUrl,
  201. avatarsArr: filteredAvatars,
  202. });
  203. await ChatModel.updateCompanionsChat(id, {
  204. avatarUrl,
  205. avatarsArr: filteredAvatars,
  206. });
  207. await ContactModel.updateCompanionsContact(number, { avatarUrl });
  208. await MessageModel.updateOwnerMessages(
  209. { companionIdFlow: { $eq: id } },
  210. { avatarUrl }
  211. );
  212. return res.status(200).json({
  213. data: {},
  214. });
  215. } catch (e) {
  216. next(e);
  217. }
  218. };
  219. const updateAvatar = async (req, res, next) => {
  220. try {
  221. const userId = req.user.id;
  222. const userNumber = req.user.number;
  223. const pathToFile = req.file.path;
  224. const originalName = req.file.originalname;
  225. const avatarUrl = `${Math.round(
  226. Date.now() / 1000
  227. )}${userId}${originalName}`;
  228. const cropImg = await Jimp.read(pathToFile);
  229. await cropImg
  230. .autocrop()
  231. .cover(
  232. 250,
  233. 250,
  234. Jimp.HORIZONTAL_ALIGN_CENTER | Jimp.VERTICAL_ALIGN_MIDDLE
  235. )
  236. .writeAsync(pathToFile);
  237. const fileContent = await fs.readFile(pathToFile);
  238. const params = {
  239. Bucket: AWS_BUCKET_NAME,
  240. Key: `${avatarUrl}`,
  241. Body: fileContent,
  242. };
  243. s3.upload(params, async (err, _data) => {
  244. if (err) throw err;
  245. fs.unlink(pathToFile);
  246. });
  247. const avatarsArr = [
  248. { avatarUrl, updatedAt: new Date() },
  249. ...req.user.avatarsArr,
  250. ];
  251. await UserModel.updateUser(userId, { avatarUrl, avatarsArr });
  252. await ChatModel.updateCompanionsChat(userId, { avatarUrl, avatarsArr });
  253. await ContactModel.updateCompanionsContact(userNumber, { avatarUrl });
  254. await MessageModel.updateOwnerMessages(
  255. { companionIdFlow: { $eq: userId } },
  256. { avatarUrl }
  257. );
  258. return res.status(200).json({
  259. status: 'success',
  260. code: 200,
  261. data: {},
  262. });
  263. } catch (e) {
  264. next(e);
  265. }
  266. };
  267. module.exports = {
  268. createNewUser,
  269. logIn,
  270. logOut,
  271. online,
  272. getCurrent,
  273. updateCredentials,
  274. updateUser,
  275. removeAvatar,
  276. updateAvatar,
  277. };