app.js 7.4 KB

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