user.js 6.4 KB

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