app.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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 server = http.createServer(app);
  13. app.use(cors());
  14. app.use(express.json());
  15. const io = require("socket.io")(server, {
  16. cors: {
  17. origin: "http://localhost:3000" //client endpoint and port
  18. }
  19. });
  20. const randomColor = require('randomcolor');
  21. const PORT = process.env.PORT || 5000;
  22. const TOKEN_KEY = process.env.TOKEN_KEY || 'rGH4r@3DKOg06hgj';
  23. const HASH_KEY = 7;
  24. const generateToken = (id, userName, isAdmin) => {
  25. const payload = {
  26. id,
  27. userName,
  28. isAdmin
  29. }
  30. return jwt.sign(payload, TOKEN_KEY);
  31. }
  32. const isValidUserName = (userName) => {
  33. const nameRegex = /[^A-Za-z0-9]/ ;
  34. return (!nameRegex.test(userName) && userName.trim().length > 2);
  35. }
  36. const getAllDbUsers = async (socket) => {
  37. const usersDb = await User.find({})
  38. socket.emit('allDbUsers', usersDb)
  39. }
  40. const getOneUser = async (userName) => {
  41. const userInDb = await User.findOne({userName});
  42. return userInDb;
  43. }
  44. app.post('/login', async (req, res) => {
  45. try {
  46. const {userName,password} = req.body;
  47. if (!isValidUserName(userName)){
  48. return res.status(400).json({message: 'Invalid username'})
  49. }
  50. const dbUser = await getOneUser(userName)
  51. if (dbUser?.isBanned){
  52. return res.status(401).json({message: 'Your account has been banned!!!'})
  53. }
  54. const hashPassword = await bcrypt.hash(password, HASH_KEY);
  55. if (!dbUser) {
  56. const user = new User({
  57. userName,
  58. hashPassword,
  59. isAdmin: !await User.count().exec(),
  60. isBanned: false,
  61. isMutted: false
  62. });
  63. await user.save()
  64. return res.json({
  65. token: generateToken(user.id, user.userName, user.isAdmin)
  66. });
  67. }
  68. if (dbUser && !bcrypt.compareSync(password, dbUser.hashPassword)){
  69. return res.status(400).json({message: 'Invalid credantials'})
  70. }
  71. res.json({
  72. token: generateToken(dbUser.id, dbUser.userName, dbUser.isAdmin),
  73. })
  74. } catch (e) {
  75. console.log(e);
  76. res.status(500).json({message: `Error ${e}`});
  77. }
  78. })
  79. io.use( async (socket, next) => {
  80. const token = socket.handshake.auth.token;
  81. const sockets = await io.fetchSockets();
  82. if(!token) {
  83. console.log('socket')
  84. socket.disconnect();
  85. return;
  86. }
  87. const usersOnline = [];
  88. sockets.map((sock) => {
  89. usersOnline.push(sock.user);
  90. })
  91. try {
  92. const user = jwt.verify(token, TOKEN_KEY);
  93. const userName = user.userName;
  94. const dbUser = await getOneUser(userName);
  95. if(dbUser.isBanned){
  96. socket.disconnect();
  97. return;
  98. }
  99. socket.user = user;
  100. socket.user.color = randomColor();
  101. const exist = sockets.find((current) => current.user.userName == socket.user.userName)
  102. if(exist) { //&& !user.isAdmin - add for two or more admins
  103. console.log(exist.userName, 'exist twice entering...')
  104. exist.disconnect();
  105. }
  106. } catch(e) {
  107. console.log(e);
  108. socket.disconnect();
  109. }
  110. next();
  111. });
  112. io.on("connection", async (socket) => {
  113. const userName = socket.user.userName;
  114. const sockets = await io.fetchSockets();
  115. const dbUser = await getOneUser(userName);
  116. io.emit('usersOnline', sockets.map((sock) => sock.user)); // send array online users
  117. socket.emit('connected', dbUser); //socket.user
  118. if(socket.user.isAdmin){
  119. getAllDbUsers(socket);
  120. }//sent all users from db to admin
  121. const messagesToShow = await Message.find({}).sort({ 'createDate': -1 }).limit(20);
  122. socket.emit('allmessages', messagesToShow.reverse());
  123. socket.on("message", async (data) => {
  124. const dateNow = Date.now(); // for correct working latest post
  125. const post = await Message.findOne({userName}).sort({ 'createDate': -1 })
  126. const oneUser = await getOneUser(userName);
  127. if(oneUser.isMutted){ //(oneUser.isMutted || !post)
  128. return;
  129. }
  130. if(((Date.now() - Date.parse(post?.createDate)) < 1500)){
  131. console.log((Date.now() - Date.parse(post?.createDate)))// can use to show timer near by button
  132. return;
  133. }
  134. // if(!oneUser.isMutted && post){
  135. // if(((Date.now() - Date.parse(post.createDate)) > 150)){//change later 15000
  136. const message = new Message({
  137. text: data.message,
  138. userName: userName,
  139. createDate: Date.now()
  140. });
  141. try {
  142. await message.save();
  143. } catch (error) {
  144. console.log('Message save to db error', error);
  145. }
  146. // const newMessagesToShow = await Message.find({}).sort({ 'createDate': -1 }).limit(20);
  147. io.emit('newmessage', message);
  148. // }
  149. // }
  150. });
  151. try {
  152. socket.on("disconnect", async () => {
  153. const sockets = await io.fetchSockets();
  154. io.emit('usersOnline', sockets.map((sock) => sock.user));
  155. console.log(`user :${socket.user.userName} , disconnected to socket`);
  156. });
  157. console.log(`user :${socket.user.userName} , connected to socket`);
  158. socket.on("muteUser",async (data) => {
  159. if(!socket.user.isAdmin){
  160. return;
  161. }
  162. // if(socket.user.isAdmin){
  163. const {user, prevStatus} = data;
  164. const sockets = await io.fetchSockets();
  165. const mute = await User.updateOne({userName : user}, {$set: {isMutted :!prevStatus}});
  166. getAllDbUsers(socket);
  167. const exist = sockets.find( current => current.user.userName == user)
  168. const dbUser = await getOneUser(user);
  169. if(exist){
  170. exist.emit('connected', dbUser);
  171. }
  172. // }
  173. });
  174. socket.on("banUser",async (data) => {
  175. if(!socket.user.isAdmin){
  176. return;
  177. }
  178. // if(socket.user.isAdmin) {
  179. const {user, prevStatus} = data;
  180. const sockets = await io.fetchSockets();
  181. const ban = await User.updateOne({userName : user}, {$set: {isBanned:!prevStatus}});
  182. getAllDbUsers(socket)
  183. const exist = sockets.find( current => current.user.userName == user)
  184. if(exist){
  185. exist.emit('ban', "dbUser")
  186. exist.disconnect();
  187. }
  188. // }
  189. });
  190. } catch (e) {
  191. console.log(e);
  192. }
  193. });
  194. //server and database start
  195. const start = async () => {
  196. try {
  197. await mongoose.connect('mongodb://localhost:27017/chat')
  198. .then(() => console.log(`DB started`))
  199. server.listen(PORT, () => {
  200. console.log(`Server started. Port: ${PORT}`);
  201. })
  202. } catch (e) {
  203. console.log(e);
  204. }
  205. }
  206. start();