forked from sithu/cmpe273-lab2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
72 lines (60 loc) · 2.49 KB
/
index.js
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
68
69
70
71
72
var connect = require('connect');
var login = require('./login');
var app = connect();
app.use(connect.json()); // Parse JSON request body into `request.body`
app.use(connect.urlencoded()); // Parse form in request body into `request.body`
app.use(connect.cookieParser()); // Parse cookies in the request headers into `request.cookies`
app.use(connect.query()); // Parse query string into `request.query`
app.use('/', main);
function main(request, response, next) {
console.log(request);
switch (request.method) {
case 'GET': get(request, response); break;
case 'POST': post(request, response); break;
case 'DELETE': del(request, response); break;
case 'PUT': put(request, response); break;
}
};
function get(request, response) {
var cookies = request.cookies;
console.log(cookies);
if ('session_id' in cookies) {
var sid = cookies['session_id'];
if ( login.isLoggedIn(sid) ) {
response.setHeader('Content-type', 'text/html');
response.setHeader('Set-Cookie', 'session_id=' + sid);
response.end(login.hello(sid));
} else {
response.end("Invalid session_id! Please login again\n");
}
} else {
response.end("Please login via HTTP POST\n");
}
};
function post(request, response) {
// TODO: read 'name and email from the request.body'
var newSessionId = login.login(request.body.name, request.body.email);
// TODO: set new session id to the 'session_id' cookie in the response
response.setHeader('Content-type', 'text/html');
response.setHeader('Set-Cookie', 'session_id=' + newSessionId);
// replace "Logged In" response with response.end(login.hello(newSessionId));
response.end(login.hello(newSessionId));
};
function del(request, response) {
console.log("DELETE:: Logout from the server");
// TODO: remove session id via login.logout(xxx)
login.logout(request.cookies.session_id);
// No need to set session id in the response cookies since you just logged out!
response.setHeader('Content-type', 'text/html');
response.end('Logged out from the server\n');
};
function put(request, response) {
console.log("PUT:: Re-generate new seesion_id for the same user");
// TODO: refresh session id; similar to the post() function
var sessionId = login.updateId(request.cookies.session_id);
response.setHeader('Content-type', 'text/html');
response.setHeader('Set-Cookie', 'session_id=' + sessionId);
response.end("Re-freshed session id\n");
};
app.listen(8000);
console.log("Node.JS server running at 8000...");