Skip to content

Commit 1431b79

Browse files
committed
hfjh
1 parent 28733f7 commit 1431b79

File tree

6 files changed

+89
-109
lines changed

6 files changed

+89
-109
lines changed

authorization/crypt.js

+20-67
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,8 @@ export function hashPassword(password) {
1515

1616

1717

18-
export async function createChatKeyHash(key) {
19-
try {
20-
const hash = jwt.sign({ key }, CHAT_KEY, { algorithm: 'HS512' });
21-
console.log(hash)
22-
return hash;
23-
} catch (error) {
24-
console.error('Hash creation failed:', error.message);
25-
throw error;
26-
}
18+
export function createChatKeyHash() {
19+
return crypto.randomBytes(32).toString('hex');
2720
}
2821

2922
// export async function messageCryption(message,key) {
@@ -42,7 +35,7 @@ export async function createChatKeyHash(key) {
4235
export async function verifyChatKeyHash(hash) {
4336
try {
4437
const decoded = jwt.verify(hash, CHAT_KEY, { algorithms: ['HS512'] });
45-
console.log(decoded,"verifyChatKeyHash function")
38+
// console.log(decoded,"verifyChatKeyHash function")
4639
return decoded.key;
4740
} catch (error) {
4841
console.error('Hash verification failed:', error.message);
@@ -52,9 +45,9 @@ export async function verifyChatKeyHash(hash) {
5245

5346
export function verifyPassword(hashedpassword, password) {
5447
return jwt.verify(hashedpassword, PASSWORD_SECRET, (err, paswd) => {
55-
console.log("------------")
56-
console.log(paswd)
57-
console.log("------------")
48+
// console.log("------------")
49+
// console.log(paswd)
50+
// console.log("------------")
5851
if (password != paswd) {
5952
throw Error("Password didnt match")
6053
} else {
@@ -63,70 +56,30 @@ export function verifyPassword(hashedpassword, password) {
6356
})
6457
}
6558

66-
export async function encryptMessage(message, key) {
67-
const decodedToken = jwt.decode(key);
68-
69-
const keyt = crypto.createHash('sha256').update(decodedToken.key).digest('hex').slice(0, 32);
70-
71-
const iv = crypto.randomBytes(16);
72-
73-
const cipher = crypto.createCipheriv('aes-256-cbc', keyt, iv);
59+
const generateIV = () => {
60+
return crypto.randomBytes(16);
61+
};
7462

63+
export async function encryptMessage(message, key) {
64+
const iv = generateIV();
65+
const cipher = crypto.createCipheriv('aes-256-gcm', Buffer.from(key, 'hex'), iv);
7566
let encryptedMessage = cipher.update(message, 'utf-8', 'hex');
7667
encryptedMessage += cipher.final('hex');
77-
78-
return encryptedMessage;
68+
const tag = cipher.getAuthTag().toString('hex');
69+
return iv.toString('hex') + encryptedMessage + tag;
7970
}
8071

81-
// export async function encryptMessage(message, key) {
8272

83-
// console.log("my sectionn------------")
84-
// console.log(message);
85-
// console.log(key);
86-
// // Generate a random Initialization Vector (IV)
87-
// const iv = crypto.randomBytes(16);
88-
89-
// // Create a cipher with AES-256-CBC algorithm, using the key and IV
90-
// const cipher = await crypto.createCipheriv('aes-256-cbc', Buffer.from(key, 'hex'), iv);
91-
92-
// // Encrypt the message
93-
// let encryptedMessage = await cipher.update(message, 'utf-8', 'hex');
94-
// encryptedMessage += await cipher.final('hex');
95-
96-
// // Return an object containing the encrypted message and IV
97-
// return {
98-
// encryptedMessage,
99-
// iv: iv.toString('hex')
100-
// };
101-
// }
102-
103-
// export async function decryptMessage(encryptedMessage, key) {
104-
// const decipher = await crypto.createDecipheriv('aes-256-cbc', key);
105-
// let decryptedMessage =await decipher.update(encryptedMessage, 'hex', 'utf-8');
106-
// decryptedMessage += await decipher.final('utf-8');
107-
// return decryptedMessage;
108-
// }
109-
110-
export async function decryptMessage(encryptedMessage, key) {
111-
const decodedToken = jwt.decode(key);
112-
113-
// Ensure that the key has the correct length (32 bytes for AES-256-CBC)
114-
const keyt = crypto.createHash('sha256').update(decodedToken.key).digest('hex').slice(0, 32);
115-
116-
// The initialization vector should be stored or transmitted along with the encrypted message
117-
// For simplicity, assuming you have stored the iv as a hex string in the beginning of the encrypted message
73+
export const decryptMessage = (encryptedMessage, key) => {
11874
const iv = Buffer.from(encryptedMessage.slice(0, 32), 'hex');
119-
const encryptedText = encryptedMessage.slice(32);
120-
121-
// Create a decipher using the algorithm, key, and iv
122-
const decipher = crypto.createDecipheriv('aes-256-cbc', keyt, iv);
123-
124-
// Update and finalize the decipher
75+
const tag = Buffer.from(encryptedMessage.slice(-32), 'hex');
76+
const encryptedText = encryptedMessage.slice(32, -32);
77+
const decipher = crypto.createDecipheriv('aes-256-gcm', Buffer.from(key, 'hex'), iv);
78+
decipher.setAuthTag(tag);
12579
let decryptedMessage = decipher.update(encryptedText, 'hex', 'utf-8');
12680
decryptedMessage += decipher.final('utf-8');
127-
12881
return decryptedMessage;
129-
}
82+
};
13083

13184
export function generateSharedCode(userid, folderid) {
13285
const combinedString = userid.toString() + "_" + folderid.toString();

authorization/middleware.js

+2
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ export function authMiddleware(req, res, next) {
88
// const header = req.headers['authorization']
99
// const token = header && header.split(" ")[1] // "Bearer kfjkdsfjkdjfkdsjfkdsjfsdfjsdkfjs"
1010
let token = req.cookies.authToken;
11+
console.log("aaaaaaaaaaaaaaaaaaaaaaa")
12+
console.log(token);
1113
// console.log(req.cookies);
1214
// console.log(`Auth Token ${token}`)
1315

package-lock.json

+1-3
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

routers/chatRouter.js

+48-29
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { User } from "../entities/user.entity.js";
33
import { Message } from "../entities/message.entity.js";
44
import { Chat } from "../entities/chat.entity.js";
55
import crypto from "crypto";
6-
import { createChatKeyHash, encryptMessage } from "../authorization/crypt.js";
6+
import { createChatKeyHash, encryptMessage , decryptMessage } from "../authorization/crypt.js";
77
export const chat = express.Router();
88

99
////// FUNCTION
@@ -32,7 +32,7 @@ async function CheckUser(userid) {
3232
chat.post("/sendmessage", async (req, res) => {
3333
// Body{obj.receiverId, obj.content}
3434
let chatkey = null;
35-
console.log("----------------------------------------------");
35+
// console.log("----------------------------------------------");
3636
try {
3737
const obj = req.body;
3838
const currentUser = await User.findById(req.user.id).populate({
@@ -43,34 +43,34 @@ chat.post("/sendmessage", async (req, res) => {
4343
}
4444
});
4545

46-
console.log("\n");
47-
console.log(obj.receiverId);
46+
// console.log("\n");
47+
// console.log(obj.receiverId);
4848
const receiverUser = await User.findById(obj.receiverId).populate({
4949
path: 'chatList',
5050
match: {
5151
usertwo: req.user.id,
5252
}
5353
});
5454

55-
console.log("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
55+
// console.log("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
5656

5757
if (!currentUser) {
58-
console.log("Current User empty");
58+
// console.log("Current User empty");
5959
res.status(404).json({ error: 'currentUser not found' });
6060
} else if (!receiverUser) {
61-
console.log("Receiver User empty");
61+
// console.log("Receiver User empty");
6262
res.status(404).json({ error: 'currentUser not found' });
6363
}
6464

65-
console.log("current user chat list \n");
66-
console.log(currentUser.chatList.length);
65+
// console.log("current user chat list \n");
66+
// console.log(currentUser.chatList.length);
6767

6868

6969
const createAndSaveChat = async (user, receiverId) => {
7070
if (chatkey==null) {
71-
chatkey = await createChatKeyHash(crypto.randomBytes(9).toString('hex'));
72-
console.log("chatkey \n")
73-
console.log(chatkey)
71+
chatkey = createChatKeyHash();
72+
// console.log("chatkey \n")
73+
// console.log(chatkey)
7474
}
7575
const chatldata = await Chat.create({
7676
usertwo: receiverId,
@@ -91,8 +91,8 @@ chat.post("/sendmessage", async (req, res) => {
9191
currentUser.chatList = [chatListData];
9292
}
9393

94-
console.log(receiverUser.chatList.length);
95-
console.log("\nifffffffffffff\n");
94+
// console.log(receiverUser.chatList.length);
95+
// console.log("\nifffffffffffff\n");
9696

9797
if (!receiverUser.chatList || receiverUser.chatList.length === 0) {
9898
const chatListData = await createAndSaveChat(receiverUser, req.user.id);
@@ -104,6 +104,13 @@ chat.post("/sendmessage", async (req, res) => {
104104
const chatIdCurrentUser = currentUser.chatList[0].id;
105105
const chatIdReceiverUser = receiverUser.chatList[0].id;
106106
let cryptconent = await encryptMessage(obj.content,currentUser.chatList[0].chatKey);
107+
// console.log("crtype conetent------------")
108+
// console.log(cryptconent);
109+
// console.log('====================================');
110+
let decrtypy = await decryptMessage(cryptconent,currentUser.chatList[0].chatKey)
111+
// console.log("decrtypy conetent------------")
112+
// console.log(decrtypy)
113+
// console.log('====================================');
107114
const message = await Message.create({
108115
content: cryptconent,
109116
receiverId: obj.receiverId,
@@ -118,8 +125,8 @@ chat.post("/sendmessage", async (req, res) => {
118125
chat: chatIdReceiverUser
119126
});
120127

121-
console.log("\n ");
122-
console.log(receiverUser.chatList[0]);
128+
// console.log("\n ");
129+
// console.log(receiverUser.chatList[0]);
123130
currentUser.chatList[0].messages.push(message._id);
124131
receiverUser.chatList[0].messages.push(message2._id);
125132
// await Promise.all([
@@ -129,30 +136,29 @@ chat.post("/sendmessage", async (req, res) => {
129136
await currentUser.save(),
130137
await receiverUser.save()
131138

132-
console.log(receiverUser.chatList[0].messages);
133-
console.log("--------- send message section ------");
139+
// console.log(receiverUser.chatList[0].messages);
140+
// console.log("--------- send message section ------");
134141

135142
return res.status(200).send(true);
136143
} catch (error) {
137-
console.log(error);
144+
// console.log(error);
138145
return error;
139146
}
140147
});
141-
142-
143-
// Get Methods
144-
///////////////*FrontendNOT*////////////////////////////////////////////
148+
// Get Methods m///////////////*FrontendNOT*////////////////////////////////////////////
145149
// /chatmessages?page=0&receiverId=123
146150
chat.get('/chatmessages', async (req, res) => {
147151
try {
152+
153+
const myid = req.user.id
148154
const { page, receiverId } = req.query;
149-
console.log("''''''''''''''''''''")
155+
// console.log("\n ''''''''''''''''''''")
150156

151-
const limit = 10
157+
const limit = 100
152158
const skipCount = page * limit;
153159

154160
if (! await CheckUser(receiverId)) {
155-
console.log("not found user");
161+
// console.log("not found user");
156162
return res.status(404).json({ error: "not found" });
157163
}
158164

@@ -168,13 +174,26 @@ chat.get('/chatmessages', async (req, res) => {
168174
options: {
169175
limit: limit,
170176
skip: skipCount,
171-
sort: { dateTime: -1 }
177+
sort: { dateTime: 1 }
172178
}
173179
});
174180

175-
const messagesArray = mychat.flatMap(chat => chat.messages); // create 1 array
181+
//console.log(mychat)
182+
const decryptedMessages = [];
183+
184+
mychat.forEach(chat => {
185+
chat.messages.forEach(element => {
186+
let decrtpycontent = decryptMessage(element.content,chat.chatKey);
187+
element.content = decrtpycontent;
188+
decryptedMessages.push(element)
189+
});
190+
});
191+
192+
193+
194+
176195

177-
return res.status(200).json(messagesArray);
196+
return res.status(200).json(decryptedMessages);
178197
} catch (error) {
179198
console.error(error);
180199
res.status(500).json({ error: 'Internal Server Error' });

routers/userRouter.js

+6-5
Original file line numberDiff line numberDiff line change
@@ -110,17 +110,18 @@ user.post("/signup", async (req, res) => {
110110

111111
// })
112112

113-
user.get("/search",async (req,res)=>{
113+
user.get("/search", authMiddleware, async (req,res)=>{
114114
try {
115115
const search = req.query.name;
116+
let myid = req.user.id
116117
if(!search){
117118
return res.status(400).json([]);
118119
}
119-
120-
const users = await User.find({ name: { $regex: new RegExp(search, "i") } }).select('name').select('email');
121-
122-
120+
console.log("-----------------")
121+
let users = await User.find({ name: { $regex: new RegExp(search, "i") } }).select('name').select('email');
123122

123+
users = users.filter(user => user._id.toString() != myid);
124+
console.log(users);
124125
if(users&&users.length>0){
125126
return res.status(200).json(users)
126127
}

server.js

+12-5
Original file line numberDiff line numberDiff line change
@@ -45,19 +45,26 @@ const app = createServer(server)
4545
const io = new Server(app,{
4646
cookie: true,
4747
cors: {
48-
origin: "http://localhost:3000",
48+
origin: "http://localhost:4003",
4949
credentials:true
5050
}
5151
})
5252

5353
io.on('connection', (socket) => {
54+
console.log(socket.id);
55+
socket.on('chat-message', (msg) => {
56+
console.log("Msg",msg);
57+
io.emit('chat-message', msg);
58+
});
59+
60+
5461

5562

5663

5764
socket.on('token', (data) => {
58-
Console.log("--------------TOKEN_Section----------------")
59-
const token = data.token;
60-
console.log(token);
65+
// Console.log("--------------TOKEN_Section----------------")
66+
// const token = data.token;
67+
// console.log(token);
6168

6269
});
6370
});
@@ -78,7 +85,7 @@ server.disable("x-powered-by")
7885
server.use(cors(corsOptions));
7986
server.use(express.urlencoded({extended: false}))
8087
server.use(express.json())
81-
server.use(rateConfig)
88+
// server.use(rateConfig)
8289
server.use(upload.single("file"))
8390
server.use("/chat", authMiddleware);
8491

0 commit comments

Comments
 (0)