user.js 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. const UserModel = require('../model/user');
  2. const ChatModel = require('../model/chat');
  3. const fs = require('fs').promises;
  4. const path = require('path');
  5. const Jimp = require('jimp');
  6. const jwt = require('jsonwebtoken');
  7. const createFolderIsExist = require('../helpers/create-directory');
  8. require('dotenv').config();
  9. const client = require('../helpers/twilio');
  10. const phoneToken = require('generate-sms-verification-code');
  11. const SECRET_KEY = process.env.JWT_SECRET;
  12. const createNewUser = async (req, res, next) => {
  13. try {
  14. const code = phoneToken(4, { type: 'number' });
  15. const color = `#${Math.floor(Math.random() * 16777215).toString(16)}`;
  16. const { number, country } = req.body;
  17. const isExist = await UserModel.findByNumber(number);
  18. if (isExist) {
  19. await UserModel.updateUser(isExist._id, { code });
  20. } else {
  21. await UserModel.createUser({ number, country, color, code });
  22. }
  23. client.messages.create({
  24. body: `${code}`,
  25. to: `${number}`,
  26. from: '+18305875860',
  27. });
  28. return res.status(201).json({
  29. status: 'success',
  30. code: 201,
  31. data: String(code),
  32. });
  33. } catch (e) {
  34. next(e);
  35. }
  36. };
  37. const logIn = async (req, res, next) => {
  38. try {
  39. const { number, code } = req.body;
  40. const user = await UserModel.findByNumber(number);
  41. if (!user || user.code !== code)
  42. return res.status(401).json({
  43. status: 'error',
  44. code: 401,
  45. data: 'UNAUTHORIZED',
  46. message: 'Invalid credentials',
  47. });
  48. const id = user._id;
  49. const payload = { id };
  50. const token = jwt.sign(payload, SECRET_KEY, { expiresIn: '24h' });
  51. let registered = true;
  52. if (!user.name || !user.lastName || !user.avatarUrl) registered = false;
  53. const online = true;
  54. await UserModel.updateUser(id, { token, code: '', online });
  55. await ChatModel.updateCompanionsChat(id, online);
  56. return res.status(200).json({
  57. status: 'success',
  58. code: 200,
  59. data: {
  60. token,
  61. registered,
  62. },
  63. });
  64. } catch (e) {
  65. next(e);
  66. }
  67. };
  68. const logOut = async (req, res, next) => {
  69. try {
  70. const id = req.user.id;
  71. const user = await UserModel.findById(id);
  72. const online = new Date();
  73. if (!user)
  74. return res.status(401).json({
  75. status: 'error',
  76. code: 401,
  77. data: 'UNAUTHORIZED',
  78. message: 'Invalid credentials',
  79. });
  80. await UserModel.updateUser(id, { token: null, online });
  81. await ChatModel.updateCompanionsChat(id, online);
  82. return res.status(204).json({});
  83. } catch (e) {
  84. next(e);
  85. }
  86. };
  87. const online = async (req, res, next) => {
  88. try {
  89. const id = req.user.id;
  90. const user = await UserModel.findById(id);
  91. const online = new Date();
  92. if (!user)
  93. return res.status(401).json({
  94. status: 'error',
  95. code: 401,
  96. data: 'UNAUTHORIZED',
  97. message: 'Invalid credentials',
  98. });
  99. await ChatModel.updateCompanionsChat(id, online);
  100. await UserModel.updateUser(id, { online });
  101. return res.status(204).json({});
  102. } catch (e) {
  103. next(e);
  104. }
  105. };
  106. const getCurrent = async (req, res, next) => {
  107. try {
  108. const user = req.user;
  109. if (!user)
  110. return res.status(401).json({
  111. status: 'error',
  112. code: 401,
  113. data: 'UNAUTHORIZED',
  114. message: 'Invalid credentials',
  115. });
  116. const id = req.user.id;
  117. const online = true;
  118. await UserModel.updateUser(id, { online });
  119. await ChatModel.updateCompanionsChat(id, online);
  120. const updatedUser = await UserModel.findById(id);
  121. return res.status(200).json({
  122. status: 'success',
  123. code: 200,
  124. data: updatedUser,
  125. });
  126. } catch (e) {
  127. next(e);
  128. }
  129. };
  130. const updateCredentials = async (req, res, next) => {
  131. try {
  132. const { id } = req.user;
  133. await UserModel.updateUser(id, req.body);
  134. return res.status(200).json({
  135. data: {},
  136. });
  137. } catch (e) {
  138. next(e);
  139. }
  140. };
  141. const updateAvatar = async (req, res, next) => {
  142. try {
  143. const userId = req.user.id;
  144. const token = req.user.token;
  145. const DIR_IMAGES = process.env.DIR_IMAGES;
  146. const pathToFile = req.file.path;
  147. const originalName = req.file.originalname;
  148. const newNameAvatar = `${Math.round(Date.now() / 1000)}${originalName}`;
  149. const img = await Jimp.read(pathToFile);
  150. await img
  151. .autocrop()
  152. .cover(
  153. 250,
  154. 250,
  155. Jimp.HORIZONTAL_ALIGN_CENTER | Jimp.VERTICAL_ALIGN_MIDDLE
  156. )
  157. .writeAsync(pathToFile);
  158. await createFolderIsExist(path.join(DIR_IMAGES, userId));
  159. await fs.rename(pathToFile, path.join(DIR_IMAGES, userId, newNameAvatar));
  160. const avatarUrl = path.normalize(path.join(userId, newNameAvatar));
  161. const avatarsArr = [
  162. { avatarUrl, updatedAt: new Date() },
  163. ...req.user.avatarsArr,
  164. ];
  165. await UserModel.updateUser(userId, { avatarUrl, avatarsArr });
  166. return res.status(200).json({
  167. status: 'success',
  168. code: 200,
  169. data: {
  170. token,
  171. },
  172. });
  173. } catch (e) {
  174. next(e);
  175. }
  176. };
  177. module.exports = {
  178. createNewUser,
  179. logIn,
  180. logOut,
  181. online,
  182. getCurrent,
  183. updateCredentials,
  184. updateAvatar,
  185. };