forked from shimondoodkin/nodejs-mongodb-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
basicapp_extend_request.js
executable file
·84 lines (75 loc) · 1.88 KB
/
basicapp_extend_request.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
73
74
75
76
77
78
79
80
81
82
83
84
this.main=function(app)
{
var cookie = {
req:null,
get:function() {
var req = this.req;
return (req.headers.cookie ? this.parse(req.headers.cookie) : {});
},
parse:function(str) {
var obj = {},
pairs = str.split(/[;,] */);
for (var i = 0, len = pairs.length; i < len; ++i) {
var pair = pairs[i],
eqlIndex = pair.indexOf('='),
key = pair.substr(0, eqlIndex).trim().toLowerCase(),
val = pair.substr(++eqlIndex, pair.length).trim();
// Quoted values
if (val[0] === '"') {
val = val.slice(1, -1);
}
// Only assign once
if (obj[key] === undefined) {
//obj[key] = querystring.unescape(val, true);
obj[key] = val;
}
}
return obj;
}
};
function getuser(callback){
var req = this;
data = req.cookie.get();
if (data.user_id){
data.user_id = app.ObjectID.createFromHexString(data.user_id);
app.models.t2_users.getall({_id:data.user_id} , function(result){
if (result.length>0){
req.user = result[0];
callback(req.user);
} else {
callback(false);
}
});
} else {
callback(false);
}
}
function redirect(res, url, callback, code ) {
res.writeHead( code || 302, {'Location': url } );
res.end();
if(callback)callback();
};
function query_to_string(query){
var query_string = '';
var prefix = '?';
for (var name in query){
query_string+= prefix + name + '=' + query[name];
prefix = '&';
}
return query_string;
}
app.extendrequest=function (req)
{
req.cookie = cookie;
req.cookie.req = req;
req.user = null;
req.getuser = getuser;
req.redirect = redirect;
req.query_to_string = query_to_string;
/*
req.sessions={}
req.sessions.req=req;
req.sessions.save=session.save;
*/
};
}