app.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. const express = require('express');
  2. const app = express()
  3. const cors = require("cors");
  4. const http = require('http'); //create new http
  5. const mongoose = require('mongoose');
  6. const socket = require("socket.io");
  7. const User = require('./db/models/User');
  8. const Message = require('./db/models/Message');
  9. const jwt = require('jsonwebtoken');
  10. const bcrypt = require('bcrypt');
  11. require('dotenv').config(); // add dotnv for config
  12. const Uuid = require('uuid'); //lib for unic id generate
  13. const fileupload = require('express-fileupload');
  14. const fs = require('fs');
  15. const server = http.createServer(app);
  16. app.use(cors());
  17. app.use(express.json());
  18. app.use(fileupload())
  19. app.use(express.static('avatars')); //folder for static files
  20. const io = require("socket.io")(server, {
  21. cors: {
  22. origin: "http://localhost:3000" //client endpoint and port
  23. }
  24. });
  25. const PORT = process.env.PORT || 5000;
  26. const TOKEN_KEY = process.env.TOKEN_KEY || 'rGH4r@3DKOg06hgj';
  27. const HASH_KEY = 7;
  28. const STATIC_PATH = process.env. STATIC_PATH || 'avatars';
  29. const generateToken = (id, userName, isAdmin) => {
  30. const payload = {
  31. id,
  32. userName,
  33. isAdmin
  34. }
  35. return jwt.sign(payload, TOKEN_KEY);
  36. }
  37. const isValidUserName = (userName) => {
  38. const nameRegex = /[^A-Za-z0-9]/ ;
  39. return (!nameRegex.test(userName) && userName.trim().length > 2);
  40. }
  41. const getAllDbUsers = async (socket) => {
  42. const usersDb = await User.find({})
  43. socket.emit('allDbUsers', usersDb)
  44. }
  45. const getOneUser = async (userName) => {
  46. const userInDb = await User.findOne({userName});
  47. return userInDb;
  48. }
  49. app.post('/login', async (req, res) => {
  50. try {
  51. const {userName,password} = req.body;
  52. if (!isValidUserName(userName)){
  53. return res.status(400).json({message: 'Invalid username'})
  54. }
  55. const dbUser = await getOneUser(userName)
  56. if (dbUser?.isBanned){
  57. return res.status(401).json({message: 'Your account has been banned!!!'})
  58. }
  59. const hashPassword = await bcrypt.hash(password, HASH_KEY);
  60. if (!dbUser) {
  61. const user = new User({
  62. userName,
  63. hashPassword,
  64. isAdmin: !await User.count().exec(),
  65. isBanned: false,
  66. isMutted: false,
  67. avatar: '',
  68. messages: []
  69. });
  70. await user.save()
  71. return res.json({
  72. token: generateToken(user.id, user.userName, user.isAdmin)
  73. });
  74. }
  75. if (dbUser && !bcrypt.compareSync(password, dbUser.hashPassword)){
  76. return res.status(400).json({message: 'Invalid credantials'})
  77. }
  78. res.json({
  79. token: generateToken(dbUser.id, dbUser.userName, dbUser.isAdmin),
  80. })
  81. } catch (e) {
  82. console.log(e);
  83. res.status(500).json({message: `Error ${e}`});
  84. }
  85. })
  86. app.post('/avatar', async (req, res) => {
  87. if (!req.files || Object.keys(req.files).length === 0) {
  88. return res.status(400).json('No files were uploaded.');
  89. }
  90. try {
  91. const file = req.files.file;
  92. const user = jwt.verify(req.body.token, TOKEN_KEY);
  93. const avatarFileName = Uuid.v4() + '.jpeg';
  94. file.mv(STATIC_PATH + '\/' + avatarFileName)
  95. const userFromDb = await getOneUser(user.userName);
  96. if(userFromDb.avatar){
  97. const oldAvatar = userFromDb.avatar;
  98. fs.unlinkSync(STATIC_PATH + '\/' + oldAvatar)
  99. }
  100. await User.findOneAndUpdate({userName: user.userName},{ $set: {'avatar': avatarFileName}}, {
  101. new: true
  102. });
  103. return res.json({ message:'Avatar was uploud succesfully...', avatarUrl: avatarFileName})
  104. } catch (error) {
  105. res.status(500).json({message: `Error uppload file to serverp: ${error}`});
  106. }
  107. })
  108. app.post('/files', async (req, res) => {
  109. if (!req.files || Object.keys(req.files).length === 0) {
  110. return res.status(400).json('No files were uploaded.');
  111. }
  112. const user = jwt.verify(req.body.token, TOKEN_KEY);
  113. const oneUser = await getOneUser(user.userName);
  114. if(oneUser.isMutted){
  115. return;
  116. }
  117. const files = req.files.files;
  118. if (files.length) {
  119. for (let i = 0; i < files.length; i++) {
  120. let file = files[i]
  121. file.mv(STATIC_PATH + '\/' + file.name)
  122. const message = new Message({
  123. text: file.name,
  124. userName: user.userName,
  125. createDate: Date.now(),
  126. user: oneUser.id, //add link to other collection by id
  127. file: file.name,
  128. fileType: file.mimetype
  129. });
  130. try {
  131. await message.save();
  132. if(!oneUser.messages){
  133. await oneUser.update({ $set: {'messages': []}});
  134. }
  135. await oneUser.messages.push(message)
  136. await oneUser.save()
  137. }
  138. catch (error) {
  139. console.log('Message save to db error', error);
  140. }
  141. const newMessages = await message.populate( {path:'user'})
  142. io.emit('newmessage', newMessages);
  143. }}
  144. else {
  145. if (files.name == 'blob') {
  146. files.name = Uuid.v4() + '.jpeg'
  147. }
  148. files.mv(STATIC_PATH + '\/' + files.name); //for one file
  149. const message = new Message({
  150. text: files.name,
  151. userName: user.userName,
  152. createDate: Date.now(),
  153. user: oneUser.id, //add link to other collection by id
  154. file: files.name,
  155. fileType: files.mimetype
  156. });
  157. try {
  158. await message.save();
  159. if(!oneUser.messages){
  160. await oneUser.update({ $set: {'messages': []}});
  161. }
  162. await oneUser.messages.push(message)
  163. await oneUser.save()
  164. }
  165. catch (error) {
  166. console.log('Message save to db error', error);
  167. }
  168. const newMessages = await message.populate( {path:'user'})
  169. io.emit('newmessage', newMessages);
  170. }
  171. return res.json({ message:'File was uploud succesfully...'})
  172. })
  173. io.use( async (socket, next) => {
  174. const token = socket.handshake.auth.token;
  175. const sockets = await io.fetchSockets();
  176. if(!token) {
  177. console.log('socket')
  178. socket.disconnect();
  179. return;
  180. }
  181. const usersOnline = [];
  182. sockets.map((sock) => {
  183. usersOnline.push(sock.user);
  184. })
  185. try {
  186. const user = jwt.verify(token, TOKEN_KEY);
  187. const userName = user.userName;
  188. const dbUser = await getOneUser(userName);
  189. if(dbUser.isBanned){
  190. socket.disconnect();
  191. return;
  192. }
  193. socket.user = user;
  194. const exist = sockets.find((current) => current.user.userName == socket.user.userName)
  195. if(exist) { //&& !user.isAdmin - add for two or more admins
  196. console.log(exist.userName, 'exist twice entering...')
  197. exist.disconnect();
  198. }
  199. } catch(e) {
  200. console.log(e);
  201. socket.disconnect();
  202. }
  203. next();
  204. });
  205. io.on("connection", async (socket) => {
  206. const userName = socket.user.userName;
  207. const sockets = await io.fetchSockets();
  208. const dbUser = await getOneUser(userName);
  209. io.emit('usersOnline', sockets.map(sock => sock.user)); // send array online users
  210. socket.emit('connected', dbUser); //socket.user
  211. if(socket.user.isAdmin){
  212. getAllDbUsers(socket);
  213. }//sent all users from db to admin
  214. const messagesToShow = await Message.find({}).sort({ 'createDate': -1 }).limit(20).populate( {path:'user'});
  215. socket.emit('allmessages', messagesToShow.reverse());
  216. socket.on("message", async (data) => {
  217. const dateNow = Date.now(); // for correct working latest post
  218. const post = await Message.findOne({userName}).sort({ 'createDate': -1 })
  219. const oneUser = await getOneUser(userName);
  220. if(oneUser.isMutted){ //(oneUser.isMutted || !post)
  221. return;
  222. }
  223. if(((Date.now() - Date.parse(post?.createDate)) < 1500)){
  224. console.log((Date.now() - Date.parse(post?.createDate)))// can use to show timer near by button
  225. return;
  226. }
  227. // if(!oneUser.isMutted && post){
  228. // if(((Date.now() - Date.parse(post.createDate)) > 150)){//change later 15000
  229. const message = new Message({
  230. text: data.message,
  231. userName: userName,
  232. createDate: Date.now(),
  233. user: oneUser.id, //add link to other collection by id
  234. });
  235. try {
  236. await message.save();
  237. if(!oneUser.messages){
  238. await oneUser.update({ $set: {'messages': []}});
  239. }
  240. await oneUser.messages.push(message)
  241. await oneUser.save()
  242. } catch (error) {
  243. console.log('Message save to db error', error);
  244. }
  245. const newMessages = await message.populate( {path:'user'})
  246. io.emit('newmessage', newMessages);
  247. // }
  248. // }
  249. });
  250. try {
  251. socket.on("disconnect", async () => {
  252. const sockets = await io.fetchSockets();
  253. io.emit('usersOnline', sockets.map(sock => sock.user));
  254. console.log(`user :${socket.user.userName} , disconnected to socket`);
  255. });
  256. console.log(`user :${socket.user.userName} , connected to socket`);
  257. socket.on("muteUser",async (data) => {
  258. if(!socket.user.isAdmin){
  259. return;
  260. }
  261. // if(socket.user.isAdmin){
  262. const {user, prevStatus} = data;
  263. const sockets = await io.fetchSockets();
  264. const mute = await User.updateOne({userName : user}, {$set: {isMutted :!prevStatus}});
  265. getAllDbUsers(socket);
  266. const exist = sockets.find( current => current.user.userName == user)
  267. const dbUser = await getOneUser(user);
  268. if(exist){
  269. exist.emit('connected', dbUser);
  270. }
  271. // }
  272. });
  273. socket.on("banUser",async (data) => {
  274. if(!socket.user.isAdmin){
  275. return;
  276. }
  277. // if(socket.user.isAdmin) {
  278. const {user, prevStatus} = data;
  279. const sockets = await io.fetchSockets();
  280. const ban = await User.updateOne({userName : user}, {$set: {isBanned:!prevStatus}});
  281. getAllDbUsers(socket)
  282. const exist = sockets.find( current => current.user.userName == user)
  283. if(exist){
  284. exist.emit('ban', "dbUser")
  285. exist.disconnect();
  286. }
  287. // }
  288. });
  289. socket.on('userWriting', async () => {
  290. let isTyping = true;
  291. io.emit('writing', {userName, isTyping})
  292. })
  293. } catch (e) {
  294. console.log(e);
  295. }
  296. });
  297. //server and database start
  298. const start = async () => {
  299. try {
  300. await mongoose.connect('mongodb://localhost:27017/chat')
  301. .then(() => console.log(`DB started`))
  302. server.listen(PORT, () => {
  303. console.log(`Server started. Port: ${PORT}`);
  304. })
  305. } catch (e) {
  306. console.log(e);
  307. }
  308. }
  309. start();