user.js 6.4 KB

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