service-privateroom
This commit is contained in:
parent
bc6aa6dd28
commit
c00d9ba51d
8 changed files with 264 additions and 0 deletions
28
backend/service-privateroom/auth.js
Normal file
28
backend/service-privateroom/auth.js
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
const request = require('request');
|
||||
|
||||
function getSession (req, callback) {
|
||||
if(typeof req.headers.cookie !== 'undefined'){
|
||||
request.post({
|
||||
headers: {'content-type' : 'application/x-www-form-urlencoded'},
|
||||
url: 'http://127.0.0.1:3000/verify:token',
|
||||
body: 'sessionid='+req.headers.cookie.replace('SESSIONID=','')
|
||||
},function (error, response, body) {
|
||||
const bodyJson = JSON.parse(body);
|
||||
if (bodyJson && bodyJson.status && bodyJson.data) {
|
||||
if (bodyJson.status === 'ok') {
|
||||
return callback(bodyJson.data.token);
|
||||
} else {
|
||||
return callback(bodyJson.data.reason);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
return callback(undefined);
|
||||
}
|
||||
module.exports.getSession = getSession;
|
||||
|
||||
function getUsername(session) {
|
||||
if (typeof session === 'undefined' || typeof session.username === 'undefined') return -1;
|
||||
return session.username;
|
||||
}
|
||||
module.exports.getUsername = getUsername;
|
||||
15
backend/service-privateroom/config.js
Normal file
15
backend/service-privateroom/config.js
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
const config = {
|
||||
mongodbDatabase: 'chat',
|
||||
mongodbHost: 'mongodb://127.0.0.1:27021/',
|
||||
// mongodbHost: 'mongodb://127.0.0.1:27018/', //when commit
|
||||
charset: 'utf8',
|
||||
mongodbLogin: '',
|
||||
mongodbPassword: '',
|
||||
|
||||
mongodbPrivatedMessages: 'privatedmessages',
|
||||
mongodbConversations: 'conversations'
|
||||
};
|
||||
module.exports = config;
|
||||
|
||||
|
||||
|
||||
13
backend/service-privateroom/message.js
Normal file
13
backend/service-privateroom/message.js
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
// renvoie un message au format JSON. On a besoin de passer en paramètre
|
||||
// res, la réponse que l'on envoie au client (Angular). Le paramètre
|
||||
// data est un objet JavaScript. Globalement, cette fonction est
|
||||
// équivalente au "echo json_encode(data);" que vous utilisiez en PHP
|
||||
function sendMessage (res, data) {
|
||||
res.json ({ status: 'ok', data: data });
|
||||
}
|
||||
|
||||
function sendError (res, reason) {
|
||||
res.json ({ status: 'error', data: {reason: reason }});
|
||||
}
|
||||
|
||||
module.exports = { sendMessage, sendError };
|
||||
22
backend/service-privateroom/models/Conversation.js
Normal file
22
backend/service-privateroom/models/Conversation.js
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
const mongoose = require("mongoose");
|
||||
const config = require("../config");
|
||||
|
||||
const url = config.mongodbHost+config.mongodbDatabase;
|
||||
|
||||
mongoose.connect(url,({useNewUrlParser: true, useUnifiedTopology: true})).then( function(){
|
||||
console.log('mongodb-conversation connected '+mongoose.connection.readyState);
|
||||
}).catch(function(err){
|
||||
console.log('error : '+err);
|
||||
});
|
||||
|
||||
const ConversationSchema = new mongoose.Schema(
|
||||
{
|
||||
members: {
|
||||
type: Array
|
||||
},
|
||||
},
|
||||
{ timestamps: true },
|
||||
{ versionKey: false }
|
||||
);
|
||||
|
||||
module.exports = mongoose.model(config.mongodbConversations, ConversationSchema);
|
||||
31
backend/service-privateroom/models/Message.js
Normal file
31
backend/service-privateroom/models/Message.js
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
const mongoose = require("mongoose")
|
||||
const config = require("../config");
|
||||
|
||||
const url = config.mongodbHost+config.mongodbDatabase;
|
||||
|
||||
mongoose.connect(url,({useNewUrlParser: true, useUnifiedTopology: true})).then( function(){
|
||||
console.log('mongodb-privated-room connected '+mongoose.connection.readyState);
|
||||
}).catch(function(err){
|
||||
console.log('error : '+err);
|
||||
});
|
||||
|
||||
const MessageSchema = new mongoose.Schema(
|
||||
{
|
||||
conversationId: {
|
||||
type: String
|
||||
},
|
||||
sender: {
|
||||
type: String
|
||||
},
|
||||
text: {
|
||||
type: String
|
||||
},
|
||||
date:{
|
||||
type: Date,
|
||||
},
|
||||
},
|
||||
{ timestamps: true },
|
||||
{ versionKey: false }
|
||||
);
|
||||
|
||||
module.exports = mongoose.model(config.mongodbPrivatedMessages, MessageSchema);
|
||||
25
backend/service-privateroom/package.json
Normal file
25
backend/service-privateroom/package.json
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
{
|
||||
"name": "service-privateroom",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"body-parser": "^1.19.0",
|
||||
"cookie-parser": "^1.4.5",
|
||||
"cors": "^2.8.5",
|
||||
"express": "^4.17.1",
|
||||
"fs": "0.0.1-security",
|
||||
"jsonwebtoken": "^8.5.1",
|
||||
"mongoose": "^5.12.11",
|
||||
"socket.io": "^4.1.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"request": "^2.88.2"
|
||||
}
|
||||
}
|
||||
28
backend/service-privateroom/routes/conversations.js
Normal file
28
backend/service-privateroom/routes/conversations.js
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
const router = require("express").Router();
|
||||
const Conversation = require("../models/Conversation");
|
||||
const {sendError, sendMessage} = require ("../message");
|
||||
|
||||
// new conv
|
||||
router.post("/newConv", async (req, res) => {
|
||||
const newConversation = new Conversation({
|
||||
members: [req.body.sender, req.body.receiver]
|
||||
});
|
||||
|
||||
try{
|
||||
const savedConversation = await newConversation.save();
|
||||
sendMessage(res,savedConversation);
|
||||
}catch (err){
|
||||
sendMessage(res,err);
|
||||
}
|
||||
});
|
||||
|
||||
// get conv
|
||||
router.post("/getConv", async (req, res) => {
|
||||
try {
|
||||
const conversation = await Conversation.findOne({$or: [{members: {$eq: [req.body.sender,req.body.receiver]}},{members: {$eq: [req.body.receiver,req.body.sender]}}]},{_id:1});
|
||||
sendMessage(res,conversation);
|
||||
}catch (err){
|
||||
sendMessage(res,err);
|
||||
}
|
||||
})
|
||||
module.exports = router;
|
||||
102
backend/service-privateroom/server.js
Normal file
102
backend/service-privateroom/server.js
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
const express = require('express');
|
||||
const app = express();
|
||||
const port = process.env.PORT || 3002;
|
||||
const http = require('http');
|
||||
const { Server } = require("socket.io");
|
||||
const server = http.createServer(app);
|
||||
const io = new Server(server, {
|
||||
cors: {
|
||||
origin: "http://127.0.0.1:4200",
|
||||
methods: ["GET", "POST"],
|
||||
credentials: true
|
||||
}
|
||||
});
|
||||
|
||||
const bodyParser = require('body-parser');
|
||||
app.use(bodyParser.urlencoded({extended:true}));
|
||||
app.use(bodyParser.json());
|
||||
|
||||
const cookieParser = require('cookie-parser');
|
||||
app.use(cookieParser());
|
||||
|
||||
const cors = require('cors');
|
||||
app.use(cors({origin: 'http://127.0.0.1:4200', credentials: true}));
|
||||
|
||||
const auth = require("./auth");
|
||||
|
||||
const Conversation = require("../service-privateroom/models/Conversation");
|
||||
const Message = require("../service-privateroom/models/Message");
|
||||
const conversationRoute = require("./routes/conversations");
|
||||
app.use("/conversations", conversationRoute);
|
||||
|
||||
io.on('connection',socket => {
|
||||
|
||||
auth.getSession(socket.request, function(res){
|
||||
const getUsername = auth.getUsername(res);
|
||||
if (getUsername === -1) {
|
||||
socket.send('error','not authenticated');
|
||||
}
|
||||
else{
|
||||
//TODO apply conversations and messages
|
||||
socket.on('privateroom',function(data){
|
||||
console.log(`${getUsername} joined the chat.`);
|
||||
const sender = data.sender;
|
||||
const receiver = data.receiver;
|
||||
const date = data.date;
|
||||
const message = data.message;
|
||||
|
||||
// get conversationId
|
||||
let conversation = async () => {
|
||||
try {
|
||||
const result = await Conversation.find({
|
||||
members: {$eq: [sender, receiver]},
|
||||
});
|
||||
return result[0]["_id"];
|
||||
}catch (err){
|
||||
}
|
||||
}
|
||||
|
||||
console.log('1azd',conversation);
|
||||
|
||||
if (conversation === null){
|
||||
const newConversation = new Conversation({
|
||||
members: [sender, receiver]
|
||||
});
|
||||
let result = async () => {
|
||||
try{
|
||||
const savedConversation = await newConversation.save();
|
||||
return savedConversation;
|
||||
}catch (err){
|
||||
}
|
||||
}
|
||||
conversation = result;
|
||||
}
|
||||
console.log('2 ac',conversation);
|
||||
const conversationId = conversation["_id"];
|
||||
|
||||
|
||||
Message.insertMany([{
|
||||
conversationId: conversationId,
|
||||
sender: sender,
|
||||
text: message,
|
||||
date: date
|
||||
}
|
||||
]).then(function(){
|
||||
console.log(data, "inserted");
|
||||
socket.broadcast.emit(conversationId,[data]);
|
||||
socket.emit(conversationId,[data]);
|
||||
}).catch(function(error){
|
||||
console.log("error",error);
|
||||
});
|
||||
});
|
||||
|
||||
socket.on("disconnect", function() {
|
||||
console.log(`${getUsername} left the chat.`);
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
server.listen(port, () => {
|
||||
console.log(`listening on *:${port}/`);
|
||||
});
|
||||
Reference in a new issue