-
Notifications
You must be signed in to change notification settings - Fork 0
/
server-part.js
105 lines (90 loc) · 3.14 KB
/
server-part.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// This function implements anonymous creation logic.
//https://gist.github.com/nleush/2654061
function loadOrCreateAnonymousProfile(req, res, next) {
var sess = req.session,
auth = sess && sess.auth;
if (!auth || !auth.userId) {
dbCounter('anonymousUsers', function(err, counter) {
if (err) {
console.log('Error getting anonymous users counter', err);
next();
return;
}
User.create({
login: "User " + counter,
is_anonymous: true
}, function (err, user) {
if (err) {
console.log("Error creating anonymous", err);
} else {
var _auth = sess.auth || (sess.auth = {});
_auth.userId = user.id;
_auth.loggedIn = true;
}
next();
});
});
} else {
next();
}
}
// The rest is usual setup.
// Counters.
var CounterSchema = new Schema({
next: Number
});
CounterSchema.statics.findAndModify = function (query, sort, doc, options, callback) {
return this.collection.findAndModify(query, sort, doc, options, callback);
};
var Counter = mongoose.model('Counter', CounterSchema);
function dbCounter(name, cb) {
var ret = Counter.findAndModify({_id:name}, [], {$inc : {next:1}}, {"new":true, upsert:true}, function(err, data) {
if (err) {
cb(err);
} else {
cb(null, data.next);
}
});
}
// User.
var UserSchema = new Schema({
is_anonymous: {'type': Boolean, 'default': false}
});
var User;
UserSchema.plugin(mongooseAuth, {
everymodule: {
everyauth: {
User: function () {
return User;
}
}
},
password: {
everyauth: {
getLoginPath: '/signin',
postLoginPath: '/signin',
loginView: 'signin.jade',
getRegisterPath: '/signup',
postRegisterPath: '/signup',
registerView: 'signup.jade',
loginSuccessRedirect: '/',
registerSuccessRedirect: '/'
}
}
});
mongoose.model('User', UserSchema);
User = mongoose.model('User');
// Express server create.
var app = exports.app = express.createServer();
// Express server configure.
app.configure(function() {
app.use(express.cookieParser('secret'))
.use(express.session({
secret: 'secret',
cookie: {maxAge: 60000 * 60 * 24 * 30}, // Month
store: new mongoStore({db: mongoose.connection.db})
}))
.use(express.bodyParser())
.use(loadOrCreateAnonymousProfile) // Should be placed before auth middleware.
.use(mongooseAuth.middleware()); // Anonymous user loaded here.
});