-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmiddleware.js
More file actions
67 lines (56 loc) · 1.48 KB
/
middleware.js
File metadata and controls
67 lines (56 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Middleware for Campus Bridge application
// Simple in-memory session store (in production, use a proper session store like Redis)
const sessions = new Map();
// Generate a random session ID
function generateSessionId() {
return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
}
// Middleware to check if user is authenticated
function requireAuth(req, res, next) {
const sessionId = req.headers['x-session-id'] || req.query.sessionId;
if (!sessionId) {
return res.status(401).json({
success: false,
message: 'Authentication required'
});
}
const session = sessions.get(sessionId);
if (!session) {
return res.status(401).json({
success: false,
message: 'Invalid session'
});
}
// Attach user info to request
req.user = session.user;
next();
}
// Create a new session for a user
function createSession(user) {
const sessionId = generateSessionId();
const session = {
user: {
id: user.id,
name: user.name,
email: user.email
},
createdAt: new Date()
};
sessions.set(sessionId, session);
return sessionId;
}
// Destroy a session
function destroySession(sessionId) {
sessions.delete(sessionId);
}
// Get user info from session
function getUserFromSession(sessionId) {
const session = sessions.get(sessionId);
return session ? session.user : null;
}
module.exports = {
requireAuth,
createSession,
destroySession,
getUserFromSession
};